tags:

views:

24240

answers:

14

Hi,

I'm having difficulty parsing some JSON data returned from my server using jQuery.ajax()

To perform the AJAX I'm using:

$.ajax({
  url: myUrl,
  cache: false,
  dataType: "json",
  success: function(data){
    ...
  },
  error: function(e, xhr){
    ...
  }
});

And if I return an array of items then it works fine:

[ { title: "One", key: "1" }, { title: "Two", key: "2" } ]

The success function is called and receives the correct object.

However, when I'm trying to return a single object:

{ title: "One", key: "1" }

The error function is called and xhr contains 'parsererror'. I've tried wrapping the JSON in parenthesis on the server before sending it down the wire, but it makes no difference. Yet if I paste the content into a string in Javascript and then use the eval() function, it evaluates it perfectly.

Any ideas what I'm doing wrong?

Anthony

A: 

@Guido I've already tried that:

I've tried wrapping the JSON in parenthesis...

littlecharva
+14  A: 

Is your server sending data as Content-Type "*/json"? If not, modify the response headers accordingly. Sending "application/json" would be fine, for example.

Tomalak
Second this guess, had the same problem once and learned that surprisingly I was using the wrong mime type. If you are testing over localhost on windows be very aware of this. Try uploading it somewhere and testing it again. If you want it to work on localhost you have to really fudge the request.
Josh
+5  A: 

Try adding this:

$.ajax({
 type: "GET",
 url: myURL,
 beforeSend: function(x) {
  if(x && x.overrideMimeType) {
   x.overrideMimeType("application/j-son;charset=UTF-8");
  }
 },
 dataType: "json",
 success: function(data){
  // do stuff...
 }
});
Josh
just wanna say that the beforeSend suggestion you suggest worked for me!! my ajax call worked great in safari and chrome but not firefox. as soon as i added the beforeSend then Firefox took right off. wow!! Thanks!!
Karmen Blake
A: 

If returning an array works and returning a single object doesn't, you might also try returning your single object as an array containing that single object:

[ { title: "One", key: "1" } ]

that way you are returning a consistent data structure, an array of objects, no matter the data payload.

i see that you've tried wrapping your single object in "parenthesis", and suggest this with example because of course JavaScript treats [ .. ] differently than ( .. )

David Alpert
+1  A: 
{ title: "One", key: "1" }

Is not what you think. As an expression, it's an Object literal, but as a statement, it's:

{                // new block
    title:       // define a label called 'title' for goto statements
        "One",   // statement: the start of an expression which will be ignored
        key:     // ...er, what? you can't have a goto label in the middle of an expression
                 // ERROR

Unfortunately eval() does not give you a way to specify whether you are giving it a statement or an expression, and it tends to guess wrong.

The usual solution is indeed to wrap anything in parentheses before sending it to the eval() function. You say you've tried that on the server... clearly somehow that isn't getting through. It should be waterproof to say on the client end, whatever is receiving the XMLHttpRequest response:

eval('('+responseText+')');

instead of:

eval(responseText);

as long as the response is really an expression not a statement. (eg. it doesn't have multiple, semicolon-or-newline-separated clauses.)

bobince
I think jQuery adds the parentheses automatically when processing the request data.
strager
This answer was very helpful to me, as I never understood why people wrap JSON in parentheses.
Andrey Tarantsov
+17  A: 

According to the json.org specification, your return is invalid. The names are always quoted, so you should be returning

{ "title": "One", "key": "1" }

and

[ { "title": "One", "key": "1" }, { "title": "Two", "key": "2" } ]

This may not be the problem with your setup, since you say one of them works now, but it should be fixed for correctness in case you need to switch to another JSON parser in the future.

Ben Combee
Indeed, in jQuery 1.4 (for example) `{ key: 'val' }` is not valid JSON.
thenduks
A: 

For some reason that I have yet to determine I can only get my JSon to parse using Firefox when I am testing locally, I use visual studio's built in server for local dev / testing. On a live server, Windows 2008 or 2003, with the same code IE works fine.

Slee
A: 

If jQuery's error handler is being called and the XHR object contains "parser error", that's probably a parser error coming back from the server.

Is your multiple result scenario when you call the service without a parameter, but it's breaking when you try to supply a parameter to retrieve the single record?

What backend are you returning this from?

On ASMX services, for example, that's often the case when parameters are supplied to jQuery as a JSON object instead of a JSON string. If you provide jQuery an actual JSON object for its "data" parameter, it will serialize that into standard & delimited k,v pairs instead of sending it as JSON.

Dave Ward
A: 

I found in some of my implementations I had to add:

obj = new Object; obj = (data.obj);

which seemed to solve the problem. Eval or not it seemed to do exactly the same for me.

Jay
Use the object literal when initializing a new object, not the Object constructor: var obj = {};
Andreas Grech
Yeah I see, var myArray = [] for arrays and var myObject = {}, thanks for the tip Dreas
Jay
+1  A: 

If you are consuming ASP.NET Web Services using jQuery, make sure you have the following included in your web.config:

<webServices>
    <protocols>
     <add name="HttpGet"/>
     <add name="HttpPost"/>
    </protocols>
</webServices>
Andreas Grech
Crucial for getting jQuery and .NET webservices to work.
Frenchie
A: 

Hi its good discussion I found a solution have a look here http://www.isolutionteam.co.uk/json-jquery-ajax-aspnet-and-c-to-get-ajaxed-data-table-rows-passing-multiple-parameters/

A: 

I had a similar problem to this where Firefox 3.5 worked fine and parsed my JSON data but Firefox 3.0.6 returned a parseerror. Turned out it was a blank space at the start of the JSON that caused Firefox 3.0.6 to throw an error. Removing the blank space fixed it

jonburney
+4  A: 

JSON strings are wrapped in double quotes; single quotes are not a valid substitute.

{"who": "Hello World"}

is valid but this is not...

{'who': 'Hello World'}

Whilst not the OP's issue, thought it worth noting for others who land here.

John Mee
A: 

see this issue in JQuery 1.4.1, which was fixed in 1.4.2

6031 parseJSON doesn't parse JSON with a leading newline in IE6 and IE7

http://dev.jquery.com/ticket/6031

Hope that helps... (it worked for me nicely).

Anton S. Kraievoy