Question on jQuery AJAX - javascript

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

Related

jQuery .when().then() not working as expected

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

AJAX method calls

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?

Why can a .get() call succeed and a .load() call fail on the same content? [duplicate]

When should the load( url, data, callback ) method be used versus jQuery.get( url, data, callback, type ) when making AJAX calls with jQuery?
First of all those two functions are completely different. The 'load' function works with selectors and loads the result of AJAX call inside the selected group and the callback is to handle the "oncomplete" event of the call; while the $.get function is more general and the callback handles the success response of AJAX call where you are free to define any behavior you want. And you can find all this information just by looking at the documentation and specification of the jQuery framework.
Here you can find a good documentation.
#Artem's answer seems to be missing the fact that the load is a more generic function than get.
According to the jQuery API docs, load uses get or post depending on the data. Quoting it here:
Request Method
The POST method is used if data is provided as an object; otherwise, GET is assumed.
So for the purpose of getting partial HTML content from the server & inserting it into the DOM, load is a better method than the get method, as the developer does not need to worry about handling huge data & various intermediate steps that the load function does before fetching & before inserting the content.
For instance, if you need to load partial content of a page, you could use the following expression:
$('#result').load('ajax/test.html #container');
This retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.
One thing to keep in mind is that, when you just need a GET request avoid providing an object to the data parameter & instead use the $.param method to get a serialized form of the request parameters.
load injects the data directly into the DOM. If you don't need this behavior, use get.
would only have to look at the jQuery code, as it is available for review.
anyway all calls must reach the same method but respond in different ways depending on the need

$.ajax, $.post or $.get won't function, cannot use the response [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
return AJAX callback return
I have made a JQuery code using AJAX, but despite all my efforts (trying $.post, $.get and $.ajax) I am not able to get any response nor using it in my code.
Example code:
var r = $.post("ajaxpage.php", function(data) {return data});
console.log(r); // nothing
One of the most common misconceptions of beginner programmers about Javascript and AJAX is to treat the AJAX request as a "normal" function, doing variable assignments or expecting to use immediately the AJAX response in their code.
That's not how it works though; let's try to understand how a correct implementation works.
AJAX stands for Asynchronous JavaScript and XML.
We will ignore for a while the XML part (which is more about how the request is carried on, via XMLHttpObject), the Javascript bit is quite obvious (it's the scripting language we use, with or without JQuery), let's focus on asynchronous.
Think about AJAX this way: it is roughly like sending a work email to a colleague, while you're at work, and giving some info; and requesting an action to be taken and/or other info in return; no matter if your friend answers immediately or not, you still have to continue your job because the answer could be delayed (your friend may be particularly busy today).
When your friends answers with relevant info, only then you will address the matter and take appropriate actions. If an action is requested, your colleague will carry it on only when he receives your email.
AJAX works in a similar way: from client-side, you make a request to a server-side page, and expect an action (like writing a row in a database) or a response (some data fetched server-side from the page you are calling.
The important bit is that your JavaScript code continues its execution regardless of the completion of the round-trip, as there can be a significant delay when your client (remember that JS runs client-side) makes an AJAX call to the server (slow server, slow connection, and so on).
So you can't expect to do things like:
var r = $.post("ajaxpage.php", function(data) {return data});
because $.post doesn't actually "return" a value like a "regular" function, the variable r cannot be valued by $.post
Instead, you should organize your code based on the done event, which is fired after the AJAX call has completed: it guarantees (if there have been no failures, like server-side errors, not found pages, etc.) that we actually have a response to use in your code on success.
With that event we can call a function that receives the response as a parameter and actually uses it.
$.post("ajaxpage.php").done(useMyResponse);
// rest of the code
function useMyResponse(response)
{
// do fancy things with the response like:
console.log(response); // works!
// or maybe
$("#someElement").html(response);
}
A shorthand for this would be:
$.post("ajaxpage.php",function (response) {
// use response
console.log(response);
});
Edit: i'm not a native English speaker, forgive my mistakes.

stop javascript execution till jquery JSON response

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.

Categories