Suave Nti
Suave Nti

Reputation: 3747

Jquery mobile ajax call isnot working (Crossdomain)

I have two projects running seperately one is a simple static HTML5 website hosted on IIS which Iam evaluating for my mobile application on port number 90.

secondly I have a webserver running for services on port 9000 which returns JSON data (I use playframework2.0 for this).

In my static website I have a HTML5 page which has the below ajax call to the service url.

$("#homePg").on('pageinit', function(event) {
 $.ajax({
        type:'GET',
        url : 'http://localhost:9000/menu',
        success : function(response){
                alert('success'+response);
        },
        error : function(xhr, status, error){
        alert('error'+xhr.responseText);
        }
      }); 
   });

everytime it goes to the error function, where as when I try the same url in the browser it works fine.

Am using Jquery 1.7.1 and jquery.mobile.1.1.1.js

Have checked in firebug the URL loads properly but response is blank

Upvotes: 1

Views: 3716

Answers (1)

Josh
Josh

Reputation: 16532

With javascript, a different port is treated as a cross domain call. You will need to use jsonp.

I use the jquery.jsonp library to do this.

$.jsonp({
    dataType: 'json',
    url: 'http://localhost:9000/menu',
    success: function (response) {

    },
    error: function (xhr, status, error) {

    }
}); //end ajax

I would like to note that jsonp can only do GET requests, so if you need to pass any data, it has to be part of the query string. If you are submitting data that has legal ramifications -- such as credit card data, you'd have to turn off your system logging so that the card numbers are not stored in the IIS logs.

You can also do jsonp calls with $.ajax.

$.ajax({
    url: 'http://localhost:9000/menu',
    dataType: "jsonp",
    jsonp : "callback",
    jsonpCallback: "jsonpcallback"
});

function jsonpcallback(data) { 
    alert('success' + data);
}

I've never used the second method, so I am not even sure if this code will work.

Upvotes: 1

Related Questions