JQuery Mobile + Phonegap : $.ajax calls not working - javascript

I was searching around for solution but failed all the way. The following codes are working fine under JQuery 1.4.4, JQuery Mobile 1.0a2 and PhoneGap 0.9. However, when I transferred it to JQuery 1.7.1, JQuery Mobile 1.1.0 and PhoneGap 1.5; it keeps on fall under error. I tracked the http call through Fiddler and realized the ajax does call to the URL but why it will fall under error instead of success? Please help!
$.ajax({
type: "GET",
cache: false,
url: updateServer+'update.xml',
dataType: "xml",
error: function(xhr, settings, exception){
alert('The update server could not be contacted.');
},
success: function(xml){
// success code
}
});

make sure that you can access the web service from the emulator itself and have allowed the application to access internet connection.
to do this, from within the emulator, open the default browser and enter the URL. it should not give you a 404 or any exception.

I had this problem with Phonegap 1.5. Downgrading to Phonegap 1.4.1 solved the problem. I was frustrated for days on end and couldn't make sense of the issue.

jQuery Mobile has a whole page in the documentation about implementing with PhoneGap. Check it out here.
http://jquerymobile.com/test/docs/pages/phonegap.html
You have to set permissions to allow cross-domain ajax calls.
Also! Remember to change your code in your html files if you are porting over from a web app. It is likely you made get calls to url "../api/handler.php" or something. You need to make all those calls absolute for use in PhoneGap. "http://mydomain.com/api/handler.php"

Ok, I figure the issue is actually the URL itself. The URL address is valid as it is accessible but it doesn't belong to the same domain. For example, my html file with the JQuery resides in http://www.yahoo.com/index.html but the URL which I am trying to call is http://www.google.com.
Browser prevents making an ajax call from a page hosted on one domain to a page hosted on a different domain (same origin policy) due to security issue. My solution here is to use a php file to retrieve the relevant data from another domain while the html (with JQuery) is calling the php file as follow:
$.ajax({
type: "GET",
cache: false,
url: 'getcontent.xml',
dataType: "xml",
error: function(xhr, settings, exception){
alert('The update server could not be contacted.');
},
success: function(xml){
// success code
}
});
Thank you for all the given helps!

Related

Calling RESTFUL service from JQuery

I am trying to call a resource from a server using REST, the Restful Service is on another server.
When i run the script below i get XMLHttpRequest cannot load file:///C:/xampp/htdocs/Rest_Client/application/views/www.creadevz.com/Restful_Server/index.php/api/Example/users/. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
<script>
document.write('Started');
jQuery.ajax({
type: "GET",
url: "www.creadevz.com/Restful_Server/index.php/api/Example/users/",
dataType: "json",
crossDomain: true,
success: function(html){
document.write('success');
document.write(html);
}
});
</script>
I have 2 Questions:
1- Why did it append file:///c:/xampp/htdocs/Rest_Client/application/views
2- how to over come the cross domain resource access restrictions.
Extra information:
1- I am using CodeIgniter with Philip Sturgeon's REST server.
2- I followed the Philip Sturgeon's tutorial and used the Example api supplied with the framework
3- I used hurl.it to test the api and it worked fine.
Solutions I have found:
1- CORS
2- JSONP
Most opinions online suggest CORS over JSONP but i am not sure how to implement it in an efficient way, also since hurl.it called the api perfectly there must be a way they are over coming the cross domain resource access restrictions without the CORS Headers.
Thanks in Advance for your help
Edit:
I failed to mention that this is done with the purpose of using it with Phonegap
In an attempt to use the CORS Headers efficiently i added it at the start of the response function in Rest_Controller.php
To answer you first question
please correct is url ,it shoud have "http://" now your code will look like this .
<script>
document.write('Started');
jQuery.ajax({
type: "GET",
url: "http://www.creadevz.com/Restful_Server/index.php/api/Example/users/",
dataType: "json",
crossDomain: true,
success: function(html){
document.write('success');
document.write(html);
}
});
</script>
This will now not append append file:///c:/xampp/htdocs/Rest_Client/application/views
It's simple, if you are working on chrome, you can install this plugin , it works for me. I hope that works for you.
Good luck

Submitting POST request from Cordova app to Google App Engine not reaching server at all

