How Does AJAX work - javascript

I have this call :
// some code;
myAjaxCall(
function abcd() {};
);
// more code
Can the more code and abcd executing in the same thread or different thread. I know it is asynchronous.

Assuming myAjaxCall is an ajax wrapper, and the first argument is the complete callback, the answer is "more code" will run before abcd function. But I'd need to see myAjaxCall function to know what is really going on.
Remember, the complete callback happens when ajax retruns. "more code" executes in the normal execution path.

The AJAX request is asynchronous, but the Javascript code is synchronous and single threaded.
The code following the AJAX call will complete before the abcd function can run. The event that occurs when the response arrives can't be handled until the code exits and returns control to the browser.

Related

Can anyone explain me the execution process of functions in jquery

I have a small doubt on Execution cycle of function in jquery. I'm trying to do some stuff with js, And in my script I have one custom function that calls on click of a button. What happens is, when I call the function it will make some ajax call and assigns the result to a variable. According to my knowledge after the execution of the function next statement should execute. But here what happens is after function call before completing the function execution next statements are executing.
Structure of my script is :
var variable=false;
function myfunction(e){
.....
.....
$.ajax({});
.....
console.log('inside : '+variable);
}
$('#button').click(function(){
....
....
myfunction(n);
console.log('called : '+variable);
....
$.ajax({});
....
....
});
Console output:
Ajax call from the function;
called : false
Ajax call from called function;
inside : true
Can anyone explain this stuff....
it will heppen indeed like this just beacause your custom function is an Ajax Call not a normal code.
Ajax stands for Asynchronous Javascript and XML
So, the request processing occur smultanelously that is what for ajax is used.
that is the reason, why even before compelting your function execution , the next statements are being executed. ( asynchronously)
Hope this helps..
Note: What ever the code you put in the Call back function of the ajax , they will be executed only after ajax call is completed
this is the power of js callbacks!
the js callbacks will do things after, and callbacks will run when get response! But js will not wait for the callbacks excution to continue, the following functions will run! Async is the beauty of js.
so in your js file, you make a ajax call for something. while ajax's running, the console will not wait until ajax complete!
if you want to excute the ajax function sync, you may make a config in the params {async: false}, then the console will wait until the ajax func complete then excute!
The call to .ajax:
Assigns an event handler to run a function when a response to an HTTP request is received
Sends the HTTP request
The next line of code runs immediately for the same reason that a line of code immediately after $('foo').click(...); runs before the function you pass to click.

waiting a function to complete

I have 2 functions. The second one is faster than the first one,how could the function wait to complete first one's work?
function1(); // slow
function2(); // fast
JavaScript is imperative and single-threaded, it just works like this. function2() won't start until function1() finishes.
If by slow you mean calling asynchronously some external service via AJAX, then we're talking. function1() must provide some sort of callback so that when asynchronous request finishes, function2() is called:
function1(function2);
The implementation is trivial, e.g. using jQuery:
function function1(callback) {
$.ajax({url: 'some-url'}).done(callback);
}
If functions are to be called asynchronously, aside from the obvious callback approach, their sequencing could be based on the events framework. You could add an event listener with function1 as a handler, and trigger that event within function2.
You must be using some AJAX request. So, after ajax complete call callback function like:
function1 = new function(callback) {
$.ajax({...}).done(callback());
}
function1(function2);
If your calling one function after the other then it will finish the first either it may be slow or fast.

Possible Javascript scope issue

I'm sort of a noob with this so please forgive me :)
I can't get this one part of the function to update the variable. Could anyone possibly take a look a see what I'm doing wrong?
http://pastie.org/private/zfnv8v2astglabluo89ta
From line 142 thru 172 I'm not getting any results in the end. I've tested inside that function to make sure it is actually returning data, but the "body" variable is passing back up after line 172. So if I look at my generated HTML on the page, it simply looks the function skips from 140 to 174.
Thanks for any feedback!!
Your $.get is asynchronous. That means it will finish sometime AFTER the rest of the code, thus you won't see it's effect on the body variable inside that function. Instead, it's success callback function will be called long after this function has already finished.
To chain multiple asynchronous ajax calls like you have here, you can't just use normal sequential programming because asynchronous ajax calls aren't sequential. The network request is sent, then your javascript continues executing and SOMETIME LATER when the response arrives, the success handler is called and is executed.
To run sequential ajax calls like you have, you have to nest the work inside the success handler so that the ONLY code that uses the response is actually in the success handler. In pseudo-code, it looks like this:
$.get(..., function(data) {
// operate on the results only in here
// a second ajax function that uses the data from the first
// or adds onto the data from the first
$.get(..., function(data) {
// now finally, you have all the data
// so you can continue on with your logic here
});
// DO NOT PUT ANYTHING HERE that uses the responses from the ajax calls
// because that data will not yet be available here
});
You cannot do what you're doing which is like this:
var myVariable;
$.get(..., function(data) {
// add something to myVariable
});
$.get(..., function(data) {
// add something to myVariable
});
$.get(..., function(data) {
// add something to myVariable
});
// do something with myVariable
None of those ajax calls will have completed before the end of your function. You have to follow a design pattern like in my first example.
For more advanced tools, one can always use jQuery deferreds which are just a different way of defining code to run after an ajax call is done. It looks a little more like sequential programming even though it's really just scheduling code to run the same way my first code example does.
Function 8 will be invoke after line 174-180. You must put code from 174-180 line to the end of function

