Hello I have some functions written in a JS file that I need help with, I have three methods structured like so:
writeDetailsToDB(); //writes details to db and returns a status to indicates success
writeOtherDetailsToDB(); //writes details to db and returns a status to indicates success
checkOk(); //checks to see both status were successful
The problem I am having is that the checkOk() is being called before the other two methods can finish executing so it always indicates failure I need to be be able to wait for the other two methods to finish before executing checkOK(). Having looked a AJAX success methods I always find an .ajax() method and URLs and I don't see how they fit my problem.
Please can someone help me!
Use the success handler of each to progress and perform the next method in sequence.
You can find documentation and examples of how to use the "success" of the call here: http://api.jquery.com/jquery.ajax/
EDIT: why the anonymous downvote?
Related
I have an object which acts as a client side API Client which exposes several functions which all return jQuery ajax() objects. Some of those ajax calls have .done() and .fail() calls chained directly onto them because they are actions which need to be taken every time the API responses come back before the rest of the js code is allowed to deal with the response. Pretty standard stuff.
I need to kick off a variable number of API requests, wait for all to fail or succeed, and then continue processing. For the examples I will create, I will simplify this down to just two ajax calls.
So I create an array to hold the returned ajax objects, and then use $.when().apply(null, deferreds).then(function(){//do something after both ajax requests complete}). When the calls complete successfully, everything works great. When calls fail (such as if the ajax call 404s), things are not so great.
The problem is that .then() doesn't seem to detect the fails, even though I thought then() was supposed to be fired regardless of success or failure of the underlying promise(s).
I can switch to .always(), which seems to work better (in that it detects the failures and still triggers the callback) but it seems to fire before some of the .fail() callbacks that are registered directly on the ajax calls, which doesn't make sense to me since I thought the callbacks for an ajax call were called in the order they were registered.
I'm sure I'm just missing something about the behavior of the ajax() when() then() combo.
Fiddle showing successful calls using .then(): https://jsfiddle.net/kwrLyw6q/5/
Fiddle using .then() with failed ajax calls (not working, would love to know why. Seems like this is the "right" way to do it, but I can't figure out where I'm going wrong): https://jsfiddle.net/kwrLyw6q/2/
Fiddle using .always() (working, but notice the out-of-order callback order. At least, out of order compared to the order I want them!): https://jsfiddle.net/kwrLyw6q/7/
It looks like deferred.then() takes three arguments:
success function (first argument).
fail function (second argument).
progress function (third)
updated fiddle
Learnyounode is a commandline based learn-by-doing-and-getting-your-results-tested tutorial for javascript's node
In the seventh tutorial, the idea is to make something of a http client using node.js's http's get function.
The get function has two arguments
the url
a callback function for the asynchronous job
So I scourgd the surface of the internet looking for a way to continously accept data till the operation ended. After a while seeing that every answer was pretty much along the lines of
function callback(res){
res.on("data",function (data) { console.log(data.toString());})
}
http.get(url,callback)
I thought maybe failing the inbuilt tests would give me a clue to see how to make multiple calls but weirdly enough it passed the multiple calls test.So I thought the test called the file and hence the function, multiple times .. but after some tries..I realised that wasn't the case.
So my question : what exactly goes on behind a async call ? how is it possible for the mechanism to call it more than once? What other surprises should I expect ? to me this is taking black box thinking to a whole new level and I place it on par with thinking about list monads atm.
I think the key point is to understand that res is an EventEmitter (IncomingMessage to be more accurate), so what does the function named callback (only once on the response event of the httpClientRequest object you create when calling http.get()) is to attach an event listener to the data event of res. Without going into details, to optimise data flow, when you receive some data bytes from the network a buffer is filled and when is full the event 'data' is triggered so you can process the incoming chunk. Hence the callback you have set to the data event is executed on every chunk of data coming from the network
Right off the bat I want to apologize that I am not posting code with this. I'm in a car working on a project and I have no internet. I am on the awesome stack exchange app.
Anyway, I am currently working with two separate API calls that I know work separately, but I need to use data from the first call to pass to the second one in order to use the second one dynamically. The reason being, the first AJAX request is a call to Google's geocoding API to get the latitude and longitude of an address. The second requires latitude and longitude as URL parameters.
I looked into using jQuery $.when and .then, but I can't figure out how to pass the data from one AJAX request to the other. I have also tried to build to separate functions and use one inside of the other.
I guess my question is would this be the most efficient way to do this? If it is how do I pass the data.
Side note, responses in jQuery are good for now. I am eventually going to convert this all to Node, but I just want to get the method down first.
if i got you correct, u can call the second ajax request in the success callback of the first one like below example
$.get('ur resource URL',function(data){
$.get('new resource URL',{param1: data.param1, param2: data.prama2}, function(data2){
console.log(data2);
});
});
Here's an example using $.post():
$.post("url_with_address", function(data){
// process geocode API response
$.post("url_with_lat_long", function(response){
});
});
You can use a tried and tested async utility library such as async. This will future proof your code, as it will work in the browser as well as in Node.
In specify, take a look at the waterfall method which allows you to chain together a number of async calls, this will help you manage the code if you need to add more dependent async calls in the future.
The structure of the waterfall function is as follows.
async.waterfall([
function(callback){
$.post('http://google.com/api/...', data, callback);
},
function(results, callback){
$.post('http://google.com/api/...', results, callback);
}
], function (err, result) {
// all done
});
If you want to use jQuery, then the $.when utility won't be that helpful, as it only resolves when every promise has resolved and you want to intercept the data before then.
The simplest way, of course, is to make the second AJAX request within the callback for the first one. However, that is a surefire way to get you on the path to callback hell.
I am calling a third party webservice using getJSON callback. The function does not have a success handler attached to the function and since it is third party, I cannot edit the code also. By the time I receive the response, some of the javascript function in the page already executes.
Is there any way I can delay the execution of the Javascript function till I receive the response data from web service except setTimeout method.
Description
You can use jQuery's .ajaxStart() and .ajaxComplete() events to get noticed if your ajax call is running. You can create a bool variable, something like isAjaxRunning and put this around the other javascript. So if isAjaxRunning is true, dont execute other javascript.
More Information
jQuery.ajaxStart()
jQuery.ajaxComplete()
if you have access to the code you can make it synchonize by adding the attribute
async : false
- then it won't be a asynchronous call like the normal ajax .
If you can post the sample code - that will give a clear picture.
I have a few questions on jQuery AJAX.
It is confusing to understand why there are multiple methods like load(), get(), post()..is the diff only like $.ajax is general way of writing and others being specific based on type..?
I do not cleatly understand the diff between complete, success..Are they similar or is there any diff as to when each should be used ?
In terms of script execution from within an HTML response, does jQuery AJAX handle it automatically OR do we need to specify something like eval() ? Also how diff is this behavior compared to a normal AJAX only handling?
Regarding the beforeSend , is it similar to ajaxSetup and generally speaking, what are the common attributes which are used out of the many which are availbale?
Edited
Also is the code written as callback for load()..e.g. load(url,function(){});
same as what is mentioned under success or ajaxSuccess..I mean will the callback function code not exectuted at the same time as the success or ajaxSuccess ?
Thnak you.
1) you need to understand HTTP. get and post make "GET" and "POST" requests, respectively, which is useful if you are building a RESTful service. EDIT: I actually don't see get and post methods on the ajax object; you pass a 'type' parameter to specify the HTTP method you want to use.
2) success fires on success, i.e. if the response returns a 200. complete always fires after everything else is done.
3) Ideally, your server would return json. If you configure the Ajax call to expect json, then it will parse it for you.
4) The documentation is very clear, beforeSend is fired before the actual underlying ajax request is invoked. The documentation says things like "Use this to set custom headers, etc."
They are just "shorthand"
everything can be done and function
the exact same with $.ajax(), the
difference is only syntax
complete is fired after every request is complete, while success only fires if there were no errors (a successfully one
whatever you want to do with the HTTP response you do by making a function(data){dostuff(data);} in the success callback area
beforeSend is called right before the ajax request is fired
Documentation