Getting JSON in nested ajax calls - javascript

The http request sent to some 'request_url' returns json response in format {'succes': 1, 'html': 'thestuff'}
so when
jQuery.ajax({
url: 'request_url',
success: function(response){
alert(response.html); //'thestuff' is here as expected
}
});
'thestuff' can be found in response.html as expected. But if this ajax is called inside the 'success' callback of another one ajax request then the response.html is coming empty and 'thestuff' is going to 'response'.
jQuery.ajax({
url: 'some_other_url',
success: function(some_other_response){
jQuery.ajax({
url: 'request_url',
success: function(respose){
alert(response.html); //there is nothing
alert(response); //I see 'thestuff' which is expected in 'html'
}
})
}
});
Why does it happen?
Update: 'thestuff' contains some js code with {} I can suppose something can get confused but why it works well with single (not nested) ajax request.

Not enough reputation to comment so adding as an answer
Here is expanding on charlietfl comment of using dataType.
I made it work using dataType="json". Json has to be strictly formatted though as per jQuery documentation.
jQuery.ajax({
url: 'some_other_url',
success: function(some_other_response){
jQuery.ajax({
url: 'request_url',
dataType:"json",
success: function(response){
alert(response.status); //there is nothing
alert(response); //I see 'thestuff' which is expected in 'html'
}
})
}
});
request_url should return something like this (note, quotes should be used instead of apostrophes)
{"status":"s","html":"some stuff"}

Related

Ajax request getting / receiving an incomplete response (limitation?)

I'm doing a simple ajax request on a html file to get it's code.
(Actually I don't need the type:"Get", because it doesn't do anything)
jQuery.ajax({
type: "GET",
url: "page-2.html",
dataType: "html",
success: function(response) {
alert(response);
}
});
The response is incomplete. The html file has 400 line sof code but the alert doesn't give me the full file. It is incomplete and stops at line +-130.
It seems that there is some character limitation. Is this possible?
The same happens when I use $.get()
Note: I also get a "Syntax Error -> page-2.html" in the console. Maybe both issues are connected.
jQuery.ajax({
type: "GET",
url: 'page-2.html',
dataType: "html",
success: function(response) {
console.log(response);
alert(response);
}
});
You were missing '' around page-2.html that's why there is error in console.
There is no issue with your ajax request because your script is perfectly working.if you get some error with response means there is some mismatched tag or html format issue that's why u got that error in response.
There is not need to encode URL in single quote ('') or double quote ("") in ajax request with this script.
Please verify your html code in page-2.html.

eval function not working in ajax post

