Parsing JSON to populate the dhtmlx grid - javascript

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

Related

JSON won`t get parsed with variables out of an array

I don´t understand why my JSON doesn´t get parsed. I hope someone could explain this to me. I try to send a JSON from PHP to JavaScript.
This code works fine:
From PHP
echo json_encode(array($row['jobunique'], $row['jobtitle']));
to JavaScript
success: function(getjoblist) {
var getjobdetails = $.parseJSON(getjoblist);
}
But this code gives me an error back:
From PHP - data comes out of an array
echo json_encode(array($data[2], $data[3]));
I thought, maybe it's an object and I need to make a string out of the variables like this:
echo json_encode(array(strval($data[2]), strval($data[3])));
But it did not work either.
Here is the JavaScript code:
success: function(callback) {
var namearray = $.parseJSON(callback);
}
Here is the error from the console:
Uncaught SyntaxError: Unexpected token in JSON at position 0
Here is the network-tab:
The callback variable is already an array. JQuery's AJAX methods automatically parse responses, if there are JSON specific headers present (Content-type: application/json).
Try run JSON.parse(["Fabi","Squ"]) in the console, it will get you the same error message.
Read more about this at http://api.jquery.com/jquery.ajax/ :
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

passing JSON data and getting it back

I'm new to passing objects through AJAX, and since I am unsure of both the passing and retrieving, I am having trouble debugging.
Basically, I am making an AJAX request to a PHP controller, and echoing data out to a page. I can't be sure I'm passing my object successfully. I am getting null when printing to my page view.
This is my js:
// creating a js filters object with sub arrays for each kind
var filters = {};
// specify arrays within the object to hold the the list of elements that need filtering
// names match the input name of the checkbox group the element belongs to
filters['countries'] = ["mexico", "usa", "nigeria"];
filters['stations'] = ["station1", "station2"];
filters['subjects'] = ["math", "science"];
// when a checkbox is clicked
$("input[type=checkbox]").click(function() {
// send my object to server
$.ajax({
type: 'POST',
url: '/results/search_filter',
success: function(response) {
// inject the results
$('#search_results').html(response);
},
data: JSON.stringify({filters: filters})
}); // end ajax setup
});
My PHP controller:
public function search_filter() {
// create an instance of the view
$filtered_results = View::instance('v_results_search_filter');
$filtered_results->filters = $_POST['filters'];
echo $filtered_results;
}
My PHP view:
<?php var_dump($filters);?>
Perhaps I need to use a jsondecode PHP function, but I'm not sure that my object is getting passed in the first place.
IIRC the data attribute of the $.ajax jQuery method accepts json data directly, no need to use JSON.stringify here :
data: {filters: filters}
This way, you're receiving your json data as regular key/value pairs suitable for reading in PHP through the $_POST superglobal array, as you would expect.
http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php
When you use ajax the page is not reloaded so the php variable isn't of use.
You may want to look for a tutorial to help. I put one at the beginning as I don't see how to format this on my tablet
you will need to json_encode your response as the tutorial shows
you may want to print to a log on the server when you are in the php function and make it world readable so you can access it via a browser
I like to use the developer tools in Chrome to see what is actually returned from the server

jQuery getJSON - reference pre-existing object

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

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