I have a Cordova app (HTML/Javascript-files wrapped into iOS WebView) which is exhibiting some weird behaviour.
I submit forms to a python-script on Google App Engine, and this works sometimes, but not all the time. When the form includes base64 encodes images, it is more likely that the it won't work.
What I mean with not working is that it doesn't reach the server at all. The server logs show that no request to the "/submit"-handler has been made. This is only for the iOS-version of the app. The Android-version works fine with the same code.
My biggest suspicions was the cross-domain issue. Here's my jQuery code which sends the form:
$.ajax({
type: 'POST',
url: "http://myapp.appspot.com/submit",
data: submittedEntryString,
crossDomain: true,
cache: false
}).done(function(data) {
console.log(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
console.log(jqXHR.responseText);
});
However I have added the header to my response. I suppose this is the correct way to do it(?)
self.response.headers['Access-Control-Allow-Origin'] = '*'
self.write("form submitted! form id is: " + str(s.form_id))
Any ideas what would cause this kind of behaviour?
The cross domain issue only occurs when you test your app code on PC browser after code below is inserted into config.xml.
<access origin="*" />
Anyway, your code seems to be correct.
My suggestion is that you could try the steps below.
(1) Not post your image and check if text data could be posted well.
(2) Use phonegap "Filetransfer" to post data includes images.

How can I run ajax code without web server?

I am running ajax without a server on my system, I have created one index.html with this.
JavaScript function:
function do_the_click(url)
{
alert('inside this method do_the_click');
$.ajax({
async: false,
url : url,
contentType: "text/html",
type : "GET",
dataType : "text/html",
success: function(data){
alert('data');
}});
}
My HTML body content is:
<a href="Java Collections.html" class="button" id="javacollections" onclick="do_the_click('this.href');"/>Java Collections</a>
I'm able to get the this message in alert window inside this method do_the_click but am not able to get the data in alert window, and so not able to get the page Java Collections.html in the index.html,
I have searched very much on Google re. how to load the data locally without using server in jquery.ajax but I didn't find any good solution, so I think that its good for others as well if it resides on Stack overflow.
You cannot do such thing. if you dont have a server you cannot send ajax it will be a cross browser issue. as the others says ajax will not work with file:// protocol you need a server to make an http:// call that ajax supports.
When you are making AJAX requests using stand alone html files, the HTTP request to the url is made by the browser. All you need to make sure is that you have included JQuery. Here is what you have to do.
Include Jquery:
<script src="js/jquery-1.10.2.min.js"></script>
The JQuery here resides in the js folder. This is included in the stand alone html file. Now to make the AJAX request use the following code.
$.ajax({
type: 'GET',
url: url,
success: function(data){
console.log(data);
},
async:false
});
AJAX creates an HTTP request that must be responded to by a server. If you don't have a server you can't use an AJAX request. You can run a server on your computer, but this is not the same as getting a file from the local filesystem.
I m able to run the ajax without webserver the problem was with my code the code written below that i had run on my filesystem u can use that as well.
function do_the_click(brl)
{
alert('inside this method do_the_click');
alert(brl);
var request = $.ajax({
async: false,
url: brl,
contentType: "text/html",
type : "GET",
dataType : "html",
});
request.done(function( msg ) {
alert(msg);
$( "#contentarea" ).load( msg, function() {
alert( "Load was performed." );
});
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
Java Collections
You won't be able to do this. If you don't have a server, you will violate the browser's cross-domain policy, as you won't have a domain!
AJAX won't work via the filesystem, you need a server.
This is an older thread but a browser doesn't need to run on a common OS like OSX/Windows/etc .. many people today are making their own browsers from WPE/Wayland or QT5Webkit where same origin policies don't apply.
Now in current scenario it depends upon where your server at. If the server is some place else, it will require CORS (cross origin request). So using file:// with CORS works perfectly.
I came to this question because I was searching for the reason, why I am able to make ajax request without using a web server. Got the answer Thanks!

Ajax call on phonegap not sending request

I am pulling my hair out on this one.
I have a jquery ajax call to my server that works on my browser, it works on my device when I have it connected to my local proxy for http sniffing, but just hangs when it's off my proxy on the wifi or on the cell network.
I've set up the phonegap config.xml to allow my domain. The request is a get on the server as well as the ajax call. You'll notice it's jsonP.
The call is straight forward jquery, I'll post the code anyway. The api object is a custom object I made to hold the application's functionality.
var dfd = $.ajax({
url: myurl, // I've confirmed the url, but prefer to keep it private
data: {
ApplicationID: api.applicationID,
DeviceID: api.device.uuid(),
OSVersion: api.device.version(),
DeviceVersion: api.device.platform(),
Lat: lat,
Lng: lng,
Bearing: bearing
},
dataType: "jsonp",
timeout: 30000
})
.fail(function (event, jqXHR, ajaxSettings, thrownError) {
console.error(jqXHR);
});
I've tried this answer, the closest I could find to my problem, but it doesn't seem to work.
Phonegap jQuery ajax request does not work
Is there something I'm missing? What am I doing wrong?
EDIT:
I forgot to mention, the timeout I have set on the ajax call does nothing, it just seems to ignore it.
Since you pull a json string, why not use
$.getJSON("http://www.example.com?jsoncallback=?",
function(data){ ... }
Note the jsoncallback. What happens here is that jquery parses an extra parameter to the code to verify the result is from the actual request. This happens on cross-domain requests.
To make your 'json-builder' compatible, simple place the jsoncallback in front of the request:
$return = $_GET["jsoncallback"].'({"title" : "test", "author" : "someone"});
Your problem may not be, as you mentioned, cross domain. Does your server logs any requests? I have similar problem with second (the same) request after linking it from index.html, first request works fine. I found an information that it may be a phonegap bug.
It turns out my problem was entirely different. My dependencies were not loading because of how the mobile browsers add AMD scripts. I've fixed this by consolidating all scripts into a single file and it's worked ever since.

jQuery xml cross domain data parsing fail in ie8

I'm new to jQuery and would like to parse an xml document.
So far, I've been doing:
$.ajax({
url: xmlUrl,
type: 'GET',
dataType: 'xml',
crossDomain: true,
error: function(){
alert('Error loading XML document');
},
success: function(xml) {
}
});
However, I always get the error message in ie8.
Here is the xmlUrl address which I want to parse.
http://api.facebook.com/restserver.php?method=links.getStats&urls=MyUrl
With really no luck. Any ideas? Thanks.
I'm afraid IE 8 does not support Crss Origin requests, hence does not allow the cross-domain request (unless you do not setup the browser itself).
As the service you are trying to use does not use any client's data, you can setup a proxy - simple PHP script, that retrieves the url and output (via curl or file_get_contents if allow_url_fopen is enabled), and use ajax without the crossdomain.
I'd suggest using the Facebook JavaScript SDK (http://developers.facebook.com/docs/reference/javascript/), as it will take care of that issue for you. Also the method of using the restserver is deprecated, you can use the new SDK to call into the Graph API.

Categories

Resources