I trying consume service with phonegap and android.
My service using localhost return the json with chrome:
{
"GetListaMunicipiosResult": [{
"MunicipioID": "1",
"MunicipioNome": "Florianópolis",
"MunicipioUf":"SC"
}, {
"MunicipioID": "2",
"MunicipioNome": "Jaraguá do Sul",
"MunicipioUf": "SC"
}]
}
In my .js file, I call the GET json with the code:
$('#cidades_page').live('pageshow',function(event){
$.ajax("http://10.0.2.2:56976/MunicipiosService.svc/ListaMunicipios",{
beforeSend: function (xhr) {
$.mobile.showPageLoadingMsg();
alert("beforeSend");
},
complete: function () {
// $.mobile.hidePageLoadingMsg();
alert("complete");
},
contentType: "application/json",
dataType: "jsonp",
jsonp: "callback",
type: "GET",
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
//alert(thrownError);
},
success: function (data) {
alert(JSON.stringify(data));
}
});
});
But when page show, only alert alert("beforeSend") fired, and after nothing happens.
I insert the json call in html using $.ajax(.... and open with chrome and its work. I do not know what else to do.
thanks for help
EDIT
I test in windows phone and now i can get error Error:GetListaMunicipios was not called.
My .js:
$.ajax("http://localhost:56976/MunicipiosService.svc/ListaMunicipios?callback=?",{
beforeSend: function (xhr) {
// $.mobile.showPageLoadingMsg();
alert('beforeSend');
},
complete: function () {
// $.mobile.hidePageLoadingMsg();
alert('complete');
},
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
crossDomain: true,
jsonp: 'callback',
jsonpCallback:'GetListaMunicipios',
type: 'GET',
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
},
success: function (data) {
alert('success');
}
});
My WCF Service
namespace GuiaService
{
[ServiceContract]
public interface IMunicipiosService
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "ListaMunicipios")]
List<ClsListaMunicipios> GetListaMunicipios();
}
}
thanks for help.
You should use done, fail and always.
success, error and complete are deprecated.
Update: as noted in the comments, this isn't true for how you're using it. I now believe the problem is because you're using jsonp as the type instead of json.
jsonp is designed to call a function automatically when loaded, so your server should be adding a function call to the generated code. It's possible that jQuery expects this behaviour and disables its own callbacks, or uses the jsonp mechanism to trigger its own callbacks, but since your server doesn't actually add the function call, nothing happens.
Related
Ajax request not sending on android studio with cordova. I tried a simple request to google but it does not work either.
What i already tried :
- Change minSdk to 23
- Add cordova whitelist plugin and permissions for https and http in config.xml
- add android:usesCleartextTraffic="true" in AndroidManifest
- i have nothing in my network profiler but ajax return a timeout error
- Outside my app, my request work
Code
$.ajax({
type: "POST",
url: OAUTH2_URL,
cache : false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', make_base_auth($("#login").val(), $("#pwd").val()));
},
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: json,
timeout: 5000,
success: function (data) {
etape3(data);
},
error: function (xhr, ajaxOptions, thrownError){
SpinnerPlugin.activityStop();
navigator.notification.confirm(
'login or password incorrect.', // message
null, // callback
'Error', // title
['Ok'] // buttonName
);
}
})
I don't know what else to do
Thanks !
I am developing Android application using PhoneGap. I am trying to execute simple login module, it works fine in web browser. But when it comes to apk, its not working. It is not able to post request to Restful API.
var usr = $('#email_address').val();
var pass = $('#password').val();
if(usr != '' && pass != ''){
alert("Before Calling Method");
$.ajax({
url:APIURL +"api/sample/sample123",
type: "POST",
crossDomain : true,
data: {username:usr,password:pass},
dataType: "json",
success: function(data){ /*Here I am posting some dummy code, I can't show original code*/
var response = eval(data);
alert(response.response);
}
});
When I am executing this on android phone, I am getting only first alert above i.e "Before Calling Method" but it is not showing another alert. I have configured res/xml/cordova.xml as
<access uri="*" subdomains="true"/>
Also I have referred some previous related doubts from StackOverflow. But It didn't helped me. Please help me to, I am waiting for positive response...
try this one
formData = {
username: $('#email_address').val(),
password: $('#password').val()
}
$.ajax({
url: APIURL + "api/sample/sample123",
type: "POST",
crossDomain: true,
contentType: 'application/json',
data: formData,
dataType: "json",
success: function(data) {
alert(data);
}
});
I am a newbie to phonegap. I m stuck. I m unable to get result while calling webservice in phone gap. I used both Ajax and getJSON Method. Getting result as undefined, RealData variable as undefined. I am feeling that I am missing something. Please help guys.
Here is my code....
function onDeviceReady() {
console.log("Device is Ready111111");
alert("alert Device ready");
/*var jqxhr = $
.getJSON(
'http://www.infoline.in/mobdata.aspx?
reqfor=area_list&city=ahmedabad',
function() {
console.log("Device is Ready111111....."+jqxhr);
alert('success');
}).error(function() {
alert('error');
});*/
$(document).ready(function () {
$.ajax({
url: "http://www.infoline.in/mobdata.aspx",
data: {
"reqfor": "area_list",
"city": "ahmedabad"
},
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg, textStatus, jqXHR) {
alert(textStatus);
var theRealData = msg.d;
alert(theRealData.length)
}
});
});
In order to view the Object you have to convert the msg into a string.
try this:
console.log(JSON.stringify(msg));
Here is my problem. When my Home page shows, I call the LoadUser function, which on success sets the globalUser variable with the returned JSON. After it loads I call the alert function but it says globalUser is undefined. I have tried many other workarounds, but I always get the undefined message.
If I call the alert(globalUser); on the success function, it works as expected alerting the object.
$('#Home').live('pageshow', function(event) {
$.when(LoadUser()).done(function(a1) {
alert(globalUser);
});
});
function LoadUser() {
$.ajax({
// connects with the web service and validate de user input
url: "http://localhost:51396/Icademy.asmx/GetUser",
contentType: "application/json; charset=utf-8",
data: { "userName": "'rodrigo'" },
dataType: "jsonp",
success: function(json) {
globalUser = JSON.parse(json.d);
return globalUser;
},
error: function(ret) {
alert("Um erro ocorreu, tente novamente mais tarde.");
}
});
}
You don't need to bother you with $.when in your case, just implement $.ajax in your pageshow event
$('#Home').live('pageshow', function(event) {
$.ajax({
// connects with the web service and validate de user input
url: "http://localhost:51396/Icademy.asmx/GetUser",
contentType: "application/json; charset=utf-8",
data: { "userName": "'rodrigo'" },
dataType: "jsonp",
success: function(json) {
globalUser = JSON.parse(json.d);
alert(globalUser)
},
error: function(ret) {
alert("Um erro ocorreu, tente novamente mais tarde.");
}
});
});
I don't see why you don't do everything within the success function. As you say yourself, that works. Plus, you have the benefit of being able to run the code on success. In your example, if there was a problem with the ajax call, yo'd show the "error occurred" alert, but then your when() code would assume success.
With all that being said...
You obviously realize the asynchronous nature of ajax, but you're solving it incorrectly with the .when().done(). LoadUser() returns immediately and it returns null, not a deferred. As such, .done() is probably firing immediately.
The solution is to replace .when(LoadUser()) with .when($.ajax()) as in the example, or return the result of $.ajax (ie, the deferred object) from LoadUser().
I'm trying to develop an application on phonegap on Android.
What I'm trying to do is call a webservice from my application, this will be used for data access.
I found many sheets online on how to do this, and the simplest one I could find that seems straight forward goes like this
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://www.webservicex.net/stockquote.asmx/GetQuote",
data: "{'usd'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Insert the returned HTML into the <div>.
$('#Content').html(msg.d);
}
});
});
However, All I can see is the text I had already put into the div, the div contents do not change. I'm testing on a Galaxy SIII device directly, not on a simulator.
My guess is that nothing seems to happen because you are getting a fail, not a success. try adding an error handler and see what happens.
.fail(function() { alert("error"); })
You are likely having 'cross domain' issues (because you are trying to get ajax from a different domain) and may need to use JSONP instead of JSON for your dataType. For more info about JSONP, see this post or the docs
EDIT:
Here is a fiddle of this code in action.
$(document).ready(function() {
//here is one way using the 'error' handler
$.ajax({
type: "POST",
url: "/failOnPurpose",
data: "{'usd'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
error:function(jqXHR, textStatus) {
alert("error:" + textStatus);
},
success: function(msg) {
// Insert the returned HTML into the <div>.
$('#Content').html(msg.d);
}
});
//here is another way using the 'fail' request handler
$.ajax({
type: "POST",
url: "/failOnPurpose",
data: "{'usd'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Insert the returned HTML into the <div>.
$('#Content').html(msg.d);
}
}).fail(function(jqXHR, textStatus) {
alert( "fail: " + textStatus );
});
});