Sahil Grover
Sahil Grover

Reputation: 1915

Issue with AJAX requests with in browser

I am implementing some AJAX requests to my server. The request type and params are exactly same in two cases but the response type coming from the server is different.

CASE 1 :

This is implementation in Titanium using titanium network http client.

var xhr = Ti.Network.createHTTPClient({
    onload : function() {
        alert('sucess');
    },
    onerror : function(e) {
         alert('error');
    },
    timeout : 5000
});
var main_url = "http://localhost:3000/shops/560/login.json?api_token=some_token&customer[phone_number]=9988776655&customer[pin]=9876";
xhr.open('GET', main_url);
xhr.send();

which returns the response perfectly and seems working for me.

CASE 2 :

This is implementation in local file using JQuery AJAX method.

var main_url = "http://localhost:3000/shops/560/login.json?api_token=some_token&customer[phone_number]=9988776655&customer[pin]=9876";

       $.ajax({
        url: main_url,
        type: "GET",
        dataType: "json",
        timeout: 5000,
        success: function(data, status, xmlstatus) {
            alert("success");
        },
        error: function(data, status, xmlstatus){
            if (t === "timeout") {
                alert("timeout");
            } else {
                alert("some error");
            }
        }
     });

But due to CROSS DOMAIN policy in browsers it returns

 XMLHttpRequest cannot load http://localhost:3000/shops/560/login.json?api_token=some_token&customer[phone_number]=9988776655&customer[pin]=9876. Origin null is not allowed by Access-Control-Allow-Origin.

So, to avoid this I added another paramater

 &callback = ?

But still it returns

 alert('some error');

Not able to figure out where the stuff is going wrong. When URL, parameters, type everything is same.

---------------EDIT-------------

Digging down iniside gives me respone :

 console.log(data) => parsererror

and

 console.log(xmlstatus) => jQuery164023596301255747676_1335786441349 was not called

Upvotes: 2

Views: 400

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382132

I think your server isn't answering with jsonp but simply with json.

A JSONP answer is like this :

callback(someJson)

Where callback is the name of the callback you provided or one automatically provided by jquery. You cannot simply call in JSONP a server that was made for JSON queries.

Here's a sample (a little complex, it's real code, but maybe you'll filter what's not related to your problem):

client : https://github.com/Canop/braldop/blob/master/chrome/braldop/inext_com.js

server : https://github.com/Canop/braldop/blob/master/go/src/braldopserver/BraldopServer.go

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382132

As you're speaking of "local file", be careful that you cannot do a lot in ajax if you're loading your file with protocol file://. You need to use http:// even if the server is localhost.

Upvotes: 0

Related Questions