How to function with ajax calls asynchronously and display loader until done? - javascript

how can I call ajax request or any function simple in new thread?
I know about async: false but my code has this structure:
1.user click on some item, and this fire click event
2.in event I call this function
var myData= {};
$.ajax({
type: "GET",
url: "...",
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
dataType: "json",
success: function (s0) {
myData.s0= s0;
$.ajax({
type: "GET",
url: "sss",
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
dataType: "json",
success: function (s1) {
myData.s1 = s1;
$.ajax({
type: "GET",
url: "...",
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
dataType: "json",
success: function (s2) {
myData.s2= s2;
}
});
}
});
}
});
// I need call this function when all ajax are done.
myFunc(myData);
My current code works but causes the web freezes until data are not downloaded beaouse I have asyn: false but I do not know how to solve it asynchronously
Optimal solution for me is call this freezing and display loading gif until done.

Well there is no fix for UI freeze during a synchronous AJAX so you might want to try web workers but it has its own caveat .I would suggest you to use jquery promise so that you don't need to define separate success ,error callbacks .A promise is guaranteed to yield so at the end of chain either you will have values in myData or not but it won't hangup forever
//show loader
$.ajax({
type: "GET",
url: "...",
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
dataType: "json",
}).then(function( s0, textStatus, jqXHR ){
myData.s0= s0;
return $.ajax( {
type: "GET",
url: "sss",
async: false,
cache: false,
dataType: "json"} );
}).then(function( s1, textStatus, jqXHR ) {
myData.s1 = s1;
$.ajax( {
type: "GET",
url: "...",
async: false,
cache: false,
dataType: "json"});
}).then(function( s2, textStatus, jqXHR ) {
myData.s2= s2;
//hide loader
})
Read more

Change async:false to async:true on all ajax calls, show loading gif at the start of your function where you initialize myData and call the function you want to call when all data is loaded in the success function on the last ajax call (just after myData.s2 = s2)

Related

Call a async:false ajax inside a async:true ajax

I have two ajax call. First one is asynchronous, second is synchronous. If I put a synchronous call inside a success function, then what will happened. Is it block any event from other places when synchronous execute.
$.ajax({
type: "POST",
url: "http://www..../k.php",
data: dataString,
crossDomain: true,
cache: false,
success: function (response) {
$.ajax({
type: "POST",
url: "http://www..../s.php",
data: dataString,
crossDomain: true,
cache: false,
async: false,
success: function (response) {}
});
});

How to access the data from an ajax call outside the function itself

This code gets a json object from another server.
How do I access the response outside of the function?
(function($) {
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'callback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
var data = json;
}
})
})(jQuery);
You can do something like this!
_outerMethod: function(data) {
//...do what you need to do
}, (function($) {
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'callback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
_outerMethod(json);
}
})
})(jQuery);

AJAX post is empty on the server side (PHP)

I am making an AJAX request to a PHP controller, by using jQuery ajax, but when trying to get the posted data with PHP the $_POST is empty. Below is the actual function:
function GetSeriesForManufacturer(manuf) {
selectedmanufacturer = manuf;
//Make an AJax Call For Getting Series Of Manufacturer
var series = null;
$.ajax({
type: "POST",
url: url,
data: "{manufacturer:'" + selectedmanufacturer + "'}",
contentType: "application/json", //; charset=utf-8",
dataType: "json",
cache: false,
async: false,
success: function (response) {
//remove loading gif
$(".loading").hide();
//Append Data
AppendSeries($.parseJSON(response.text), selectedmanufacturer);
//Custom Scrollbar Call
$('.MatchingSeries ul').mCustomScrollbar();
},
error: function (XMLHttpRequest, textStatus, errorThrown) { }
});
}
Thanks in advance!
First, you don't need to stringify data. Just send object literal is ok.
data: {manufacturer: selectedmanufacturer},
Second, you don't need this line:
contentType: "application/json",
Let jQuery do the encoding for you:
$.ajax({
type: "POST",
url: url,
data: {
manufacturer: selectedmanufacturer
},
contentType: "application/json", //; charset=utf-8",
dataType: "json",
cache: false,
async: false,
success: function (response) {
...
},
error: function (XMLHttpRequest, textStatus, errorThrown) { }});

jQuery AJAX from different URLs

