I am calling the twitch TV API to get users info from one endpoint and I want also to call another endpoint in the same API to check if those users are streaming live or not, but only if the first ajax call is successful. Can anyone give me a hint on how to do it?? My first call below:
var getUserInfo = $.ajax({
type: "GET",
url: "https://api.twitch.tv/helix/users/?login=ESL_SC2&login=freecodecamp&login=noobs2ninjas",
// contentType: ('application/x-www-form-urlencoded; charset=UTF-8'),
crossDomain: true,
headers: {
"Client-ID": "5k4g3q59o69v6p9tudn39v50ro1mux",
},
dataType: "json",
success: function (json) {
console.log(JSON.stringify(json, null, 2));
},
error: function () {
console.log("OOPS!!!");
},
})
The jQuery ajax function is built using the callback design to deal with its asynchronicity. You have two callbacks, success and error, one of which will fire when you receive a response from the Twitch API. If you want to make another ajax request depending on if your previous request was successful then you can simply write a very similar ajax request inside your success callback function pointing to the new location you are trying to acccess. I would recommend splitting that off into a separate function to maintain the readability of your code however.
The success function only runs if the call was successful.
Trigger the code for the second request from the success function.
Related
I want to taking data out of the Ajax Jsonp.
Why doesn't work this app?
Please Help.
var res;
$.ajax({
url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35416355&dimensions=ga:pagePath&metrics=ga:users&filters=ga:pagePath==/p/etkinlikler.html&start-date=2015-10-25&oauth_token=AQAAAAAVs-uLAASpEAf-MmJK_kHgpU9Fwv8WArM',
dataType: 'jsonp',
async: false,
success: function(result) {
res = result.totalsForAllResults["ga:users"];
}
});
$("div").html(res);
https://jsfiddle.net/q6vfgemp/
The data is retrieved correctly but since the request is async you cannot set the html outside of the success callback, put it inside the success callback and it will work.
Also it's a good practice to console.log the data when you're not sure where the problem is to make sure it is retrieved successfully.
Edit: Here is why the async: false option is not working, check the accepted answer for the details.
In JSONP you should add a callback parameter to the request.
The response would be a script calling your callback with the requested data.
So, you should call a URL like this:
http://domain.ext/?callback=xxx
And you should have a function with name "xxx":
function xxx(data) {
// Here you can manage the received data
}
Also, the requested resource should support JSONP, if it doesn't you will not receive anything in your callback.
Since the request is asynchronous, your code sets the "div" before the result is actually retrieved. In order to make sure you retrieve the result, and then set the div, do this:
$.ajax({
url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35416355&dimensions=ga:pagePath&metrics=ga:users&filters=ga:pagePath==/p/etkinlikler.html&start-date=2015-10-25&oauth_token=AQAAAAAVs-uLAASpEAf-MmJK_kHgpU9Fwv8WArM',
dataType: 'jsonp',
async: false,
success: function(result) {
res = result.totalsForAllResults["ga:users"];
$("div").html(res);
}
});
Is there a way to confirm whether a particular ajax request in async or sync in Browser Dev Tools like Chrome Developer Tools or Firebug.
For ajax request HTTP Request Header does not indicate whether its sync or async.
X-Requested-With:XMLHttpRequest
no you cant do that but you can run this in console or add this to your code
XMLHttpRequest.prototype.open = (function(open){
return function(method, url, async, user, password) {
console.log("xhr call: "+url +"isAsync: "+async);
open.apply(this, arguments);
};
})(XMLHttpRequest.prototype.open);
it logs the infomation :D hope its helpful
I don't know if you are still looking for an answer but I hope this will help someone!
In chrome browser navigate to rightClick/inspect/networkTab/xhr? move the cursor to the time where your requests are processed as shown in below pic:
THIS IS MY ASYNC CODE(default ajax)
`$.ajax({
type: "GET",
contentType: "application/json", // data type of request
url: //url,
data: //data,
dataType: "json", // data type of response
success: function (result) {
// some code here
}
});`
I was making a series of ajax calls to the localhost and each call was linked to the previous call's response. But I got wrong outputs because all the ajax requests were being sent at almost the same time and the responses(blue in color) which should have been received serially were disordered. The timing diagram below shows the issue perfectly(look at the waterfall tab).
THIS IS MY CODE FOR SYNC CALLS(async: false in ajax)
$.ajax({
async: false,
type: "GET",
contentType: "application/json", // data type of request
url: //url,
data: //data,
dataType: "json", // data type of response
success: function (result) {
// some code here
}
});
Now how to know if async: false is working?
You can see that the timings of ajax calls in async mode are overlapping each other and also the timings for calls in sync mode(async: false) are distinctively separate thus proving that sync calls [async: false] are working fine. If the timings still overlap then sync calls are likely not working, unlike my case.
All ajax requests are asynchronous others wise if its specified to be synchronous hence why they call it Asynchronous JavaScript and XML (AJAX). To make an ajax request synchronous you would have to pass in false inside the open method of an XMLHTTPRequest object like this
var xhr = new XMLHttPRequest();
xhr.open("POST", "file to get.php", false);
The third parameter specifies it as synchronous but it defaults to true
I am pretty much new to ajax and working on jquery ajax request. Ajax callback is not calling success method. Interaction is between cross-site domains.
My AJAX request looks like
$.ajax({
timeout: 20000,
url: 'test.com',
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
console.log('callback success');
this._cache = data;
localStorage.token = data.access_token;
} });
There are no errors in this call.
This ajax request is not calling success function.Request is returning json data. it's just success method is not getting called.
This ajax request is not calling success function.
Get request is getting fired successfully. I can even trace the response in fiddler with 200 http response.For some reason success method is not getting called.
it's returning json object, which I've traced in fiddler
You're telling jQuery to expect a JSONP response, so it is trying to execute the JSON document as if it were a JavaScript script (because that is what JSONP is). This fails because it is not JSONP.
Either return JSONP instead of JSON or (assuming the server returns the correct Content-Type) remove dataType: 'jsonp',.
ok... I came here with the same problem... and when I read that specifying datatype:jsonp never calls success as a callback per #mondjunge from a comment above, it started me thinking about some behavior I saw earlier from my code and that maybe datatype:json might have the same behavior for what ever reason here too.
So after reading this page I took out my datatype declaration from my ajax request and my servlet returned the proper data payload, returned a 200, and jquery called the success function finally and modified my DOM.
All those steps happened except the last one until I removed my datatype from my ajax call. NOT what I was expecting!
Hopefully someone else can shed some light on why this happens... for now at least the few that don't lose their minds to this issue that find this post can do this in the mean time.
Check if your ajax is executed
Check it's status. If response code is != 200, than you should add error method also, for error handling.
Try this:
$.ajax({
timeout: 20000,
url: 'test.com',
method: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
console.log('callback success');
this._cache = data;
localStorage.token = data.access_token;
},
error: function(xhr, error){
console.debug(xhr); console.debug(error);
},
});
If I make an ajax call to a controller.... what needs to happen in the controller so that the ajax call then calls
1) complete:
2) success:
3) error:
4) any other callbacks that exist.
For ex. I have this ajax call.
$.ajax({
url: "/ContactPartial/ContactUs",
type: "POST",
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
complete: function () { },
success: function () { },
error: function () { }
});
In other words, what can I do inside /ContactPartial/ContactUs to control which of the 3 (complete,success,error) gets called after the controller code executes.
Also, how is this related to related to return Json(new {some: data});
These three callbacks are related to the status of the Ajax call. These are called depending on success of the call. For complete details refer to the documentation
So, if the server responds with a success (200), then both the Success and the Complete handlers would be called. In the complete handler, you might put some code to dismiss a modal window (regardless of success or error), and in the success function, you might put code to let the user know the call was successful, reload a grid view, etc. Also, keep in mind that the callback functions don't have to be anonymous functions, they can be defined functions that are shared among several Ajax calls.
EDIT:
If you are wanting to force the server to generate an error, take a look at:
The HttpResponse class, specifically the StatusCode property
This SO post explains more too (generating a 401 error)
I am doing AJAX with JQuery but every time the "onSuccess" event must be executed after another AJAX request disconnected.
Here is the code:
d.ajax({
url: f.options.url.offline,
dataType: "jsonp",
jsonp: "callback",
cache: false,
data: {
status: "offline",
ticket: f.connection.options.ticket
},
success: function(g) {
f._offlineSuccess()
},
error: function() {
f._offlineError()
}
})
All my AJAX requests are JSONP, and when the above code is triggered, there is another AJAX connection (long polling request, last about 10 senconds) already established in the mean time. So the "f._offlineSuccess" function is always executed after another AJAX connection disconnected.
I can not see any relationship between the two AJAX requests, and I don't know why the "onSuccess" function must be executed after another AJAX connection stopped.
Any help is appreciated~
================================
updated:
I just found out if I have two JSONP connection at the same time, the "onSuccess/onFailure" function will be blocked. I don't know if some one encountered the same problem before?
Ajax requests are asynchronous. so a new request is not going for the previous one to finish. If you want that behaviour use async parameter to false, or use the complete() function to call for another request. This will fire only when the first request is finished.
UPDATE
For JsonP use jQuery.getJSON() and do the second request on callback if the call was succesfull.
function (data, textStatus) {
// data will be a jsonObj
// textStatus will be one of the following values:
// "timeout","error","notmodified","success","parsererror"
this; // the options for this ajax request
}
If you use firebug - net tab, you will be able to see the full url of the two jsonp requests. You should be able to see the callback function names on the end of the url. Are these different or the same? I can only assume they are the same.