I was reading a code snippet and figuring out how it works when this weird javascript problem came up.
In their javascript they called
var apiUrl = '/api/v1/pin/?format=json&order_by=-id&offset='+String(offset);
...
$.get(apiUrl, function(pins) {
for (...; i < pins.objects.length; i++) ... // works fine
});
their api returns this json format:
{"meta": {"limit": 50, "next": "?limit=50&format=json&order_by=-id&offset=60", "offset":
10, "previous": null, "total_count": 79}, "objects": [ {...},{...}, ... ]}
I tried to mimic it but the $.get never accepted my simplified json string.
// my attempt
$.get(myApiUrl, function(pins) {
for (...; i < pins.objects.length; i++) ... // ERROR: undefined length
});
My Json string is in the similar but shortened format.
{"objects": [{...},{...}, ... ]}
I couldn't get it to work until I googled the $.getJson() command. I am just wondering why their javascript code works with just $.get whereas mine has to use $.getJson??
Is it some kind of header you can set to force javascript to read it as json?
If you don't specify content type explicitly jQuery will try to determine data type based on headers returned by server.
If you are not using JSON serializers, then verify validity of your JSON using http://jsonlint.com/ or this, otherwise you will get an error.
Correct ContentType header for JSON is: application/json
In both cases the AJAX call returns a string. jQuery somehow has to figure out what to do with it. How it does that depends on the dataType option.
The docs call the default value Intelligent guess. So how to guess? Evaluating the Content-Type header of the response. If it's application/jsonthen jQuerywill try to create an object.
To ensure that jQuerywill always try to interpret the response as JSON you can set the dataType to json.
Set the HTTP response header Content-Type to application/json
Eg:
HTTP/1.1 200 OK
Content-Type: application/json
Related
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).
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().
We use JSON.stringify(oData); to get data in json, and how could we get data in the form of xml?
oModel.read('/', null, null, true, function(oData, oResponse){
var data = JSON.stringify(oData);
document.write(data );
});
You're using an OData service, but you're wanting the response in a certain format. That can only mean, to me, that you're wanting to bypass all the work that the ODataModel mechanism does for you and get the raw XML that is returned by the OData server. If that is the case, I have a question and an answer for you.
Question: Why?
Answer: If you really want to get the XML from the OData response, i.e. the raw Atom feed that typically comes back from, say, a Northwind entityset like http://services.odata.org/Northwind/Northwind.svc/Products , then you can actually access the whole HTTP response object in the success callback of the read() method. Extending the source code in your question a bit, it would look like this:
oModel.read('/', null, null, true, function(oData, oResponse){
document.write(oResponse.body);
});
This will produce something like this:
<feed xml:base="http://services.odata.org/Northwind/Northwind.svc/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<id>http://services.odata.org/Northwind/Northwind.svc/Products</id>
<title type="text">Products</title>
<updated>2014-08-26T07:33:36Z</updated>
<link rel="self" title="Products" href="Products"/>
<entry>
<id>http://services.odata.org/Northwind/Northwind.svc/Products(1)</id>
...
But - are you sure you really want this?
To get XML formatted response, add $format=xml to your odata url
See example :
http://services.odata.org/Northwind/Northwind.svc/Products?$format=json
http://services.odata.org/Northwind/Northwind.svc/Products?$format=xml
And to get response in XML format, use the sap.ui.model.xml.XMLModel
oModel.read('/?$format=xml', null, null, true, function(oData, oResponse){
var xmlDataModel = new sap.ui.model.xml.XMLModel(oData);
});
Server returns this JSON document:
{
"username-found": true,
"question-required": true
}
Which successfully passes JSONLint's validity check.
In web browser:
$.post('my_url', {"post":"data"}, function(data) {
data = $.parseJSON(data);
});
The code runs and successfully parses the JSON document in Opera 12 browser, however in Firefox 16, JavaScript error occurs and says "not well-formed".
JQuery is of version 1.7.2.
I cannot see what I did wrong there, do you know?
Edit:
Does it have anything to do with the way server returns the JSON? Here it is:
return new StreamingResolution("text", new StringReader(json.toString()));
uggestion, I might have found the cause. When I did alert(data), Firefox tells me that data is an object, Opera tells me that data is the JSON string.
Solution 1 (Client) - Set DataType in jQuery Request
I think the internals are a bit different in that specific browser version (because jQuery tries to detect the dataType automatically and is doing the parsing internally in the case of a JSON response) and JSON is automatically encoded in FF and not in Opera?
Try to add the dataType so jQuery will handle this (I would prefer that):
$.post('my_url', {"post":"data"}, function(data) {
// data should be an json object here
}, 'json');
It's just a guess.
OR Solution 2 (Server) - Send MIME type
You could also send a correct MIME type from the server so you don't have to set the dataType on the client. Its up to you but I think that would be the correct solution.
Regarding this answer it should be application/json.
Reference
How is the dataType detected automatically in jQuery?
Default: Intelligent Guess (xml, json, script, or html) 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).
Source: http://api.jquery.com/jQuery.ajax/
You can directly use the data object directly ..
No need to use $.parseJSON();
You also have a $.getJSON shortcut method in jQuery. Maybe jQuery automatically uses the best configuration for this case and maybe start working
Here is the $.getJSON documentation
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.