0

I have this case (a JSON string returned by my server):

{"success": true, "users": [1, 3, 4, 8]}

However, when using this kind of request, I'd get that response as a "string":

var availableUsers = $.ajax({
    url: absPath + '/users/findUsers',
    type: 'POST',
    data: {contents: $('#messageTo').val()},
    dataType: 'json',
    async: false
}).responseText;

With: alert(typeof(availableUsers)); I'd get: string return value from typeof.

When doing this:

window.eval(availableUsers); It won't be evaluated as expected, to a JavaScript Object.

How can I get the valid JSON response (using, async: false) converted to a JavaScript accessable Object or how can I propertly evaluate the string returned from the server?

Thanks!

  • 1
    Check the content type header returned from the request to /users/findUsers – a'r Nov 22 '11 at 18:05
  • 1
    possible duplicate of [how to parse json in javascript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) – Felix Kling Nov 22 '11 at 18:05
  • 1
    Is there a reason you aren't using a `success` callback here? Even with `async:true`, this would likely be a) more legible, and b) more likely to do what you expect. I don't think jQuery's automatic JSON-parsing will kick in with `.responseText`. – nrabinowitz Nov 22 '11 at 18:07
  • 2
    Can you use `jQuery.parseJSON`? – Mike Christensen Nov 22 '11 at 18:07

2 Answers2

0

try setting the content type of your request to application/json read more here: What is the correct JSON content type?

Community
  • 1
  • 1
MilkyWayJoe
  • 9,082
  • 2
  • 38
  • 53
0

Why not get the JSON object in a callback? Check the success setting.

$.ajax({
     url: absPath + '/users/findUsers',
     type: 'POST',
     data: {contents: $('#messageTo').val()},
     dataType: 'json',
     success: function(data){
         var availableUsers = data;
         alert(typeof availableUsers);
     },
     async: false 
});

With the callback, you may do what ever you want with the object you got from the server.

OnesimusUnbound
  • 2,886
  • 3
  • 30
  • 40
  • my availableUsers is a global variable and I need it outside that anonymous function under the $.ajax({})! $.parseJSON helped the trick ;) –  Nov 22 '11 at 18:14
  • @Commando: Then just remove the `var`. But honestly you should not use synchronous requests. They are not needed in most cases. – Felix Kling Nov 22 '11 at 18:41