naspinski
naspinski

Reputation: 34717

jQuery $.ajax error: Parsing JSON Request failed with valid JSON?

I have a simple ajax call:

$.ajax({
    url: 'http://localhost:39657/List/Receptacle',
    dataType: "json",
    success: function(json) { alert("success"); }
});

And in Fiddler, the entire response is:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Sat, 18 Feb 2012 07:39:11 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 97
Cache-Control: private
Content-Type: application/json; charset=utf-8
Connection: Close

[{"Selected":false,"Text":"ABC","Value":"3"},{"Selected":false,"Text":"XYZ","Value":"4"}]

So it appears to have worked, but I get no alert...

What am I doing wrong here? Why is my JSON not parsing? Thank you.

Upvotes: 2

Views: 4396

Answers (2)

Kurt
Kurt

Reputation: 1

you have to do this serverside:

 HttpResponseMessage m = new HttpResponseMessage(HttpStatusCode.NotFound);            
 m.Content = new StringContent("oops");                             
 throw new HttpResponseException(m);

Upvotes: 0

JIA
JIA

Reputation: 1495

why you have '?callback=?' at the end of url ? is it jsonp? yes then change the dataType:'jsonp'

Edit

make a error handler

$.ajax({
    url: 'localhost:39657/List/' + $(this).val(),
    dataType: "json",
    success: function(json) {
           alert("success");
    },
    error:function(xhr){
        console.log(xhr.responseText);
    }
});

see if it hits the success handler or the error handler and what error message does it give? i dont think there is something wrong with the json parsing as it is valid json and being parsed fine look here


as infered from the comments you are running into the CORS blues, which is implemented as a security feature to prevent cross site scripting attacks you cannot use jsonp by just setting the dataType to jsonp on the client side, the server side has to be configured as well, if its a web-service you can set the response header to allow the cross domain resource sharing by

var resp = new HttpResponseMessage();
resp.Headers.Add("Access-Control-Allow-Origin","*");

alternatively you can make a server side proxy and have that proxy call your other project whether its a webservice or web application and then return the received response to the client side

Upvotes: 2

Related Questions