0

I am using jQuery.getJSON to get some data. I have an object called helpdesk.data.STATUS.MESSAGE.NOTLOGGEDIN which is created in a normal script tag. In the JSON returned by the call to getJSON, I am trying to reference helpdesk.data.STATUS.MESSAGE.NOTLOGGEDIN. I am using the .done method to capture the JSON and do something with it, and .error to catch any errors.

The JSON being returned looks perfectly valid, however it is going into the .error function with a status of 200 (OK).

If I change the reference to the object to a string, it goes into the .done method. Does anyone know of a way to reference an object which already exists within the page firing the getJSON request from the JSON being returned?

The returned JSON is:

{"builds": {"status": helpdesk.data.STATUS.FAILURE, "messages": [helpdesk.data.STATUS.MESSAGE.NOTLOGGEDIN]},"details": {"status": helpdesk.data.STATUS.FAILURE, "messages": [helpdesk.data.STATUS.MESSAGE.NOTLOGGEDIN]}}


Final code:

$.ajax("/helpdesk/resources/js/json/data.json.php", {"data": {"data": "styling-builds,details", "update": "update", "nojson": "nojson"}}).done(function(data) {
    eval("data = " + data);
});
9
  • Note that your JSON is not valid (try to copy/paste it in json.parser.online.fr) Commented Nov 13, 2013 at 9:48
  • It has 4 errors on the objects I am referencing. What I'm trying to do is reference objects which already exist in the page before the call to getJSON. Commented Nov 13, 2013 at 9:49
  • Hmm perhaps using $.post (or $.ajax) with dataType set to json and then using JSON.parse or something similar would do it. Commented Nov 13, 2013 at 9:50
  • I don't think it's correct to reference variables in your JSON response Commented Nov 13, 2013 at 9:50
  • Ok, but the thing is this would be so much better if we can achieve this as all the possible errors are already stored in an object anyway. I'll try the $.post method and see if I get anywhere with that Commented Nov 13, 2013 at 9:53

1 Answer 1

1

To sum it up: it is obviously incorrect to put references to client variables in your JSON response and it will result in invalid JSON format (cf http://json.parser.online.fr/).

The only workaround I see (if you really want to reference an existing variable in your JSON) is to return your response as a string and call eval on it on client-side (variables and functions will be correctly interpreted then).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. See updated post for final code. It is working perfectly now :). Along with global error handling (which will log an error in the DB via another ajax call) this is going to be very powerful!

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.