Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery won't parse my JSON from AJAX query

Tags:

json

jquery

ajax

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

like image 668
littlecharva Avatar asked Oct 30 '08 09:10

littlecharva


People also ask

Can you use JSON with AJAX?

According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page. Many developers use JSON to pass AJAX updates between the client and the server.

Can AJAX be used with jQuery?

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!

How do I get AJAX response in JSON?

Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.


2 Answers

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

like image 164
Tomalak Avatar answered Sep 23 '22 01:09

Tomalak


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.

like image 26
Ben Combee Avatar answered Sep 21 '22 01:09

Ben Combee