I am new on JQuery. I have this JSON response from the server how could I parse it?
[
{
"note": {
"created_at": "2012-04-28T09:41:37Z",
"updated_at": "2012-04-28T09:41:37Z",
"text": "aaaaaaaaaaafdafasd fasfasd dfa sdfasf asdfa fasdfda",
"lng": 44.5159794497071,
"id": 7,
"deleted": false,
"user_id": 1,
"note_type": "text",
"lat": 40.1884140543842
}
},
[ ... more JSON ...]
]
How could I parse this?
You have to set the data type of the request to "json", and the data will be already parsed in your success callback.
Everything you need to know at the moment is on http://api.jquery.com/jQuery.ajax/
Here is a very simple example of what you can do:
$.ajax({
url: url, // the service URL. Must answer proper JSON
data: { // the parameters of the request. This should be adapted to your case
param1: value1,
param2: value2
},
dataType: "json",
type: "POST",
success: function(resultData) {
// here, resultData is your parsed json
},
error: function() {
// handle error here
}
});
jQuery.parseJSON
Use this jQuery method to parse JSON objects.
If the server outputs actual JSON (the example in the question has errors) and it has the correct content type (application/json rather then the text/html that PHP defaults to) then you don't need to do anything.
jQuery will parse it for you (and present you with a JavaScript object in the success handler).
That's not JSON. What you have posted looks like a PHP array that had brackets wrapped around it to try to make it into JSON.
Use this site to validate your JSON in the future.
Now, to get your PHP array into JSON, use json_encode() and dispatch it to the browser with a specific header.
$array = array( 'test' => 'sure' );
header('Content-type: application/json');
print json_encode($array);
exit;
Now, you'll have actual JSON with which you can use in JavaScript.
$.get( 'yourFile.php',
function(data){
console.log(data);
}
);
Related
I am encountering some really strange behavior when sending JSON over AJAX.
JSON data:
data = {
"name": "box1",
"comment": ["fragile"],
"type_A": [
{
"item": "1",
"attr": [
"big",
"red"
]
},
{
"item": "2",
"attr": [
"small",
"red"
]
},
],
"type_B": [],
"misc": {}
};
POST request:
$.ajax({
url: url,
type: "POST",
// data: JSON.stringify(data),
data: data,
success: function (result) {
console.log("inside success");
},
error: function (error) {
console.log("inside error");
}
});
If I pass in data here without JSON.stringify(), the empty fields type_B and misc get lost/stripped away. But if I do use JSON.stringify() then the backend cannot parse it properly without JSON.parse(). Is there a way to not strip away empty fields without doing a JSON.parse() in the backend?
I tried adding contentType: "application/json" and dataType: "json" to the request but didn't help.
What you have labeled "JSON data" is not JSON. It is a JavaScript object literal. It is part of JavaScript source code. It is not a JSON data file.
When you use jQuery's Ajax functions you can pass a few different things to data.
If you pass it an object, then jQuery will Form URL Encode it.
URL Encoded data has no standard way to represent anything other than a set of flat key=value pairs.
PHP introduced an extension which lets you express arrays and associative arrays by using square brackets in the key names. For example:
array[]=item1&array[]=item2
Each items in the array is represented by a copy of the key.
If you have no items, then there are no keys of that name.
If you use this method of encoding data then you cannot express empty arrays. The closest you could come would be to have an array containing a zero length string.
If you pass it a string, then jQuery will just send it as is.
Using JSON.stringify will convert your object to a string containing JSON data.
JSON is capable of expressing empty arrays.
PHP, however, will not automatically parse JSON formatted requests.
So…
Is there a way to not strip away empty fields without doing a JSON.parse() in the backend?
No. There isn't. You either use a format which doesn't support empty fields, or you use a format which PHP won't automatically parse for you.
I tried adding contentType: "application/json"
This tells the server that the data you are sending is encoded as JSON. If you are sending JSON then you should include this.
It doesn't alter the data you send. You need to encode the data as JSON yourself.
and dataType: "json" to the request but didn't help.
This tells the server that you expect the response to the request to contain JSON. It also tells jQuery to ignore the content-type of the response and parse it as JSON whatever the server says it is.
It has no effect on the data you send.
Jquery processes your data before sending and uses the request's post formdata instead of putting JSON in the body of the request.
To avoid this, use processData: false and contentType: 'application/json':
$.ajax({
url: url,
type: "POST",
processData: false,
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
console.log("inside success");
},
error: function (error) {
console.log("inside error");
}
});
I have jquery ajax call which will go to a .js file and returns JSON
var validate = function () {
alert('test string');
}
$.ajax({
url: "JS/JQB/SampleData/Filters.js",
async:false,
success: InitailiseJQB
});
Filters.js file contains below JSON,
[{
"id": "Group",
"filters": [{
"id": "49be7d78-4dcf-38ab-3733-b4108701f1",
"validation": {
"callback": validate
}
}]
}]
in the above JSON validate is the javascript function but the problem is when i am requesting for the JSON using ajax call, it is throwing run time error called JavaScript runtime error: Invalid character
On success, are you sure you mean to call:
success: InitailiseJQB
There may be an accidental spelling error there.
I have one javascript file which sends AJAX request to php file, which fetch some data from database. If php finds any data it return it as json object in response, but when it does not find any recrod in database based on query, it return a message something like "not match found".
It means javascript either get string message in "not match found" or json object.
I am trying to check if xmlhttp.responseText is json object or a string, but have not been succedeed. Any idea about how to solve this problem?
Should I convert "not match found" string into a json and send back to javascript and then parse it or there is any better way to solve this?
Thank you
BR
I don't think you need to parse your error message "No match found". There's two options: either create an if/else statement in the PHP file that the ajax calls, or you can attempt to encode the JSON in the php file and if it's unsuccessful, you can just write out a "No match found" message in the error part. I highly recommend using the $.ajax call because it can handle the responses better.
JS
$.ajax({
url: "myFile.php",
dataType: "json",
success: function(data) {
var myNewJsonData = data;
alert(myNewJsonData);
},
error: function() {
alert("No match found.");
}
});
PHP (myFile.php)
<?php
//Do your query business and stuff here
//Now let's say you get back or store some array that looks like this for example
$myArray = array('name' => 'Mike', 'age' => 20);
/* Now attempt to create a JSON representation of the array using json_encode() */
echo json_encode($myArray);
?>
When you echo it out, it gets sent back through either the $.ajax's call success or error function as a parameter (which I named data), depending on whether or not there was an error reported back. If there was not, then success is called, and if there is an error, well then you can guess which one gets called. json_encode will create a JSON representation of the array of data that you get back from your query.
Maybe I'm not understanding your question, can't you just print out an error using something like this:
$.ajax({
url: "myphpfile.php",
dataType: "json",
success: function(data){
alert(data.info);
},
error: function(xhr, status, error) {
alert(status);
alert(xhr.responseText);
alert(xhr);
}
});
Then do something inside of the error block?
Even though I totally agree with Patrick Q's comment, there is another option that has not been mentioned. You could also set the Content-Type of the response to indicate if it's json or text:
#header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
and
#header( 'Content-Type: text/plain; charset=' . get_option( 'blog_charset' ) );
or even,
#header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
Then you could check the response's content type to make a decision:
$.ajax({
type: "POST",
url: "xxx",
data: "xxx",
success: function(response, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
//do something
} else
if (ct.indexOf('json') > -1) {
// handle json here
}
}
});
A.
Here's what I'm trying to accomplish:
User enters JSON in a textarea element.
{
"test":[
{"a":"b"}
]
}
Client side JavaScript parses the JSON.
myObject = $.parseJSON($("#my-textarea").val());
JSON is sent over an ajax post request to the server with
dataType: json,
data: {"my_object": myObject}
Post parameters are checked on the server side in sinatra and the JSON looks like this now.
{
"test": {
"0": {
"a": "b"
}
}
}
I'm wondering why the test array was changed into a hash and if there's anything I can do to avoid that. I'm thinking that the original JSON is improperly formatted, but I'm unsure.
EDIT:
Here is a stripped down version of the ajax request and controller action.
function test() {
return $.ajax({
url: "/test",
type: "post",
dataType: "json",
data: {"test":[{"a":"b"}]},
success: function(response) {
}, error:function(jqXHR,exception) {
ajaxError(jqXHR,exception);
}
})
}
post '/test' do
puts params
return {}
end
I would stringify the resulting JSON object before you send it, like this:
dataType: json,
data: {"my_object": JSON.stringify(myObject)}
If you have to support browsers that don't have JSON natively, you can conditionally import the json js to add that support. (jQuery does not natively have a JSON stringify method).
Try this
var test = "{ \"test\":[{\"a\":\"b\"}]}"
$.parseJSON(test) // or even JSON.parse(test)
If you trace the object before it goes to the server side you will confirm that it was parsed correctly. So the problem is in sinatra I would say.
Just first check what's the parse result before doing the server call.
If you don't know if it's your client doing the bad translation, create a native javascript object (without the parse) and send it instead. If it's still bad, I doubt the problem is on the client.
Output I got on the chrome console:
JSON.parse(test)
Object {test: Array[1]}
test: Array[1]
0: Object
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);
}
});