Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Cross Domain Ajax

My ajax code is

$.ajax({
    type: 'GET',
    dataType: "jsonp",
    processData: false,
    crossDomain: true,
    jsonp: false,
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        console.log("in");
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

This is a cross domain ajax request.

I am getting correct response for the request, while checking with firebug i can see that response.

This is the response I am getting in firebug response and while accessing this url through web browser

{"AuthenticateUserResult":"{\"PKPersonId\":1234,\"Salutation\":null,\"FirstName\":\"Miqdad\",\"LastName\":\"Kumar\",\"Designation\":null,\"Profile\":\"\",\"PhotoPath\":\"\/UploadFiles\/\"}"}

But I am getting error

SyntaxError: invalid label

{"AuthenticateUserResult":"{\"PKPersonId\":8970,\"Salutation\

Whether I need to use any other method to get it works. I want to implement this in phonegap+jquery mobile app.

Also, I don't have any access to the web service

If I disable chrome web security it's working fine

like image 649
Miqdad Ali Avatar asked Jun 07 '13 17:06

Miqdad Ali


People also ask

Can you do cross domain Ajax?

Browser does not allow cross domain AJAX requests due to security issues. Cross-domain requests are allowed only if the server specifies same origin security policy. To enable CORS, You need to specify below HTTP headers in the server. Access-Control-Allow-Origin – Name of the domain allowed for cross domain requests.

How do I make a cross domain AJAX request?

For a successful cross-domain communication, we need to use dataType “jsonp” in jquery ajax call. JSONP or “JSON with padding” is a complement to the base JSON data format which provides a method to request data from a server in a different domain, something prohibited by typical web browsers.

How can I call Ajax to another domain?

ajax({ url: 'proxy. php', type: 'POST', data: { address: 'http://www.google.com' }, success: function(response) { // response now contains full HTML of google.com } });

What is Ajax crossDomain?

CORS is a mechanism that defines a procedure in which the browser and the web server interact to determine whether to allow a web page to access a resource from different origin. Figure 2. Cross domain ajax request. When you do a cross-origin request, the browser sends Origin header with the current domain value.


2 Answers

Looks like the inner JSON struct is passed along as a string. You'll have to JSON.parse() it once more to get that data as an object.

try {
  responseData = JSON.parse(responseData);
}
catch (e) {}

Edit: Try the following:

$.ajax({
    type: 'GET',
    dataType: "json",
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        console.log("in");
        var data = JSON.parse(responseData['AuthenticateUserResult']);
        console.log(data);
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});
like image 117
EWit Avatar answered Oct 16 '22 09:10

EWit


Unfortunately it seems that this web service returns JSON which contains another JSON - parsing contents of the inner JSON is successful. The solution is ugly but works for me. JSON.parse(...) tries to convert the entire string and fails. Assuming that you always get the answer starting with {"AuthenticateUserResult": and interesting data is after this, try:

$.ajax({
    type: 'GET',
    dataType: "text",
    crossDomain: true,
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        var authResult = JSON.parse(
            responseData.replace(
                '{"AuthenticateUserResult":"', ''
            ).replace('}"}', '}')
        );
        console.log("in");
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

It is very important that dataType must be text to prevent auto-parsing of malformed JSON you are receiving from web service.

Basically, I'm wiping out the outer JSON by removing topmost braces and key AuthenticateUserResult along with leading and trailing quotation marks. The result is a well formed JSON, ready for parsing.

like image 29
ElmoVanKielmo Avatar answered Oct 16 '22 10:10

ElmoVanKielmo