jQuery getJSON - reference pre-existing object - javascript

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);
});

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).

Related

Parsing JSON to populate the dhtmlx grid

I get JSON as a response, from an ajax call, the contents of which I then want to be loaded in the grid.
From the JQuery documentation, http://api.jquery.com/jQuery.ajax/, for response of type JSON:
"json": Evaluates the response as JSON and returns a JavaScript
object.
So I convert the JavaScript object back to JSON using JSON.stringify:
importConfigurationStatusGrid.parse(JSON.stringify(result), "json");
But the grid doesn't get populated.
The response I get looks like this:
{"rows":{"Added to index":["file1", "file2",...."],
"Conflicting":["file3", "file4",..."], "Removed":["file5",
"file6",...."]}}
I checked the JSON format on https://docs.dhtmlx.com/grid__data_formats.html#jsonformat, and I think the difference between the two(the response I get and the format specified) might be the cause.
How can I parse the JSON string using the parse method of dhtmlxGridObject?
result = {"rows":{"Added to index":["file1", "file2",...."], "Conflicting":["file3", "file4",..."], "Removed":["file5", "file6",...."]}}
importConfigurationStatusGrid.parse(result, "json");
Edit 1:
#ogui: I don't know what your AJAX request looks like, but you can add
a dataType property and set it to json so that your result gets
automatically parsed as an object for you.
The ajax request does have a dataType: 'json' property specified. So there isn't a need to use JSON.parse(). The problem lies in converting the JS object to a valid JSON format that the parse(dhtmlx) method requires.
#ogui: You could aso use jQuery.getJSON().
Even if I were to use this method, the grid object would have have to parse the same JSON, which it is failing at.
Use JSON.parse.
result = JSON.parse(result);
I don't know what your AJAX request looks like, but you can add a dataType property and set it to json so that your result gets automatically parsed as an object for you. This is mentioned in the jQuery AJAX documentation page you linked. You could aso use jQuery.getJSON().

save parsed JSON as obj

first question ever, I'm trying to parse a JSON file stored within the same file directory on my webhost as my html file that runs the javascript to parse it, I've added a console.log to debug and confrim that the file is being caught by the 'get' to ensure that I am able to 'get' the file throgh the use of jquery getJSON, in the callback i've tried to create a function that re-defines a global variable as an object containing the parsed data, but when I try to inject it into a document.getElemendtById('example').innerhtml = tgmindex.ToughGuys[1].name;
it returns a error "Uncaught TypeError: Cannot read property '1' of undefined"
here's my js/jquery
var tgmIndex;
$(document).ready(function () {
$.getJSON("http://webspace.ocad.ca/~wk12ml/test.json",function(data){
console.log( "success" );
tgmIndex =$.parseJSON;
document.getElementById('tgm1').innerHTML= tgmIndex.ToughGuys[1].name;
});
});
and here is whats contained in the JSON (i made sure to try linting it first and it's a valid json)
{"ToughGuys":[
{"name":"Ivan", "position":"Executive"},
{"name":"Little Johnny", "position":"Intern"},
{"name":"Beige Cathy", "position":"Executive"},
{"name":"Stan", "position":" original Intern"}
]}
You're setting tgmIndex to the parseJson function.
Should be doing tgmIndex =$.parseJSON(data);
Presumably your service is returning application/json. Therefore data already contains the json.
tgmIndex = data;
Then... "Tough Guys" is what you should be indexing. Not "ToughGuys"
Your example JSON is wrong in your question. If I go to
http://webspace.ocad.ca/~wk12ml/test.json
I see:
{"Tough Guys":[
{"name":"Ivan", "position":"Executive"},
{"name":"Little Johnny", "position":"Intern"},
{"name":"Beige Cathy", "position":"Executive"},
{"name":"Stan", "position":"Intern 0"}
]}
See "Tough Guys" There's your problem.
document.getElementById('tgm1').innerHTML= tgmIndex['Tough Guys'][1].name;
If data for some reason isn't JSON:
tgmIndex = $.parseJSON(data);

JSON Reader issue: cannot access jsonData

I have a strange thing going on here: I am using a JSON reader within a store to fetch search results. After loading the store I receive data or error states (built together as a JSON, too). So in both ways I get a successfully response, so I have to check the JSON for myself to trap "error conditions". But I cannot access the jsonData property that shhould be a JSON object within the reader. Chrome tells me that:
I can access the applyDefaults though (it returns true in that case) but not the jsonData.
My code looks like this:
var result = searchStore.getProxy().getReader();
console.log(result.jsonData);
The output is "undefined". As you can see in the picture the jsonData object holds my JSON (with the isError property I wanted to access).
What I am doing wrong?
You need to think more async and think of the timing it takes for a request to return and when you are trying to get the jsonData. Instead of using console.log, set a breakpoint or use the debugger; statement so you can freeze the browser and walk through the code. You can then inspect variables and such to see what the object looks like.
Try to access your JSON data in a success callback, to make sure the data is gathered from the server.

Retrieving values of json object in javascript

I am sending an AJAX request to server and retrieving a response as a json object from the server with javascript code to my android application. I know the key values of the json object(ID, name, status, etc.) but I do not know how to get their values.(100, Mark, success, etc.) I need those data for processing for some other task. Can someone please tell me how to extract data from that json object. When I use alert(http.responseText); as follows I get the json object displayed. I need to get the values out of it.
method used to receive response
http.onreadystatechange = function() { //Handler function for call back on state change.
if(http.readyState == 4) {
alert(http.responseText);
json object I receive
{"header": {"ID":100,"name:"Mark"},"body":{"status":"success"}}
You have to convert The string to an object by doing var response=JSON.parse(http.responseText);
Just treat it like any object - console.log(response['name'])
You need to convert it to a JavaScript object using JSON.parse:
var obj = JSON.parse(http.responseText);
Since some legacy browsers do not have native JSON support you should include json2.js to shim it for those browsers.
you will have to eval the http.responseText to get the json object...
but using eval is not recommended, so you can use the json2 library to parse the text into json object..
or else you can even use the library like jquery and use function parseJSON to get it converted to json object

AJAX responseXML

i have a problem regarding the responseXML of ajax..
I have this code from my callback function:
var lineString = responseXML.getElementsByTagName('linestring')[0].firstChild.nodeValue;
However, the linestring can only hold up to 4096 characters max.. the remaining characters are rejected.
I dont know what to use to get all the values that the lineString
returns. its quite a big data thats why I thought of using the responseXml
of AJAX, BUT turned out it still cannot accomodate everything.
My linestring consists of lines from a logfile which I concatenated and just
put line separator. I need to get this data in my form so that is why after reading from the php, i send it back via AJAX
Do you have suggestions guys.
XML adds a lot of extra markup for most ajax requests. If you are expecting some kind of list with data entities, sending them in a JSON format is the way to go.
I used JSON to get quite huge arrays with data.
First of all, JSON is just Javascript Object Notation meaning that the Ajax Request would request a String which will actually be evaluated as a Javascript object.
Some browsers offer support for JSON parsing out of the box. Other need a little help. I've used this little library to parse the responseText in all webapps that I developed and had no problems with it.
Now that you know what JSON is and how to use it, here's how the PHP code would look like.
$response = [
"success" => true, // I like to send a boolean value to indicate if the request
// was valid and ok or if there was any problem.
"records" => [
$dataEntity1, $dataEntit2 //....
]
];
echo json_enconde($response );
Try it and see what it echos. I used the php 5.4 array declaration syntax because it's cool! :)
When requesting the data via Ajax you would do:
var response
,xhr = getAjaxObject(); // XMLHttp or ActiveX or whatever.
xhr.open("POST","your url goes here");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
try {
response = JSON.parse(xhr.responseText);
} catch (err) {
response = {
success : false,
//other error data
};
}
if(response.success) {
//your data should be in response
// response.records should have the dataEntities
console.debug(response.records);
}
}
}
Recap:
JSON parsing needs a little help via JSON2 library
PHP can send maps as JSON
Success boolean is widely used as a "successful/unsuccessful" flag
Also, if you're into jQuery, you can just set the dataType : "json" property in the $.ajax call to receive the JSON response in the success callback.

Categories

Resources