This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I apologize for asking such a simple question, but googling "javascript or jquery first" just keeps giving me people asking which they should learn first.
Currently I have a couple lines of javascript, followed by a bit of jquery, followed by a bit more javascript. This is the part where it breaks down...
$.get("alliances.php", function(data, status){
console.log(data);
searchIndex = data.search(allianceName);
rawAllianceLink = data.slice(searchIndex-25,searchIndex);
});
console.log(rawAllianceLink);
After I carry this code out, the JQuery goes last and my console.log prints undefined. (Note, the console.log isn't the actual statement, I have more lines that need to go after this, it is just an example that it is performed out of order.) Was wondering if someone could clarify or explain how I can alter when each of these steps is carried out.
Simple ans:
Its simply because your $.get(... is an AJAX call. You have to log your data in callback handler.
$.get("alliances.php", function(data, status){
console.log(data);
searchIndex = data.search(allianceName);
rawAllianceLink = data.slice(searchIndex-25,searchIndex);
})
.done(function() {
console.log(rawAllianceLink);
});
Let's get a few things clear here. $.get() is a wrapper for $.ajax() in jQuery. The javascript being applied happens within the jQuery library.
Next, the $.get call is asynchronous meaning that the console.log(rawAllianceLink); likely will fire prior to the $.get() request completing, which takes some time to fetch the file and read the data.
The function(data, status) is applied to the data returned from alliances.php only after the request has fully completed. Within that callback function, it would seem as if you've properly applied the javascript methods that you intend.
If you need to fire further code after the callback execution occurs, then you should place it into a function and execute the function at the end, passing the rawAllianceLink as an argument, like so:
$.get("alliances.php", function(data, status){
console.log(data);
searchIndex = data.search(allianceName);
rawAllianceLink = data.slice(searchIndex-25,searchIndex);
process_request(rawAllianceLink);
});
function process_request(RAL){
console.log(RAL);
}
Now things will be fired in the proper order. You could also look into jQuery's $.defered, but that may be another beast, entirely.
What is happening in your code, is that, the jQuery "get" function is called, which sends a request to the server to retrieve some information at "alliances.php", but it just sends the request, it doesn't wait for a response, then it carries on with the console.log. At some later point, the browser gets the response back from the server, and when the browser gets a chance, it executes the code in the callback function. This kind of programming isn't unique to jQuery, it happens with event handler, timeouts, intervals, etc. in javascript, whether you use jQuery or not.
Related
This question already has answers here:
Easy to understand definition of "asynchronous event"? [closed]
(11 answers)
Closed 7 years ago.
I have the following Javascript and it's returning results out of the order I would expect them.
function getCurrentItems(id){
alert("2");
$.ajax({
url: "somePHPurlthatspitsoutajsonencodedArray.php",
type: "POST",
dataType: "json'",
data: {id:id},
success: function(data){
alert("3");
}
});
alert("4");
}
$(document).on('click', '.eventClass', function(e){
alert("1");
var id = "someID";
var results = getCurrentItems(id);
alert("5");
});
I would think I'd get alerts in the order of 1, 2, 3, 4, 5.
Instead I get them in the order of 1, 2, 4, 5, 3.
I just can't figure out why that success alert (5) fires last?
AJAX is short for asynchronous JavaScript and XML. Asynchronous is the keyword here. I'll use an allegory to explain async.
Lets say you're washing dishes manually. You can't do anything else while doing that, so it is synchronous.
Lets say you put your dishes in a dishwasher. You can do other things, you've delegated the task to the dishwasher, so this is asynchronous. Asynchronous is generally better, because you can do multiple things at one time. Javascript only asyncs when requesting info from the server, as Javascript is single threaded (it only runs on 1 CPU core and can only do one thing at a time on it's own).
A callback is a function that is called when the async task completes. The dishwasher finishes, so now you have to empty it as soon as you complete what you're doing when it finshed.
So in your code, you start the dishwasher, say you're going to alert("3") when the dishwasher finishes running, and then you go alert 4 and 5. Then when the dishwasher finishes/your server returns data, you alert 3 like you said you would.
That make sense?
The reason that you give a success callback function in an ajax request is that the request might take some time to return, but your code can continue running. In this case the ajax request is sent, and the success function is remembered for later, then your code continues (alerting 4 and 5). When the browser receives the response to the ajax request it calls the success function (alerting 3).
The way that Javascript works, only one thread is run per browser tab, so event handlers are not called until any previously running code is completed. Therefore, even if your getCurrentItems function were to take several seconds to complete, by which time the server response had returned, the success function would still not be called until after your function had completed.
Edit: Because an ajax call can take some time, it is not generally desirable to be able to call a function like getCurrentItems which includes an ajax request, and wait for the response. If you do this, then you are likely to leave your browser window unresponsive, and you will have to deal with potential errors from the ajax call. Instead, you should put any code that you wish to run which relies on the ajax result in the success function, or in another function which you call from there. As languages go, Javascript is very good for doing this kind of thing. You could even take a callback function as an argument to getCurrentItems, and run it from the success function.
As others have mentioned, you're getting the results in the order you see because the ajax request doesn't return with it's data and call your success callback until the response is received, but code continues to execute immediately after the $.ajax call.
To get the workflow you're probably expecting, you could use promises, or simply pass in a callback:
function getCurrentItems(id, onSuccess){
alert("2");
$.ajax({
url: "somePHPurlthatspitsoutajsonencodedArray.php",
type: "POST",
dataType: "json'",
data: {id:id},
success: function(data){
alert("3");
onSuccess(data);
}
});
alert("4");
}
$(document).on('click', '.eventClass', function(e){
alert("1");
var id = "someID";
var results = getCurrentItems(id, function(data){
console.log('data',data);
alert("5");
});
});
I'm experiencing some extremely weird behavior with Ajax. Or maybe it's normal. I wouldn't know. I'm quite new to playing around with Ajax.
My problem is that I am making a few Ajax calls(two using $.post() and one using the standard $ajax() call), and they seem to return the data fine, but the code inside the success function only works in a very peculiar way.
I have noticed that some things work if placed first in line to be executed; but why is that? It really doesn't make any sense to me. In this case I would like the span with the id link_span to be updated dynamically, as my Ajax calls link and unlink devices from each other.
(the correct_classes function counts how many links have been linked and adds it to the link_counter variable that I've made global with the window object).
But as the span only wants to update if the corresponding code is placed on top, it's kinda useless.
Another problem is also that .ajaxComplete() and other such event handlers don't always get called. For example, I attempted to show and hide a loader gif by using .ajaxComplete() to close it when ajax stop. But this only works with one of my calls which is the standard $.ajax call.
I'm really confused.
Any help would be great, and please ask me to clarify if there's something I haven't made clear enough.
Here is a small snippet of what I'm talking about:
$.post( "<?php echo base_url(); ?>connections/ajax_link", datax).done(function( resp,status ) {
$("#loader_overlay").css('display','none');
display_confirmbox();
resp=JSON.parse(resp);
var str = resp['parent_selector'];
var arr = mystr.toString().split("||");
correct_classes(arr[1], resp);
$( '#link_span' ).text( '( ' + window.link_counter + ' ) links found' ); //this doesnt work unless its on top
});
Update
It seems that the problem is caused by correct_classes();
the array from the ajax call gets passed to the function in which jQuery complains about something, and causes the rest of the ajax code to halt. Yet everything inside correct_classes() gets executed. The error in question is this:
TypeError: invalid 'in' operand e
specifically what is causing the problem seems to be this(i commented everything else out and this is:
$.each( val, function( i, value ) {
var mystr = value;
}
I really cant figure out why it complains about this code when it seems to work.
i'm not sure to have understand your problem.... but if you use 3 async ajax call ($.post or $.ajax is indifferent $.post is a contract syntax to call $.ajax({type:"post"})) you need to wait the full loading of all calls for use their response.
so.. if one of your call evalue window.link_counter you need to wait his response before call the code you have post.
For wait the complete load you may nast the call inside the success function of the prev call.
for you knowlage there is an attribute of $.post() dataType if you set it to "json" you not need to parse the response because Jquery do it for you, this code is useless:
resp=JSON.parse(resp);
and, the method .done() is calling whether the call is successful if it fails, $.post() has a success function callback. Use it, it's better, and use .fail() to catch call error.
See documentation about $.post(): here
however... the element who have this id #link_span is generated by one of ajax call?
This question already has answers here:
Sequencing ajax requests
(10 answers)
Closed 9 years ago.
I am working a script, I need to loop an array of AJAX requests:
$('#fetchPosts').click(function(){
for(var i=0; i < link_array.length; i++) {
settings = {
// some object not relevant
}
var status = main_ajaxCall(settings, i); // ajax call
}
});
function main_ajaxCall(settings, i) {
$.ajax({
type: "POST",
url: "../model/insert.php",
data:{obj_settings: settings},
dataType: "json",
cache: false,
success: function (data) {
// some handeling here
return 0;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
return 1;
},
};
Why does the AJAX requests fire instantly? It does not seem to wait for a response from model/insert.php, is there any way to force it to wait for a response before firing the next AJAX request?
EDIT 1:
It seems I wasnt clear, sorry, I dont want it to wait, I want to queue up the calls.
I cant make the call in one request, this is impossible in my current situation.
Set async to false if you want to wait for a response (default: true)
$.ajax({
async: false,
...
http://api.jquery.com/jQuery.ajax/
If you do not want blocking, you can set a success handler function using .ajaxComplete(), and you have to keep track of active AJAX connections if you want to wait for all to complete - How to know when all ajax calls are complete
The best solution would be to minimize the number of AJAX requests to one. If you have to make a loop of AJAX requests, the logic could be simplified somewhere (put that in the server perhaps?)
EDIT 1: (In response to OP edit)
If you want to queue the AJAX requests, this question has been answered before here:
Sequencing ajax requests
Queue ajax requests using jQuery.queue()
You could also use these libraries (all you needed to do was Google):
https://code.google.com/p/jquery-ajaxq/
http://codecanyon.net/item/ajax-queue-jquery/full_screen_preview/4903957
http://schneimi.wordpress.com/2008/03/10/multiple-ajax-requests-problems-and-ajaxqueue-as-solution/
It fires instantly and doesn't wait around because that's what AJAX does best (The first A stands for asynchronous).
The request to a server could take a long time to respond, and in most cases, don't want user's browser's freezing up or stopping them from doing anything else. If you do, you could probably just use a normal request.
This is the reason you give it functions for success error, so it can call them when the server responds.
If you want nothing to be able to happen in the browser while you're calling insert.php, you could drop an overlay (eg. dark div) over everything with a loading image and remove it on success.
Maybe replace the $('#fetchPosts') element with "loading..." text and then reverse it when done. Hiding visibility of the fetchPosts element and adding a different "loading.." element is a nice way.
Your AJAX call will wait for a response from the server, but wil do so asynchronously. That is, your script will continue to execute rather than block the browser while the server responds. When the server responds (or when the request times out - usually several seconds) your success: or error: functions will then execute.
The effect of your code here is to create several concurrent requests based on the link_array length.
You could specify async:false in your AJAX call, but this would freeze the browser while all the AJAX calls are made.
You should rewrite your code to execute all the handling as part of your success: function. I'd recommend you rewrite your code to assemble all your request into one, and make one AJAX call rather than several, and have the server return all the responses as one block. I can't suggest exactly how you do that - it's implementation dependent.
EDITED:
In response to your clarification, if you want them to be called in order, you'll need the success function to call the next one. You'll then have a chain of success calls the next, whose success calls the next, whose success calls the next.. etc until the last one which does the final processing. One way would be to pass the call number to the success function.
Here is the code :-
var quiz;
function startQuiz() {
$.ajax({
url: 'get_quiz/',
cache: 'false',
dataType: 'json',
async: 'false',
success: function(data) {
quiz = data;
alert(quiz[0].q); // I'm able to access quiz here
},
}
);
}
startQuiz();
alert(quiz[0].q); // Not able to access it here.
I'm not able to access quiz here, am I mission something?, Whats wrong with this?
Ajax is assynchronous which can be an unfamiliar concept. Your code will run like this:
1. var quiz;
2. define function startQuiz;
3. call startQuiz;
4. do ajax call (and continue! don't block)
5. alert(quiz[0].q); // Not able to access it here.
-- ajax call comes back
6. quiz = data;
7. alert(quiz[0].q); // I'm able to access quiz here
Ajax is asynchronous, it doesn't block. This means that when you make the ajax call the callback doesn't actually get called until the ajax call returns, it doesn't block and wait. Instead the code will continue on.
Then later when the ajax call returns the data, your callback function will be executed.
Javascript does this by means of an event loop.
See it like this: steps 1-5 are part of the first event. 6-7 are part of the second event.
A cool thing about JavaScript is that in your callback you still have access to anything above it (like the variable quiz) because of scoping. This is called a closure. Your callback function closes around the scope and brings it with him to the next event.
AJAX calls are asynchronous, you should wait for the result to come back from the server. Either do all the work in a callback function or have a look on a promises library (I like Q promises library), which makes waiting for AJAX results very easy.
This is due to the asynchronous nature of JavaScript, once you call startQuiz() it executes and jumps back out and executes your quiz alert().
You have to access your quiz data explicitly after the callback is called to make sure you have access to it.
You also have to worry about scoping, as you may not be actually modifying the same quiz variable.
var quiz,
fetched = false;
$.ajax({
//blah
success : function(data){
fetched = true;
quiz = data;
}
});
setInterval(function(){
if(fetched){
//quiz is populated
}else{
//quiz hasn't be populated yet
}
},50);
Although not a clever example, I'm just trying to get the point across that startQuiz() doesn't wait for the ajax call. The A in AJAX mean asynchronous.
You should give jQuery deferreds a try which ist the preferred way of writing ajax related code since jQuery 1.5: http://javascriptplayground.com/blog/2012/04/jquery-deferreds-tutorial
Once you get the hang of it maybe will be easier to write and understand your code.
I want to retrieve the height and width of an image on a server by using an ajax post call to a php file which returns a double pipe delimited string 'width||height'
My javascript is correctly alerting that requested string from the php file so the info is now in my script but i cannot seem to access it outside the $.post function.
This works:
var getImagesize = function(sFilename)
{
$.post("getImagesize.php", { filename: sFilename, time: "2pm" },
function(data){
alert(data.split('||'));
});
}
But retrieving is a different matter:
// this line calls the function in a loop through images:
var aOrgdimensions = getImagesize($(this, x).attr('src')) ;
alert(aOrgdimension);
// the called function now looks like this:
var getImagesize = function(sFilename)
{
var aImagedims = new Array();
$.post("getImagesize.php", { filename: sFilename },
function(data){
aImagedims = data.split('||');
});
return "here it is" + aImagedims ;
}
Anyone able to tell me what i'm doing wrong?
You are misunderstanding the way that an AJAX call works. The first "A" in AJAX stands for asynchronous, which means that a request is made independent of the code thread you are running. That is the reason that callbacks are so big when it comes to AJAX, as you don't know when something is done until it is done. Your code, in the meantime, happily continues on.
In your code, you are trying to assign a variable, aOrgdimensions a value that you will not know until the request is done. There are two solutions to this:
Modify your logic to reconcile the concept of callbacks and perform your actions once the request is done with.
Less preferably, make your request synchronous. This means the code and page will "hang" at the point of the request and only proceed once it is over. This is done by adding async: false to the jQuery options.
Thanx for the Asynchronous explaination. I did not realize that, but at least now i know why my vars aren't available.
Edit: Figured it out. Used the callback function as suggested, and all is well. :D