I have literally lost hair over the last 2 and a half days i've spent on this problem...
Using phonegap to build an app for iPhone and Android. Cross domain ajax works in my browser and also on iPhone. it will NOT work on Android.
I have not been using jQueryMobile, just jQuery, until i read somewhere that i should be using the mobile version to get cross domain to work on android. So i've changed up the project to suit jMobile. Do i really need to use JqueryMobile in order to get cross domain ajax working?? i would much rather not use it if possible.
tried changing things like $.mobile.allowCrossDomainPages=true; $.support.cors = true; to no avail. I'm at a loss. Please help me out
Heres my ajax code
$.ajax({
url: 'URL',
type: 'GET',
contentType: "application/json",
dataType: 'jsonp',
jsonp: 'jsoncallback',
success: function(response){
console.log("inside ajax");
$.each(response, function(i,item){
var category = "<div class='icon-text'><a class='ajaxify' href='pages/onlineRecipe.html' onclick='$(setOnlineID("+item.id+"))' >"
+"<p><img alt='Image-alt' width='64' class='wrap-around' id='img"+item.id+"' />"
+"<strong>"+item.title+"</strong>"
+"<br/>"+item.desc+"</p></a></div>";
$('#categories').append(category);
var img = "#img" + item.id;
$(img).attr('src', "data:image/png;base64,"+item.image);
//other bindings
App.ajaxLinkify($("a.ajaxify"));
App.addTouchEvents($(".page"));
});
},
error: function(xhs, status, error){
//output.text('Ha producido un error cargando el dato. Por favor, intèntalo de nuevo.');
console.log("Ajax not working");
}
});
My suggestion would be to check <access origin="http://www.example.com" /> in res/xml/config.xml (cordova 2.3)
Try adding this jQuery.support.cors = true;
oh and one other tip, just incase it's caching a previous bad call add this to your ajax
cache: false,
need to add this to corresponding php file: header("Access-Control-Allow-Origin: *");
Related
I'm sending an Jquery.Ajax request to a server which is hosting a .asmx web service.
jQuery.ajax({
type: 'GET',
url: 'http://IP-destination/myFolder/WebService.asmx/LogonUser',
cache: 'true',
data: {
'username':get_cookie('username'),
'password':get_cookie('password'),
'environment':get_cookie('environment')
},
dataType: 'jsonp',
beforeSend: function(){$.mobile.loading('show', 'a', 'Laddar...', false); alert("go");},
error: function(a, b, c){
$.mobile.loading('hide','a');
alert(a + b+ c);
},
success: function(response){
$.mobile.loading('hide','a');
alert("success");
self.loginUser_cb(response);
}
});
While sending data through my browser, emulator or "Legacy Hybrid build (Intel XDK) for android" everything works great.
But when I use Cordova (still android, works on IOS) the request get an "500 Internal Server Error".
It seems like my URL is missing my data parameters:
http://oi60.tinypic.com/21jvb5y.jpg
When I use my browser the URL is correct with the data parameter in the end of the url: /LogonUser?callback=jQuery19105695250731240461_1425028837473&username=MyUserName&password=Secret&environment=Dev
My question is: What could possibly cause this in Cordova Android but work great
in the emulator/ios/Hybrid Legacy build? The URL seem to be cut short.
I'd look to simplify things as much as possible and see if the get_cookie portion is failing for you. Try removing that and using static values. If it works, it means your cookies may not exist as you think they should and you should write logic to handle that.
I'am develoing a VB.NET MVC4 Web App using Android's webView to run it.
I have the next problem: When i make an ajax PUT request to my own controllers method, i recieve a 404 status code.
In the other hand, when i make a get or post petition, works fine. ¿Any idea?
$.ajax({
type: 'PUT',
url: 'myurl',
data: data,
success: function (json, textStatus) {
alert(json);
},
error: function (jqXHR) {
alert('error');
}
});
jqXHR.readystate = 4
jqXHR.message = server error file or directory not found
jqXHR,status: 404
EDIT: IIS is configured to work with PUT and DELETE and thanks to that it works correctly in the browser but not with the Androids WebView.
Your code is missing a quote url: 'myurl needs a ' on the end
$.ajax({
type: 'PUT',
url: 'myurl',
data: data,
success: function (json, textStatus) {
alert(json);
},
error: function (jqXHR) {
alert('error');
}
});
This might be an error in your example but that's all we can see to correct the other things to check is IIS Setup of the site does is it set to allow PUT, DELETE ect
GET & POST are standard and are enabled by default.
So please follow the answer to this question:
How do I enable HTTP PUT and DELETE for ASP.NET MVC in IIS?
I'm developing a mobile application based on PhoneGap. I need to use AJAX, I'm working with jQuery.
I'm trying to get a JSON from a WS on PHP with CORS, but I get an error, and the error message is empty. I tested the code in a Web Browser and it works. But, when I used it with PhoneGap it did not worked. I tested my code in PhoneGAp with Fecebook WS and it works. This is the combination that I tested:
Test 1
Source: file:///C:/.../index.html (Web Browser)
WebService: http: //localhost/.../getemployees.php
Result: it works
Test 2
Source: PhoneGap
WebService: http: //localhost/.../getemployees.php
Result: it does not works
Test 3
Source: PhoneGap
WebService: https: //graph.facebook.com/OldemarshCr
Result: it works
This is the code:
$.getJSON(url, function (data) {console.log(data);})
.success(function() { console.log("second success"); })
.error(function(jqXHR, textStatus, errorThrown) {
console.log('******* '+"error: " + textStatus+' *******');
});
This is the JSON response:
{"items":[{"id":"10","firstName":"Kathleen","lastName":"Byrne","title":"Sales Representative","picture":"kathleen_byrne.jpg","reportCount":"0"},{"id":"9","firstName":"Gary","lastName":"Donovan","title":"Marketing","picture":"gary_donovan.jpg","reportCount":"0"},{"id":"7","firstName":"Paula","lastName":"Gates","title":"Software Architect","picture":"paula_gates.jpg","reportCount":"0"]}
Thanks,
In ajax call, try and add
$.ajax({
crossDomain: true,
xhrFields: {withCredentials: true}
});
$.ajax did not work... this is the error that I get
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
I tested the code on web browser and it worked.
This is the code:
$.ajax({
crossDomain: true,
xhrFields: {withCredentials: true},
type: 'GET',
url: url,
dataType: 'json',
success: function(response){ console.log(response); }
error: function(error){ console.log('Error: '+error); }
});
Thanks,
Good News!!
I solved the problem. Both methods, getJSON and ajax, are working, the problem was the server.
When I accessed the Web Services from a external server (not localhost) it worked.
Thanks,
I've been on this now for three days, and I've tried pretty much every piece of alternative code and fixes to no avail.
Here's the code, taken from bog-standard jQuery examples:
$.ajax({
url: "http://api.wunderground.com/api/4213a68e7f20c998/geolookup/conditions/forecast/q/Australia/Noarlunga.json",
dataType: "jsonp",
success: function(parsed_json) {
alert("YEP!");
var loc = parsed_json['response'];
var weather = "Location: " + parsed_json.location.city + "<br />";
weather += "Wind: " + parsed_json.current_observation.wind_dir + " ";
weather += parsed_json.current_observation.wind_mph + "-" + parsed_json.current_observation.wind_gust_mph + " knts";
$("#info").html(weather);
}
});
and here's some config that lots of people suggested ( which did nothing )
$( document ).bind( "mobileinit", function() {
// Make your jQuery Mobile framework configuration changes here!
$.mobile.allowCrossDomainPages = true;
$.mobile.ajaxEnabled = true;
$.mobile.pushStateEnabled = false;
$.mobile.allowCrossDomainPages = true;
});
In addition, I have:
added <uses-permission android:name="android.permission.INTERNET" /> to the AndroidManifest.xml file
tested the json request URL in the browser on the same target ( works fine )
tested the page in FireFox / Chrome ( works fine )
tried the app on my Galaxy s2 over 3G ( UI all works fine but ajax request STILL fails )
Note this isn't the complete code, but it's just sitting in a standard phonegap deviceready listener event function wrapped in a standard .ready() function.
The fact this fails on my phone AND the SDK would seem to indicate a phonegap / Eclipse issue, and not a connection / permission issue.
I am trying to deploy to an Android 2.3 AVD, using the Android SDK. I haven't tried deploying to an Android 4 AVD yet.
I'd love it if anyone knows what the problem is because I've run out of suggestions to try!
If precondition is that you could modify php code on server..
Try this so you could test either in local browser or on mobile WITHOUT JSONP
1.Follow instruction of jQueryMobile website, which explains well how to make it work with phonegap (http://jquerymobile.com/test/docs/pages/phonegap.html)
In your <script></script> area, add
$(document).on("mobileinit", function(){
//apply overrides here
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
});
your ajax could be
$.ajax({
type: "GET",
url: "http://xx.xx.xx.xx/xxx/xx.php"
}).done(function( msg ) {
alert(msg);
//refresh the content
$( '.ui-content' ).load( 'xx/xx.html', function () {$(this).trigger('create') });
});
2.Your php is something like this:
<?php
header('Access-Control-Allow-Origin: *');//for local browser test
$test='[{"name":"aa","address":"aa"}, {"name":"bb","address":"bb"}]';
echo $test;
?>
in
$( document ).bind( "mobileinit", function()
add
$.support.cors = true.
:)
I tried lots of combinations and the thing that finally worked was adding the following to my index.html. The key thing is making sure it's loaded before you load jquerymobile (if you're using that). It won't work if it is loaded anywhere after that.
<script type="text/javascript">
$(document).bind("mobileinit", function() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
});
</script>
I have the following Problem. In the Phonegap App(for Android) I want to make an AJAX-Call to connect with a Sharepoint Server, with the following Code:
$.ajax({
url:"https://xxx/_vti_bin/lists.asmx",
beforeSend: function( xhr ){
xhr.setRequestHeader(
"SOAPAction",
"http://schemas.microsoft.com/sharepoint/soap/GetListCollection"
);
xhr.setRequestHeader("Content-Type","text/xml; charset=utf-8");
},
dataType:"xml",
contentType: "application/xml; charset=utf-8",
timeout:10000,
type:'POST',
cache: false,
username: "username",
password: "password",
data: soapEnv,
success:function(data) {
// alert data
var serializer = new XMLSerializer();
serialized = serializer.serializeToString(data);
alert(serialized);
},
error:function(XMLHttpRequest,textStatus, errorThrown) {
// alert errors
alert("Error status :"+textStatus);
alert("Error type :"+errorThrown);
alert("Error message :"+XMLHttpRequest.responseXML);
alert("Error statustext :"+XMLHttpRequest.statusText);
alert("Error request status :"+XMLHttpRequest.status);
},
complete: function(jqXHR, textStatus){
alert(textStatus);
}
});
When I try to run it on the Android Emulator the error messages are:
Error status: error
Error type:
Error message: undefined
Error statustext: error
Error request status: 0
However when I try to run it on my Browser (Chrome) with disabled websecurity (because of same origin policy) it works all fine. Phonegap normally shouldn't care about SOP because of the file:/// Protocol. I added the following to 'mobileinit':
$(document).bind("mobileinit", function() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
});
But when I run the same Code in Chrome without websecurity disabled, I get exactly the same errors as in the Android Emulator.
I also tried an AJAX call to wikipedia (with html instead of xml, and GET instead of POST), and that worked without a problem.
Also I think the AJAX to Sharepoint doesn't even get fired (no traffic in Fiddler2, if I managed to configure it the right way)
So I am really stuck with this problem since 2 days now, if anyone knows how to make this ajax call work, it would made me so happy :-)
(soapEnv is the XML envelope, sent to the server)
Well I know that once upon a time jQuery had a bug where it treated a request status of 0 as an error. When running from the file protocol a status of 0 is the same this as a 200 (OK). You may need to update your version of jQuery.
Alternatively to test my theory just do a plain vanilla XHR request to your service to see if it works. Here is my stock example:
http://simonmacdonald.blogspot.com/2011/12/on-third-day-of-phonegapping-getting.html