I am writing a Javascript program which can query data from more than one servlets each sec. If it queries from one servlet, I know how to do it in xxx.js file:
var TPS_URL = "http://localhost:8888/tps";
var jQueryFunction = function()
{
$.ajax
({
type: "GET",
async: false,
url: TPS_URL,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
.......
}
});
};
setInterval(jQueryFunction,1000);
But now I have another servlet to query. How can I add another servlet into this js file? Just simply create another "TPS_URL_2" and "jQueryFunction_2", and do the same thing above?
var TPS_URL_2 = "http://localhost:9000/tps";
var jQueryFunction_2 = function()
{
$.ajax
({
type: "GET",
async: false,
url: TPS_URL2,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
.......
}
});
};
setInterval(jQueryFunction_2,1000);
??
Also, if I get a result from the first url and also another result from the other url, and I want to SUM them together, how can I do it?
set the URL as a parameter to the function and call this function as many times as you need
var jQueryFunction = function(xurl)
{
$.ajax
({
type: "GET",
async: false,
url: xurl,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
.......
}
});
};
Call it like this
setInterval( function(){ jQueryFunction('some url') },1000);

animation not work in IE when jQuery ajax calling inside js function

I'm trying to show a div with gif animation inside when a button click via javascript call. But the problem is, it's working fine in firefox only. In IE and Chrome, the animation won't show up. I've tried debugging with alert("stop"); before and after the animation and it's indeed working, but after I removed the alert, it won't work anymore. Any suggestion please?
Here's the snippet for the TestPage.aspx:
<div id="animationDiv" style="display: none;">
<img src="loading.gif" />
</div>
...
<div>
<asp:Button ID="testButton" runat="server" Text="Test AJAX" OnClientClick="return testButtonClick();" />
</div>
...
<script type="text/javascript">
<!--
var docWidth, docHeight;
function testButtonClick() {
var o_animationDiv = $("#animationDiv");
o_animationDiv.width(docWidth);
o_animationDiv.height(docHeight);
o_animationDiv.show();
$.ajax({
type: "Post",
url: "TestPage.aspx/TestAjax",
async: false,
cache: false,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: testAjaxSuccess,
error: testAjaxError
});
function testAjaxSuccess(data, status, xhr) {
// do something here
};
function testAjaxError(xhr, status, error) {
// do something here
};
o_animationDiv.hide();
return false;
};
$(document).ready(function () {
docWidth = $(document).width();
docHeight = $(document).height();
});
//-->
</script>
Here's the snippet for TestPage.aspx.cs:
// using PageMethod for ajax
[System.Web.Services.WebMethod(EnableSession = true)]
public static string TestAjax()
{
System.Threading.Thread.Sleep(5000); // 5 seconds
// or do something else here
// ie. if validation error, throw an exception
return string.Empty;
}
UPDATE 1: added some javascript function
Why don't you call the .hide() on the post success:
$.ajax({
type : "Post",
url : "TestPage.aspx/TestAjax",
cache : false,
data : "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// hide element when POST return as arrived,
// meaning the "5 seconds" period has ended!
o_animationDiv.hide();
}
});
You can read about callback function at the jQuery documentation!
jQuery ajax is asynchronous, so that won't wait for ajax result to hide again.
o_animationDiv.hide();
o_animationDiv.show();
This lines work in serial and you can't see if it's working properly. So you should wait for ajax result to hide it.Try this,
$.ajax({
type: "Post",
url: "TestPage.aspx/TestAjax",
async: false,
cache: false,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function() {
o_animationDiv.hide();
});
UPDATE:
Sorry I missed the point that you create a synchronous ajax request.
But there is a problem already. Most browsers lock itself when running a synchronous XHR. This also effects previous proccess sometimes.
Here is a similar question
Maybe if you use beforeSend, you can avoid this problem.
beforeSend
A pre-request callback function that can be used to modify the jqXHR
(in jQuery 1.4.x, XMLHTTPRequest) object before it is sent
Try this one,
$.ajax({
type: "Post",
url: "TestPage.aspx/TestAjax",
async: false,
cache: false,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend : function() {
o_animationDiv.show();
}
}).done(function() {
o_animationDiv.hide();
});
UPDATE-2:
If that doesn't work, try this one,
...
o_animationDiv.width(docWidth);
o_animationDiv.height(docHeight);
o_animationDiv.show();
setTimeout(function() {
$.ajax({
type: "Post",
url: "TestPage.aspx/TestAjax",
async: false,
cache: false,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: testAjaxSuccess,
error: testAjaxError
}).done(function() {
o_animationDiv.hide();
});
}, 600);

Categories