I am trying to parse json from a request, but I keep getting null. When I do console.log(data), it prints null.
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
dataType: "jsonp",
success: function(content) {
var data = jQuery.parseJSON(content);
console.log(data);
}, data: {
q: 'select * from html where url="http://www.google.com"',
format: "json"
}
});
I think that your "content" is probably already parsed for you by jQuery. What happens when you:
console.log(content);
??
(Actually now that I think of it the content is parsed by the browser when it receives the response script body.)
Related
I'm stumped why my Flask called JSON data is not being read by ajax success wait statement that works very well elsewhere. I realize the Success: statement is supposed to wait for data to returned and it does, but then the data returned isn't accessible as any JSON. There are no console nor browser console errors to indicate why data is considered 'invalid'
Flask Function
#blueprint.route('/target_liner')
def target_liner():
ind_id = int(request.args.get('ind_id'))
label = "1508 Loss Correction"
data = '[{"Program_Name":"' + label + '"}]'
return data
JSON Data
[{"Program_Name":"1508 Loss Correction"}] // This is confirmed legal JSON
Javascript
function updates() {
$.ajax({
url: "/target_line",
method: "GET",
data: {
ind_id: 1508
},
success: function (data) {
console.log(data);
alert(data); // This shows the JSON string correctly in Chrome Inspect console
alert(data.Program_Name);
alert(data[0]['Program_Name']);
alert(data[0].Program_Name );
}
});
};
updates();
The data retuned is a String. You can either do a JSON.parse(data) after the success or you can use dataType: 'json' in your ajax request. you might get a parse error if your JSON String is not formed properly when you use dataType: 'json' .
You have three possibilities:
in your flask change return data to return jsonify(data);
add dataType: "json", to your ajax call as per comment by #Rocket Hazmat;
add to the succes response a conversion from string to json: data = JSON.parse(data);
$.ajax({
url: "/target_line",
method: "GET",
data: {
ind_id: 1508
},
success: function (data) {
data = JSON.parse(data);
console.log(data);
console.log(Object.keys(data[0])[0]); // print: Program_Name
console.log(data[0].Program_Name ); // print: 1508 Loss Correction
}
});
Given below is the ajax call from the javascript
let dataX = {"VERSION": "iVersion_100", "ITOKEN": "iToken", "METHOD":"GSB"};
$.ajax({
type: "POST",
url: "target.php",
data: dataX,
dataType: "json"
})
.done(function(data) {
console.log(data);
});
Now, here is the simple target.php
<?php ob_start();
$iVersion = $_REQUEST['VERSION'];
$iToken = $_REQUEST['ITOKEN'];
$iMethod = $_REQUEST['METHOD'];
echo $iVersion;
?>
I was expecting to see "iVersion_100" in the console log. Instead, it is returning NULL. I have almost broken the wall with my head banging. Request your help desperately. Thanks in advance.
You're setting dataType: "json"
but the PHP responds with iVersion_100
this is not valid JSON
as you have no .error handler, it seems jQuery "silently ignores" this error condition and the end result is that .done is never called
change your code to
let dataX = {"VERSION": "iVersion_100", "ITOKEN": "iToken", "METHOD":"GSB"};
$.ajax({
type: "POST",
url: "target.php",
data: dataX,
dataType: "json"
})
.error(function() {
console.log(arguments);
})
.done(function(data) {
console.log('hello');
console.log(data);
});
You'll see there is an error, "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
Since you are using dataType: "json" in this code your are telling ajax to get return data in json format.
In place of sending data in json your are just echo $iVersion; echo the data. If you want to use json as dataType please parse data before output it like this echo json_encode($iVersion); and you will get the data.
Or
If you want to use simple out put in none json format please Remove dataType: "json" from ajax attribute. You will get the output echo $iVersion;.
I have My jquery function that is returning me data of the formatt:
{"Suggestions":[{"name":"RR Restaurant","category_id":"166","locality":"Gayathri Nagar","listing_info":"listing","random_id":"1ll0f0wJ"},{"name":"Oko Restaurant","category_id":"166","locality":"Kumara Krupa","listing_info":"listing","random_id":"0F7ZGV9p"},{"name":"H2O Restaurant","category_id":"166","locality":"Maratha Halli","listing_info":"listing","random_id":"0JNPOyuP"},{"name":"Taj Restaurant","category_id":"166","locality":"Shivaji Nagar","listing_info":"listing","random_id":"7GeA0Kfq"},{"name":"PSR Restaurant","category_id":"166","locality":"Peenya Industrial Area","listing_info":"listing","random_id":"cRvJCwQ3"},{"name":"ac restaurant","category_id":"166","listing_info":"keyword"},{"name":"Indian Restaurant","category_id":"166","listing_info":"keyword"},{"name":"goan restaurant","category_id":"166","listing_info":"keyword"},{"name":"thai restaurant","category_id":"166","listing_info":"keyword"},{"name":"andhra restaurant","category_id":"166","listing_info":"keyword"}],"ImpressionID":"test"}
I wish to parse the same to get multiple variables with The field "Name" and "Random Id" in different js variables
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
My JSON object seems to be nested with "Suggestions" as the parent. Please help.
If you add a property to $.ajax function you be ensure that is json parsing:
dataType: 'json'
EDIT
To iterate above the string you can use for(in) or each() jquery
json = "[{'key':'value'},{'key':'value']";
for(var i in json) {
console.log(json[i]);
//if you see in console [OBJECT Object] you are
//in a new object you must to iterate nested of this.
}
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
dataType: "JSON", //You need this to be inserted in your ajax call.
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
After insert dataType you can probably do this.
console.log(data.Suggestions);
Also take a look at the API Doc at below url regardless of dataType.
http://api.jquery.com/jquery.ajax/
The data object you are specifying is what will be sent as the arguments to your success method, if you use the GET method.
$("#what).on("keypress", function() {
$.get("/AutoComplete.do", function(response) {
var data = JSON.parse(response);
//data.suggestions = [lots of objects];
//data.suggestions[0].locality = "Gayathri Nagar"
});
});
Okay so here is my problem. I have a simple jQuery Ajax request and I can't get is work when I set the DataType to "JSON".
var form_data = { "id": msg, "token": token };
$.ajax({
type: 'POST',
url: "ajax.php",
data: form_data,
dataType: 'json',
beforeSend:function(){
// this is where we append a loading image
},
success: function(data) {
var thing = JSON.parse(data);
$('.body-item').html(thing.b);
},
error: function() {
alert('error');
}
});
This is my ajax file actually. The ajax.php looks like this:
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$foo = json_encode($arr);
echo $foo;
When I run the jQuery script, I got a 200:OK response with Firebug, and when I take a look at the response I got the following: {"a":1,"b":2,"c":3,"d":4,"e":5}
However I do NOT get anything showed in the .body-item div, nor if I try with alert().
Also if I run the same code WITHOUT the: dataType: 'json' part, I get everything outputted correctly.
What could be the issue here?
When you use dataType: 'json', jQuery calls JSON.parse() and puts the result in data. You shouldn't call it yourself, since data is not a JSON string, it's the parsed object. So just do:
$('body-item').html(data.b);
From the documentation:
"json": Evaluates the response as JSON and returns a JavaScript object.
How should I be passing query string values in a jQuery Ajax request? I currently do them as follows but I'm sure there is a cleaner way that does not require me to encode manually.
$.ajax({
url: "ajax.aspx?ajaxid=4&UserID=" + UserID + "&EmailAddress=" + encodeURIComponent(EmailAddress),
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
I’ve seen examples where query string parameters are passed as an array but these examples I've seen don't use the $.ajax() model, instead they go straight to $.get(). For example:
$.get("ajax.aspx", { UserID: UserID , EmailAddress: EmailAddress } );
I prefer to use the $.ajax() format as it's what I’m used to (no particularly good reason - just a personal preference).
Edit 09/04/2013:
After my question was closed (as "Too Localised") i found a related (identical) question - with 3 upvotes no-less (My bad for not finding it in the first place):
Using jquery to make a POST, how to properly supply 'data' parameter?
This answered my question perfectly, I found that doing it this way is much easier to read & I don't need to manually use encodeURIComponent() in the URL or the DATA values (which is what i found unclear in bipen's answer). This is because the data value is encoded automatically via $.param()). Just in case this can be of use to anyone else, this is the example I went with:
$.ajax({
url: "ajax.aspx?ajaxid=4",
data: {
"VarA": VarA,
"VarB": VarB,
"VarC": VarC
},
cache: false,
type: "POST",
success: function(response) {
},
error: function(xhr) {
}
});
Use data option of ajax. You can send data object to server by data option in ajax and the type which defines how you are sending it (either POST or GET). The default type is GET method
Try this
$.ajax({
url: "ajax.aspx",
type: "get", //send it through get method
data: {
ajaxid: 4,
UserID: UserID,
EmailAddress: EmailAddress
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
And you can get the data by (if you are using PHP)
$_GET['ajaxid'] //gives 4
$_GET['UserID'] //gives you the sent userid
In aspx, I believe it is (might be wrong)
Request.QueryString["ajaxid"].ToString();
Put your params in the data part of the ajax call. See the docs. Like so:
$.ajax({
url: "/TestPage.aspx",
data: {"first": "Manu","Last":"Sharma"},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Here is the syntax using jQuery $.get
$.get(url, data, successCallback, datatype)
So in your case, that would equate to,
var url = 'ajax.asp';
var data = { ajaxid: 4, UserID: UserID, EmailAddress: EmailAddress };
var datatype = 'jsonp';
function success(response) {
// do something here
}
$.get('ajax.aspx', data, success, datatype)
Note
$.get does not give you the opportunity to set an error handler. But there are several ways to do it either using $.ajaxSetup(), $.ajaxError() or chaining a .fail on your $.get like below
$.get(url, data, success, datatype)
.fail(function(){
})
The reason for setting the datatype as 'jsonp' is due to browser same origin policy issues, but if you are making the request on the same domain where your javascript is hosted, you should be fine with datatype set to json.
If you don't want to use the jquery $.get then see the docs for $.ajax which allows room for more flexibility
Try adding this:
$.ajax({
url: "ajax.aspx",
type:'get',
data: {ajaxid:4, UserID: UserID , EmailAddress: encodeURIComponent(EmailAddress)},
dataType: 'json',
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Depends on what datatype is expected, you can assign html, json, script, xml
Had the same problem where I specified data but the browser was sending requests to URL ending with [Object object].
You should have processData set to true.
processData: true, // You should comment this out if is false or set to true
The data property allows you to send in a string. On your server side code, accept it as a string argument name "myVar" and then you can parse it out.
$.ajax({
url: "ajax.aspx",
data: [myVar = {id: 4, email: 'emailaddress', myArray: [1, 2, 3]}];
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
You can use the $.ajax(), and if you don't want to put the parameters directly into the URL, use the data:. That's appended to the URL
Source: http://api.jquery.com/jQuery.ajax/
The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code
var id=5;
$.ajax({
type: "get",
url: "url of server side script",
data:{id:id},
success: function(res){
console.log(res);
},
error:function(error)
{
console.log(error);
}
});
At server side receive it using $_GET variable.
$_GET['id'];