Access json data from php - javascript

I have a problem accessing JSON data. I'm new to JSON and jquery so there is probably a easy solution to it and I would be glad to find out.
My jQuery:
$.post(
"currentPage.php",
{
'currentPage': 1
},
function(data){
$("body").append(data);
}
);
currentPage.php:
$returnArray['left'] = 'test_left';
$returnArray['right'] = 'test_right';
$returnArray['numLeft'][] = 1;
$returnArray['numRight'][] = 2;
$returnArray['numRight'][] = 3;
print json_encode($returnArray);
I tried to access the data like this:
data.left
data['left']
but it returns blank, how is the best way to access the data in the HTML-file?

I could be wrong, but I don't think the post method assumes a data return-type of json. You could set that by changing the ajax function to:
$.post(
"currentPage.php",
{
'currentPage': 1
},
function(data){
$("body").append(data);
},
"json"
);

Provide the datatype you expect to get as parameter to the .post() method (in your case json):
$.post("currentPage.php",{'currentPage': 1},
function(data){
$("body").append(data);
},
'json' // <-- add the expected datatype
);
I think the default is to treat the result as HTML. Read the documentation.
jQuery.post( url, [ data ], [ success(data, textStatus, XMLHttpRequest) ], [ dataType ] )
urlA string containing the URL to which the request is sent.
dataA map or string that is sent to the server with the request.
success(data, textStatus, XMLHttpRequest) A callback function that is executed if the request succeeds.
dataType The type of data expected from the server.

In JQuery, you need to set the return data type (dataType) to json so the function knows what type of data to expect and process. From the manual:
"json": Evaluates the response as JSON
and returns a JavaScript object. In
jQuery 1.4 the JSON data is parsed in
a strict manner; any malformed JSON is
rejected and a parse error is thrown.
(See json.org for more information on
proper JSON formatting.)
You can do this with the full $.ajax() call, or you can use $.getJSON(). There is no HTTP POST shortcut to return JSON (i.e. $.postJSON doesn't exist), but you can supply the dataType parameter to $.ajax() or just add the parameter to $.post() . When you have a JSON object, use json.keyName to access the data.
$.ajax({
url: "currentPage.php",
data: {
'currentPage': 1
},
dataType: "json",
type: "post",
success: function(data) {
$("body").append(data);
}
});

Related

What's diffrence in jQuery ajax dataType="json" vs JSON.parse()

Is there any real diffrence between using dataType='json' and parse response by JSON.parse(response) in jQuery Ajax?
$.ajax({
url: path,
type: 'POST',
dataType: 'json',
data: {
block : lang,
},
}).done(function(response, textStatus, jqXHR)
{
output = response;
});
VS
$.ajax({
url: path,
type: 'POST',
data: {
block : lang,
},
}).done(function(response, textStatus, jqXHR)
{
output = JSON.parse(response);
});
dataType: 'json':
Sets the Accept request header to tell the server that JSON is the desired response format
Attempts to parse the response as JSON regardless of what the server's Content-Type response header says the format is. (jQuery's default behaviour is to use the Content-Type to determine the correct parser).
JSON.parse:
Attempts to parse the response data as a string of JSON regardless of what it actually is (if the server responds with correctly labelled JSON, this will error since it will have already been parsed by jQuery).

Abstracting an AJAX call so I can make my code more dynamic

I am trying to take a typical jQuery AJAX call and wrap it in its own function so I can call it with different parameters to make it more dynamic. I seem to be missing something about the success or with callbacks in general. The basic function is to pass JSON to a Google charts implementation. This works if I hardcode the JSON but I want to pick it up out of my REST API. Right now I have this small bit of code:
var getAjax = function (url){
$.ajax({
url: url,
dataType: json,
success: drawChart
});
}
var drawChart = function (data) {
jsonData = data;
console.log(jsonData);
// Create our data table out of JSON data loaded from server.
var jsonDataTable = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
//var chartPie = new google.visualization.PieChart(document.getElementById('pie'));
//var chartBar = new google.visualization.BarChart(document.getElementById('bar'));
var chartJson = new google.visualization.BarChart(document.getElementById('json'));
//chartPie.draw(trailerData);
//chartBar.draw(chewyData);
chartJson.draw(jsonDataTable);
}
console.log('got here');
getAjax("data/dashboard0");
When I check the console I can see a 200 from jQuery but I get nothing in my window. I also tried using the getAjax(data) to define the function but in my reading I saw I should do it like this but I am not quite sure which approach is the correct one.
I imagine your syntax error is preventing the code from working...
The dataType should be a string:
dataType: 'json',
Note on response data - If you need the raw data, rather than a parsed data object, you can get that from the raw XHR... no need to unwind the parsed data into another string.
var drawChart = function (data, status, jqXHR) {
var jsonString = jqXHR.responseText;
var parsedData = data;
//...
You should instead return a promise in your function, then resolve it via .then(). success: drawChart is not very dynamic. Observe the following...
var getAjax = function (url){
return $.ajax({ url: url, dataType: 'json' });
}
[...]
getAjax('data/dashboard0').then(function(response) {
// callback - do drawing tuff
});
console.log('got here before callback')
Check out the jQuery deferred docs for more information
The success's method first argument is parsed. If you need a JSON string then you have to JSON.stringify(responseData) which will return a JSON string.
Even if you set dataType: 'json', jQuery will still parse the response.
Please read the jQuery Docs for dataType:
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.)