So I am using ajax to post a serialised form to a php script and then on success alert the returned data.
My code works fine on my local environment, but uploaded, the eval() function mucks everything up.
here is my code:
function post_that_shit(formIdToSerialize, postUrl) {
var serializedData = $("#"+formIdToSerialize).serialize();
var post_url = postUrl+".php";
//alert(serializedData + "\n" + post_url);
$.ajax({
url: post_url,
type: "POST",
data: serializedData,
success: function(data){
data = eval('('+data+')' );
console.log(data.msg);
if(data.reload == 'yes'){
window.location.reload();
}
if(data.relocate != 'no'){
window.location.href = data.relocate;
//alert(data.relocate);
}
if(data.msg != 'no'){
$(".message").html(data.msg);
//alert(data.msg);
}
//alert('relocate: '+data.relocate);
}
});
}
So it is pretty simple.
The php echo out a json encoded array like so:
echo json_encode(array('msg' => $errors, 'relocate' => 'no'));
And depending on what is echoed, the msg is displayed or the user relocated.
Why do I get the error of SyntaxError: Unexpected token ')' when I use the code online?
Locally it works just fine :(
Thanx for your help
Chris
You don't need to use eval(). Just set the dataType option to 'json' and the data will be internally parsed to an object by jQuery
$.ajax({
url: post_url,
type: "POST",
dataType:'json',
data: serializedData,
success: function(data){
console.log(typeof data); // returns "object"
In addition setting the proper content type header for application/json at server also helps
I don't know why you need the eval() function in that place. It's a wrong coding. Your solution is put the data type to JSON and the ajax function treats automatically as a json:
$.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedData,
success: function(data){
console.log(data.msg);
if(data.reload == 'yes'){
window.location.reload();
}
if(data.relocate != 'no'){
window.location.href = data.relocate;
//alert(data.relocate);
}
if(data.msg != 'no'){
$(".message").html(data.msg);
//alert(data.msg);
}
//alert('relocate: '+data.relocate);
}
});
First of all, eval is evil. Don't use it... never ever! It's like a bomb ready to detonate.
Secondly, parsing json can be done natively in Javascript. No need for eval.
You can use JSON.parse and it will return you an object parsed by the string containing the json text.
eval is used to evaluate code, in other words, it is executing javascript not json. When eval returns an object, it is simply a side effect of JSON being a subset of JavaScript. In other words, any string formatted as json can be evaluated to JavaScript. But JavaScript cannot be formatted to JSON. There is no representation of Date, Function and many more complex objects. That said, when using eval, you're actually executing JavaScript and that is the big problem here. It could execute potentially dangerous code while parsing JSON simply requires parsing data into a data structure and nothing more.
Here more about JSON: https://fr.wikipedia.org/wiki/JavaScript_Object_Notation
So it would allow anyone to add somewhat some javascript that would then get executed by your use of eval. It could allow someone to execute code on the browser of other users. It could be used to steal passwords for example or steal any kind of private information that wouldn't be accessible otherwise.
jQuery on the other hand allow you to parse json natively by using the dataType attribute as 'json'. Like this:
$.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedData,
success: function(data){
console.log(data.msg);
Or using JSON.parse
$.ajax({
url: post_url,
type: "POST",
data: serializedData,
success: function(data){
data = JSON.parse(data)
console.log(data.msg);
Also as charlie pointed out, parsing by ourselves JSON means that we have to wrap it in a try catch, because parsing might fail if the json isn't valid.
But using jQuery gives us a way to handle that easily.
You could rewrite your code such as this:
var req = $.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedDate
});
req.done(function (data) {
// Success
});
req.fail(function () {
// Error something went wrong
});
The advantage of using the promise form is that you can chain calls to have clean async code instead of the callback hell and infinite function nesting.

JSONP via getJson not working?

I have getJson like this:
$.getJSON(userUrl+'scanp?callback=?', { 'someparametar': 100 }, function(data){
console.log(data);
});
and I do get a response from my url, and it looks like this:
'"jQuery1110010384737118147314_1401820556204({'hasWon':'false','code':'120580e9fce67a4921f31af7ffa358cc10c83b10','defaultReward':'{\"secure_url\":\"https://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"url\":\"http://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"resource_type\":\"image\",\"format\":\"png\",\"height\":960,\"width\":640,\"signature\":\"a8ca9bb867e0a3d99e1666b7891e8f918d81e627\",\"version\":1401318096,\"public_id\":\"k6jrm2pehwycmehrkicz\"}''}"'
Any idea why I don't get any response when I console.log it?
With 'callback' in your querystring, JQuery wraps the response with a randomly generated method name. To get JSON (without method name), remove 'callback=?' from querystring.
If your server supports JSONP, you can make a call like this :
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(JSON.stringify(json));
},
error: function(e) {
console.log(e.message);
}
});
Hope this helps.
Well I figured it out, the request I wrote was perfectly fine. The thing that was causing the the problem was response I was getting from server.
It was JSON stringified before return.

SyntaxError: missing ; before statement jquery jsonp

I am using below code to access rest service hosted on another domain.
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType:"jsonp",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
I am able to get the data correctly, but I get this error in firebug in mozilla:
SyntaxError: missing ; before statement
{"Hello":"World"}
Can anyone suggest me what I am doing wrong here? Even though Json data is valid. I tried all the suggestions posted in this question But still I am getting same error.
If it's really JSON you ask for, don't set "jsonp" as dataType, and don't provide a callback :
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
the format of JSON and JSONP are slightæy different
JKSONP is a function invocation expression
callback({"hellow":"world"});
whereas JSON is simply a serialized object
{"Hello":"world"}
fromyour posting it would seem that the server is returning JSON and not JSONP
So you either need to change the server to reply correctly (The actual callback name is a get parameter to the request). You should do this if you are using the ajax call across domains
If you are not using ajax across domains stick to regular JSON

making ajax work on JSBIN

I'm trying to get ajax to work in JSBIN like demonstrated in this video. What have I don't wrong. Seems like it ought to work!
$(document).ready(function(){
$.ajax({
type: "get",
url: "http://jsbin.com/ipefom/1/js",
dataType: "json",
success: function(returnedData){
console.log(returnedData)
}
});
});
http://jsbin.com/ocerag/3/edit
I don't understand where my parseerror comes from.
Your json is invalid:-
There is as edit:8 in json which is misplaced and also you have duplicate keys while the number is repeated again. Seems like the same set was copy pasted again.
"968":"a","969":"a","970":"a","971":"a","972":"a","973":"a","974":"a","975":"a","976":"a","977":"a","978":"a","979":"a","980":"a","981":"a","982":"a","983":"a","984":"a","985":"a","986":"a","987":"a","988":"a","989":"a","990":"a","991":"a","992":"a","993":"a","994":"a","995":"a","996":"a","997":"a","998":"a","999":"a"} edit:8
{"0":"a","1":"a","2":"a","3":"a","4":"a","5":"a","6":"a","7":"a","8":"a","9":"a","10":"a","11":"a","12":"a","13":"a","14":"a","15":"a","16":"a","17":"a","18":"a","19":"a","20":"a","21":"a","2
Because it is not returning valid json, when you try
dataType: "html", in place of dataType: "json", then it will show that the returning is not a valid json.

Categories