JSON data handling from PHP array - javascript

I am using an AJAX request to dynamically fetch some data from a database. The data is returned back to AJAX after being put through the PHP function json_encode(). The returned value that I recieve from the AJAX request is as follows:
{"counter":1,"1":{"objectID":"1","objectType":"note","objectDate":"2015-10-10 19:55:26","objectTitle":"Test Note","objectContent":"Lorem ipsum dolor sit amet consecetur adpiscing...","objectColor":"white"}}
How would I go about splitting this data down into separate variables such as counter for where the {"counter":1 JSON object is? Also, how would I split the sub-arrays of the JSON data into individual javascript arrays?
All help would be much appreciated. Thanks.

All you need to do is set dataType to "json" in your ajax call then pass the result with success like:
$.ajax({
url: 'example.com',
dataType: 'json',
success: function(json) {
console.log(json);
}
});
From the jQuery.ajax() documentation
dataType:
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests are converted to "jsonp" unless
the request includes jsonp: false in its request options. The JSON
data is parsed in a strict manner; any malformed JSON is rejected and
a parse error is thrown. As of jQuery 1.9, an empty response is also
rejected; the server should return a response of null or {} instead.
(See json.org for more information on proper JSON formatting.)

With a simple:
JSON.parse(data);
I have managed to achieve this.
Couldn't find this when originally researching.

Related

How can i do cross domain query using ajax & jsonp?

I send ajax to url , but i get error.
Here is my code:
$.ajax({
url: "http://webrates.truefx.com/rates/connect.html?q=ozrates&c=EUR/USD&f=csv&s=n",
dataType : 'jsonp',
success: function (data) {
alert(data);
}
})
Maybe i doing something wrong?
In order to access data using JSONP, the server you are requesting the data from must format its response as JSONP.
You are getting an error because the response is not JSONP (it is CSV, which you asked for explicitly when you put t=csv in the query string).
Either:
Use a different method to get the data
Change the server so it responds with JSONP formatted data

Issue about getting response in $.get()

$('#requestButton').click(function() {
$.get('ajax.php', function(data) {
alert(data);
});
});
alert() doesn't showing. What's the problem?
The problem is that your server is claiming:
content-type: application/javascript
But you are sending back a JSON document. jQuery won't populate data when it gets (what it thinks is) a JavaScript program back from the server.
You need to send the correct content type, which is application/json.
Using getJSON or specifying "json" are hacks to tell jQuery to disbelieve the content type and parse in a different data format, but you should fix the server so it tells the truth about the content instead.
Instead of :
$.get
use :
$.getJSON
As you mentioned in the comment section about returned data is json.
Or add a dataType in the $.get() call:
$.get( "ajax.php", function( data ) {
console.log(data);
}, "json" ); //<-----------add dataType here

Error 415: x-www-form-urlencoded versus JSON

The web service accepts application/json, but $.ajax() with dataType : 'json' set just tries to send data as application/x-www-form-urlencoded. What's the trick here?
dataType: 'json' specifies that jQuery expects JSON back from the server (see docs). In order to specify that you are sending JSON, you need to add contentType: "application/json".
Furthermore, jQuery cannot convert an object into JSON for you. If you are passing any object to data, you need to stringify it yourself:
data: JSON.stringify(dataObject);

Why is the jquery $.post command not sending JSON data to the server

I've been using the $.getJSON command for awhile. But since I'm actually posting to the server I need to be using $.post. But as soon as I switch from $.getJSON to $.post, the back end, which is the Flask Python framework, doesn't seem receive any JSON data. That's the only thing I changed. The documentation for $.post seems to indicate that the format is the same for sending data with either command.
With $.getJSON, I could access the JSON parameters in Flask with the request.args.get command. But after changing to $.post, request.args is empty (so request.args.get() always returns None). Here's the line of javascript with $.getJSON:
$.getJSON("/admin/emails/ajax/send", {'data':JSON.stringify(data)}, function(){...})
And then just imagine that line with $.post(...) instead.
EDIT It appears that issue is when I change from 'GET' to 'POST', the data disappears from Flask's request.args object. I tried using the $.ajax method and go the same results. Does anybody know why?
Just unwrap this beast and use $.ajax so you're not tripping over wrappers.
$.ajax({
type: 'POST',
url: '/admin/emails/ajax/send',
data: JSON.stringify(data),
dataType: 'json',
success: function(json){
//the JSON response from the server
}
});
OK I figured it out. If you send JSON data to the server in a 'GET' method, Flask puts the JSON data into request.args. If, instead, you send the data in 'POST' method, Flask puts the data in request.form. Kinda confusing, but whatever.
Above answer is correct, but if wanna use $.post u should go to server side and add a header: "Content-type: app/json"(something like this google it)
Did you tried $.post this way:
$.post("/admin/emails/ajax/send", {'data':JSON.stringify(data)}, function(data){
console.log(data);
}, "json");
//-^^^^^^-----------are you putting dataType here.

Javascript automatically parsing nested object

This is more a question of procedure than anything else. I'm curious why this happens and I can't seem to find any documentation on this "feature" within the ECMA script documentation.
When I make an AJAX call within jQuery to my server, it returns the following JSON response to the page:
{"version":"v1","status":"OK","timestamp":"2013-02-14 10:32:45","data":"true","error":""}
With this string I have to call jQuery.parseJSON(string); to get it as an object, and the be able to reference it as an object.
However, when my server returns something like this:
{"version":"v1","status":"OK","timestamp":"2013-02-14 10:12:19","data":{"a":"asgsadfga","b":false,"c":[]},"error":""}
Javascript automatically loads this an an object without the need to parse. It would seem that because this example returns a nested object, despite the fact it was returned from the server as a string, Javascript will immediately recognize that, and parse the string for me.
Is this expected functionality, and if so, can anyone point me to the documentation of this?
EDITED:
Here is the offending AJAX call:
jQuery.ajax({
url: url,
type: 'GET',
async: false,
success: function (result) {
console.log(result)
}
Make sure that your server sets the proper Content-Type response HTTP header:
Content-Type: application/json
So that jQuery will automatically parse the JSON string returned by your server to a javascript object which will be passed as argument to your success callback.
Or if for some reason you've got some broken server side script which you have no control over you could set the dataType parameter to force jQuery to parse the result as JSON:
$.ajax({
url: '/script.cgi',
type: 'POST'
dataType: 'json',
success: function(result) {
// result will be a javascript object
}
});
But obviously the proper thing to do is to fix your server side script to return the proper Content-Type response header.
According to ajax() in jQuery API Documentation under dataType:
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).
Hope this helps.
You should specify dataType to be json in your $.ajax call. dataType is the MIME you are expecting to receive from the server. contentType is what the server is expecting from you.

Categories