Jquery - Ajax: SyntaxError: JSON.parse: unexpected character

I am receiving the following valid JSON from my server:
[{"name":"Bubble Witch Saga 2","impressions":10749},{"name":"Grinder","impressions":11284},{"name":"Loovoo","impressions":12336},{"name":"Injustice God Among Us","impressions":12786},{"name":"Bookmyshow","impressions":13182},{"name":"Angry Bird","impressions":15404},{"name":"Flipkart","impressions":16856},{"name":"CNN-IBN","impressions":17230},{"name":"Fore Square","impressions":17595},{"name":"NDTV","impressions":19542},{"name":"Whatsapp","impressions":19976}]
But I keep getting an error in my console saying "JSON.parse: unexpected character." This is my client-side code:
$.ajax({
'type': 'get',
'data': {},
'dataType': 'json',
'url': 'dashboard/data/'+type,
'complete': function(data) {
var top10Value = JSON.parse(data);
$.each(top10Value, function(key,value){
console.log(key+" -- "+value);
});
}
});
Why am I getting this error?
When you specify dataType : json, result is already parsed in jQuery.
Moreover, complete
function argument is returning an object representing the result not the result itself.
That case you should use var top10Value = JSON.parse(data.responseText);
jQuery is clever enough to parse the response as it is, even if dataType isn't specified.
In your case, it is specified and therefore, it is already parsed and data is the parsed JSON object.
What you are doing is therefore parsing an Object.
Doc says:
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). The available
types (and the result passed as the first argument to your success
callback) are:
data returned already json format only,
$.ajax({
'type': 'get',
'data': {},
'dataType': 'json',//Return Json Format
'url': 'dashboard/data/',
'complete': function(data) {
//data returned already json format only
//var top10Value = JSON.parse(data);
$.each(top10Value, function(key,value){
console.log(key+" -- "+value);
});
}
});

Ajax .done() no data

I am using the following jquery to make an ajax call:
$.ajax({
url: "/projects/project/xGetProjectStatus",
type: "GET",
dataType: "json"})
.done( function(request){
alert(request.responseText);
var data = JSON.parse(request.responseText);
if(data.success){
//stuff here
}
})
The alert pop up always says that responseText is undefined. The page I am "get"ting is well formatted JSON and if I run these commands in the console one at a time everything works fine. What is wrong?
You're looking for responseText in the response, it won't be there. You'll find it instead on the jqXHR object itself (which is the third parameter passed to your done() function, and also returned by your whole $.ajax() call).
And because you have dataType: "json" the response is already a JSON parsed object.
Change this:
.done( function(request){
alert(request.responseText);
var data = JSON.parse(request.responseText);
if(data.success){
//stuff here
}
})
To just this:
.done( function(data){
if(data.success){
//stuff here
}
})
When you set the dataType in a jQuery.ajax call it will be returned as a parsed object. So your request object in .done is actually your parsed json string
If you don't want jQuery to automatically parse your JSON you can remove the datatype from the call.
$.ajax({
url: "/projects/project/xGetProjectStatus",
type: "GET"
}).done( function(request){
alert(request.responseText);
var data = JSON.parse(request.responseText);
if(data.success){
//stuff here
}
})
This is because the first parameter of the done function is not the XHR object but the contents of the responseText as an object already. jQuery handles all that for you and so there's no need to do any manual conversion.
the done function is called whenever the ajax call is successful anyways so no need to re-check it and the fail function is called when a response other than 200 is returned.

jQuery: Yahoo Autocomplete/Autosuggest

I'm trying to retrieve yahoo autocomplete.
Yahoo's JSON url is this: http://ff.search.yahoo.com/gossip?output=fxjson&command=query
So I have:
$("selector").autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ff.search.yahoo.com/gossip",
dataType: "jsonp",
data: {
"output" : "fxjson",
"command" : request.term
},
success: function( data ) {
response(data[1])
}
})
}
});
And here is an example: http://jsfiddle.net/yQbdb/
Can someone spot a mistake or what I'm I doing wrong? It should work.
Thanks
Setting output to jsonp works for me.
See example query for the structure of the output.
The explanation is below.
Code is HERE.
$("#wd6450").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://ff.search.yahoo.com/gossip",
dataType: "jsonp",
data: {
"output": "jsonp",
"command": request.term
},
success: function(data) {
var suggestions = [];
// for each element in the data.gossip.results array ...
$.each(data.gossip.results, function(i, val) {
// .. push the value of the key inside our array
suggestions.push(val.key);
});
// call response with our collected values
response(suggestions);
}
});
}
});
Explanation:
By using dataType: "jsonp" jQuery expects the output format to be in JSONP. When you make a call from your code using output: "fxjson" the URL looks like this but as you can see the output is not a valid JSONP, because the callback was not called.
On the other hand when you specify output: "jsonp" the query looks like this and as you can see the output is a valid JSONP - the callback was called.
You linked a Amazon example in the comments. $.ajax() call there will try to URL like this. Output from Amazon's webservice is valid JSONP, because callback is called with all the data.
So the result is: Yahoo webservices will return format in JSONP if you provide ?output=jsonp parameter in the URL by configuring $.ajax() with output: "jsonp". Amazon's webservice returns this format by default without any extra parameters. This is webservice specific configuration and must be consulted with its documentation or other related resourcers.
Information about JSONP available HERE.

Categories

Resources