$.ajax with setTimeout synchronous or asynchronous? total performance? - javascript

I have seen a code for some chat system which says some thing like below to get the chat messages. I have seen that AJAX is asynchronous. setTimeout here is refreshing the chatlog periodically. So on the whole is it asynchronous communication? $.ajax is synchronous or asynchronous? what is its significance here????
http://net.tutsplus.com/tutorials/javascript-ajax/how-to-create-a-simple-web-based-chat-application/
Asynchrounous communication means the server has to send the data to client if there is any new data without the client bugging the server. Isn't it? Please give me a detailed explanation of what's going on below ....... Any better solution how chatlog can be updated automatically with jquery-ajax
if we are checking every x seconds and reloading the whole window again, what is the need to use $.ajax here? just making code complex .... what is the difference between using just php-sql request to the database and setimeout .... cost of the first case: the whole chat is reloaded over and over+ajax call, cost of the second case: whole chat is loaded over and over ... so i don't understand what is the benefit of using ajax according to performance .... in fact i see the later is better...... Isn't it???
function updateMsg()
{
$.ajax({
url:"db.php",
type:"POST",
success:function(data){
}
});
setTimeout("updateMsg()",7000);
}

You can use async param. async param determines: is request synchronous or asynchronous
$.ajax({
url:"db.php",
type:"POST",
async: true, // async: false

By default is async :
async (default: true) Type: Boolean By default, all requests are sent
asynchronously (i.e. this is set to true by default). If you need
synchronous requests, set this option to false. Cross-domain requests
and dataType: "jsonp" requests do not support synchronous operation.
Note that synchronous requests may temporarily lock the browser,
disabling any actions while the request is active. As of jQuery 1.8,
the use of async: false with jqXHR ($.Deferred) is deprecated; you
must use the success/error/complete callback options instead of the
corresponding methods of the jqXHR object such as jqXHR.done() or the
deprecated jqXHR.success().
function updateMsg() {
$.ajax({
url: "db.php",
type: "POST",
async: true, //or false
success: function (data) {}
});
}

Related

jQuery Ajax request async false

I'd like to know why I get this error if I send a ajax request like:
$.ajax({
url: "testOperation.php",
async: false,
data: compareHeure,
success: function (data, statusRequest) {
})
error:
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user's experience. For more help,
check https://xhr.spec.whatwg.org/.
Is there a problem ?
Thanks,
I'd like to know why I get this error
The short answer is because of this option in the ajax:
async: false,
There could be other better solution to the problem you currently have. If you post more details about why do you need to use Synchronous ajax?
Either use this way:
$.ajax({
url:'',
type:'post',
success:function(data){
// make another ajax call here then
}
})
You can use jQuery.when():
$.when( $.ajax("/page1.php"), $.ajax("/page2.php") ).done(function(a1, a2) {
// here you can get both ajax response when both gets completed.
console.log(a1);
console.log(a2);
});
Here .done() only executed when both ajax gets completed.
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
This is just a warning generated which has nothing to do with non working of you code
You have a syntax error in code and missing a }
$.ajax({
url: "testOperation.php",
async: false,
data: compareHeure,
success: function (data, statusRequest) {
}
});
You get a warning because Synchronous XMLHttpRequest block the UI threat and it is generally not a good choice (in fact it has been deprecated).
Blocking the UI threat make any user interaction delayed and sloppy possibly causing the browser to hang for a while.
Wherever possible use AJAX with async calls and use callback or a promise to detect when the call is has status: success, progress or rejected (fail).
Examples:
https://jsfiddle.net/sb11heds/
var jqxhr = $.ajax( "https://fiddle.jshell.net/favicon.png" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
jqxhr.always(function() {
alert( "second complete" );
})
Just like everyone else said, Synchronous XMLHttpRequest thread is deprecated.
I think you are avoiding Async because you might be waiting for the call to get finish and then do something else. You could instead use a callback like .done:
$.ajax({
url: "testOperation.php",
data: compareHeure,
success: function (data, statusRequest) {
}
}).done(function(data){
// Do another Ajax or something with the data returned from the Ajax call
})
Synchronous AJAX calls are deprecated, because they may produce some issues in page content load.
It may also cause distortion in view-able design, so it is not good practice to use synchronous AJAX, and it may not available in future.
Check if your AJAX call is set to false (async: false) explictly (default is true - which is the right way to go about it), if not then the chances are that you have some extensions running on your browser that do a synchronous call back. Easy way to identify is to open the console in Chrome, enable "Log XMLHttpRequests" and you will be able to see the extension that is causing the issue to be reported. Hope this helps.

To check if ajax call is synchronous or asynchronous in Browser Dev Tools

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

Is this a scope issue in JavaScript / JQuery? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is it posible to use ajax respone outside of it?
I've created the following JavaScript routine that goes to a WCF oData service and gets some data. In the success element I get the results into the results variable and alert them - I see that there are objects returned. When I run the second alert, outside of the ajax call and before returning the results, the results variable is "undefined".
Can anyone please tell me where I'm going wrong?
function retrieveJsonpODataSet(baseUrl, query)
{
var oDataUrl = baseUrl + "?$format=json&$callback=?";
var results;
$.ajax(
{
url: oDataUrl,
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'jsonp',
async: false,
success:
function (data, textStatus, xhr)
{
results = data.d;
alert(results); // This shows the results
},
error:
function (xhr, textStatus, errorThrown)
{
alert("Query failed.\n\n" + oDataUrl + "\n\n" + errorThrown);
results = null;
}
});
alert(results); // This shows "undefined"
return results;
}
Please ignore the query parameter - I've not finished the routine yet.
EDIT
Initially I had no async:false in the ajax call. I've added that now but it doesn't fix the problem.
The ajax call is an asynchronous operation. It fires and your code does not stop at it. So results is returned which at that point is undefined. What you need to do is to pass callback to the function.
function retrieveJsonpODataSet(baseUrl, query, callback) {
/* some code */
$.ajax({
/* some settings */
success: function(res) {
/* some code */
callback(results);
}
});
}
Now you use it like this
retrieveJsonpODataSet(baseUrl, query, function(res) {
/* Hurray, I have result now in res variable! */
});
DO NOT USE async: false OPTION! It blocks ALL scripts untill the call finishes... and what if it does not finish at all?? You will be blocked forever.
EDIT
I've missed that the request is JSONP. In that case async: false won't even work (it does not work for cross-domain requests and JSONP). So you have to use callbacks anyway.
A fellow Richard!
This isn't a scope issue, but more of an execution one. Both the success and error options are event handlers, and run asynchronously (hence it being called AJAX). This essentially means that the alert(results) and return results can, and likely will, get executed before the success or error events are triggered.
Your ajax is async, so the alert executes before the ajax completes. You need to set the ajax call async property to false in order for script to halt the execution until ajax request is made & processed.
However, jQuery docs says:
async
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false is deprecated.
AJAX request are sent, without the script waiting for a response, that's what Dave Newton means by A-synchronus, put the alert inside the success callback function, and you'll see what the actual response is.
alternatively, you can specify the async property, and set it to false, to force your script to wait for the response, before continuing.

JavaScript: Global variables after Ajax requests [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
the question is fairly simple and technical:
var it_works = false;
$.post("some_file.php", '', function(data) {
it_works = true;
});
alert(it_works); # false (yes, that 'alert' has to be here and not inside $.post itself)
What I want to achieve is:
alert(it_works); # true
Is there a way to do that? If not can $.post() return a value to be applied to it_works?
What you expect is the synchronous (blocking) type request.
var it_works = false;
jQuery.ajax({
type: "POST",
url: 'some_file.php',
success: function (data) {
it_works = true;
},
async: false // <- this turns it into synchronous
});​
// Execution is BLOCKED until request finishes.
// it_works is available
alert(it_works);
Requests are asynchronous (non-blocking) by default which means that the browser won't wait for them to be completed in order to continue its work. That's why your alert got wrong result.
Now, with jQuery.ajax you can optionally set the request to be synchronous, which means that the script will only continue to run after the request is finished.
The RECOMMENDED way, however, is to refactor your code so that the data would be passed to a callback function as soon as the request is finished. This is preferred because blocking execution means blocking the UI which is unacceptable. Do it this way:
$.post("some_file.php", '', function(data) {
iDependOnMyParameter(data);
});
function iDependOnMyParameter(param) {
// You should do your work here that depends on the result of the request!
alert(param)
}
// All code here should be INDEPENDENT of the result of your AJAX request
// ...
Asynchronous programming is slightly more complicated because the consequence
of making a request is encapsulated in a function instead of following the request statement. But the realtime behavior that the user experiences can be significantly
better because they will not see a sluggish server or sluggish network cause the
browser to act as though it had crashed. Synchronous programming is disrespectful
and should not be employed in applications which are used by people.
Douglas Crockford (YUI Blog)
AJAX stands for Asynchronous JavaScript and XML. Thus, the post to the server happens out-of-sync with the rest of the function. Try some code like this instead (it just breaks the shorthand $.post out into the longer $.ajax call and adds the async option).
var it_works = false;
$.ajax({
type: 'POST',
async: false,
url: "some_file.php",
data: "",
success: function() {it_works = true;}
});
alert(it_works);
Hope this helps!
It seems that your problem is simply a concurrency issue. The post function takes a callback argument to tell you when the post has been finished. You cannot make the alert in global scope like this and expect that the post has already been finished. You have to move it to the callback function.
The reason your code fails is because post() will start an asynchronous request to the server. What that means for you is that post() returns immediately, not after the request completes, like you are expecting.
What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,
var it_works = false;
$.ajax({
url: 'some_file.php',
async: false, # makes request synchronous
success: function() {
it_works = true;
}
});
alert(it_works);

Jquery ajax onSuccess event

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.

Categories

Resources