1

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 :-)

2 Answers 2

3

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,""));
Sign up to request clarification or add additional context in comments.

3 Comments

How do I wrap the callback parameter with my response? you mean by doing a $callback.'({'.$jsonResponse.'})'; ?
@PinoyStackOverflower -- Sorry it took a while to get back.. The callback parameter contains the function name of that callback that exists on the front end. jQuery includes it for you in the jsonp request. So you would read that 'callback' parameter from the request on the server, and then for the response to the client you would return a string like callbackParameterValue + '(' + JSON.stringify(serverData) + ')'. Then jQuery will get the response and pass it to the success function, at which time you need to parse it to JSON as I mention above.
Hi @mpickell, Could you please post the complete code which includes your suggestion by editing Adam's code. That would be more helpful. Thank You!
0

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);
            }                 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.