Adam
Adam

Reputation: 75

jQuery $.ajax call parser error on JSONP response

Ahoy!

I am using a WCF service to handle ajax calls from a web server on a seperate domain (therefore employing JSONP). My call looks like this:

$.ajax({
    dataType: 'jsonp',
    type: 'GET',
    url: 'http://localhost/s.svc/login?callback=?&l=en&e=foo&p=bar',
    success: function (serverData) {
        // [...]
    },
    error: function (jqXHR, textStatus, errorThrown) {
        // [...]
    }
});

The response I get from the server looks like this:

?({"DataIsValid":true,"ErrorOccurred":false,"EmailAddressValidationMessage":"","PasswordValidationMessage":""});

And jQuery subsequently throws a parsererror when reading it.

The response above looks like valid JSON and, per the documentation, I think "?callback=?" is appropriate for $.ajax calls using JSONP.

Thanks in advance for pointing out what I am obviously missing :-)

Upvotes: 1

Views: 11804

Answers (2)

Raveendra
Raveendra

Reputation: 1

I was missing below in MVC action method response(wrapping the reponse in callback method).

response.Write(request.Params["callback"] +"(" +htmlContent +");");

And jquery ajax call should be like below.

jQuery.ajax({
           url:"https://servername/virtualDirectory/ActionMethod,               
           crossDomain: true,
            dataType: 'jsonp',                  
            type: 'GET',
            cache: false,
            jsonp:"callback",              
            success: function (data) {   
                alert('success');                
                $fs("#fs_container").htm(data);                   
            },
            error: function (data, status, req) {                          
               alert(req.responseText + " " + status);
            }                 
});

Upvotes: 0

mpickell
mpickell

Reputation: 341

A couple things i see here:

  1. Get rid of your callback parameter in the URL. Making an jQuery JSONP call adds its own callback and your success/error function will be called. On the backend, read the "callback" parameter from the request and use it to wrap your jsonp response (you are already doing that it appears -- so don't change that part).
  2. When you get into your success function, the serverData will be a string. Parse it with jQuery.parseJSON() or JSON.parse():

var data = jQuery.parseJSON(serverData); // or use JSON.parse(serverData);

That should do it.

One final thing. If you start getting "Unexpected token..." errors on the parse you probably have a control character hidden somewhere in your JSON string. I had this issue and it was a newline ("\n"). Figure out which character it is by getting the string to parse in something like Chrome's dev tools console, and then replace it:

var data = jQuery.parseJSON(serverData.replace(/\n/g,""));

Upvotes: 3

Related Questions