Is that asynchronous of any javascript calling?

I am quiet new to javascript, can not understand that why all javascript calls are asynchronous,
for example, we have calling with order like
call_function1;
call_function2:
if function2 is depend on the results of function1, that can not be ensured, because the execution is asynchronous. Is that true ? And why ?
If true, how to ensure they are synchronous.
If this is duplicated question, I am sorry, because it is quiet new for me.
Thanks fo your answer first.
JavaScript calls are synchonous. If second function depends on results of first function, you might use callbacks model.
function foo(callback) {
var results = // get some results;
callback(results);
}
function boo(results) {
// do something with results here..
}
foo(boo);
No Javascript has functions that guarantee order and behave much like other languages. For example:
function f1() {
alert(1);
}
function f2() {
alert(2);
}
f1();
f2();
You will always get 1 and then 2. What's more is AFAIK javascript runs on one thread so you don't have to worry about race conditions either.
The asynchronous part of javascript comes from waiting on events. For example if you make 2 ajax requests (the a in ajax standing for asynchronous is a hint), you cannot guarantee which will come back first and thus if you have different callbacks for the two requests, you can't guarantee which will be called first.
Calling two functions in a row is definitely not asynchronous.
In fact.. javascript is 100% synchronous. Unless you use 'web workers' all javascript will always run in a single thread, in a single process. There is never, ever a situation where 2 scripts are running at the same time.
Even if you handle an event, coming from an XMLHTTPRequest for instance, the event will only be triggered after all other javascript code has stopped executing.
As mentioned in the comments to your question, JavaScript function calls are usually not asynchronous. The following will be executed in order:
function sayHello() {
console.log("Hi");
}
function sayBye() {
console.log("Bye");
}
sayHello();
sayBye();
The above code will first print "Hi", then "Bye", as the calls to sayHello and sayBye are in that order.
However, if a function does perform some action asynchronously, and you have another function that relies on the result of that, you can supply the second function as a callback to the asynchronous request. For example:
xmlHttpRequestObj.onreadystatechange = function() {
if(xmlHttpRequestObj.readyState == 4 && xmlHttpRequestObj.status == 200) {
//Asynchronous call returned successfully. Do something that relies on that here.
}
}
I don't know how you say that "Javascript is generally said to be asynchronous". It is generally the opposite: Javascript is almost always not asynchronous.
So generally (no ajax, no callback, no event handling), the following functions calls will execute sequentially.
function1();
function2();
If you are assigning both these functions to a single event, both will be called concurrently, but will not be executed in parallel. Same if both are called at the same time (using setTimeout), or as an Ajax callback. See Is JavaScript guaranteed to be single-threaded? for a very good explanation.
You could have heard that Ajax is asynchronous. That is true when you consider the request to servers without interfering with the user, "in the background". But this does not mean that Javascript is asynch. In fact even with Ajax calls, the javascript part is single threaded.

Is there any possibility of two asynchronous Javascript function instances executing two blocks of code at the same time?

I understand that Javascript doesn't have multiple threads, but I'd like to know if the following code has any chance of breaking. My understanding is that unless an asynchronous function is called, such as setTimeout or an AJAX call, that once a block of code starts executing there's no way for it to pause until it completes or does call an asynchronous function.
Basically, users select multiple checkboxes and then hits a button that executes AJAX processing of their selections. My goal is to have a "Saving..." icon that stays only until all the AJAX processes are complete, and after all are finished display a success message.
Barring any AJAX errors, so long as the callback function in the jQuery.post executes in its entirety without interruption, I don't see how the if(numProcessed == toProcess) would ever execute more than once or less than once. But if two AJAX callbacks get into the callback function, both increment the numProcessed counter before either get to the following if, then it seems that the code inside would be executed twice.
var numProcessed = 0;
var checkedBoxes = jQuery("input[type=checkbox]:checked");
var toProcess = checkedBoxes.size();
checkedBoxes.each(function() {
jQuery.post('somepage.php',{...},function(results) {
numProcessed++;
if(numProcessed == toProcess) {
jQuery("#saving-message").remove();
jQuery("#feedback-panel").text('Successfully processed all selections.');
}
}
}
There is only one thread in JavaScript so every function that want to be execute is put in stack and have to wait until all others are execute. In your case "each" is the first function in the stack, so every callback function have to wait and will be execute in the order they put on the stack.
After all "numProcessed == toProcess" could only one time be true.
The rx.net team has introduced rx for javascript. Reactive extension are for asynchronous programming. they have also written for rxjs for jquery too. My be that suite your need http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx

Categories

Resources