Sequential AJAX call inside loop using jQuery.Deferred() - javascript

I'm having a loop, inside the loop there is an AJAX call. For each loop AJAX returns a value. I want sequential loop one after another only when AJAX request is completed. I've done this using async:false but this method hangs my other code.
I want to do with $.Deferred()
This is my code:
function CheckAvailability(Display) {
var Status = "";
$.ajax({
type: "POST",
url: "myurl",
dataType: "json",
data: { "Display": Display },
async: false,
success: function (result) {
Status = result[0].Availability;
}
});
return Status;
}
$(DisplayData).each(function (index, Display) {
var Availability = CheckAvailability(Display) === 'Yes' ? '' : '<span style="margin-left:10px"><i class="fa fa-exclamation text-danger"></i></span>';
var Name = Display.Name + Availability;
console.debug(Name);
});
I want output like:
Display1 Yes
Display2 No
Display3 No
Display4 Yes

Related

simplify if statement in several AJAX

I need to use the same if..else to deal with every AJAX data in my code.
$.ajax({
url: "api/aall.json",
dataType:'json',
type: 'GET',
data: "data",
cache: false,
ifModified: true,
success: function getData(data){
console.log(data);
for(var i=0;i<7;i++){
// if...else
}
});
There are several AJAX get differnt:
$.ajax({...});
$.ajax({...});
$.ajax({...});
$.ajax({...});
if...else code:
if(MainClass_Code=="PD" || MainClass_Code=="CD"){
newsKindRepalce = "aipl";//news
}else if(MainClass_Code=="PF" || MainClass_Code=="JF"){
newsKindRepalce = "aopl";//international
}else if(MainClass_Code=="CU"){
newsKindRepalce = "acul";//culture
}else{
newsKindRepalce = "acn";//artist
}
It's would be very heavy when I use if...else in my all AJAX to deal with data, how can I do to simplify this?
change your if else to this:
const code = { PD: "aipl", CD: "aipl", PF: "aopl", JF: "aopl", CU: "acul" };
newsKindRepalce = code.hasOwnProperty(MainClass_Code)
? code[MainClass_Code]
: "acn";

how can i call multiple ajax request after one request complete

created two functions i want to call the get_name_from_id when my first ajax function get successful but it is not working when i add alert in get_name_from_id function after jsonstring like alert("xyz") it shows but ajax part not exectue
function get_name_from_id(){
var team_name = ("sahil","krishna");
var jsonString = JSON.stringify(team_name);
$.ajax({
dataType:"json",
type:"POST",
url:"fetchidwithname.php",
data: {team_name : jsonString},
cache: false,
success:function(a)
{
alert(a);
}
});
}
$("#matchbet").click(function(){
var matchlist = $("#match_list option:selected").val();
var jsonString = JSON.stringify(matchlist);
$.ajax({
dataType:"json",
type:"POST",
url:"selectedmatch.php",
data: {matchlist : jsonString},
cache: false,
success:function(currentmatch)
{
var current_bettable = team1 + "_vs_"+ team2 + matchdate;
var bet_team= '<select id="betting_team"><option value='+ team1 +'>'+ currentmatch.team1 + '</option><option value='+ team2 +'>'+ currentmatch.team2 + '</option></select>';
$("#teamholder").html(bet_team);
$("#current_match_table").val(current_bettable);
get_name_from_id();
}
});
});
You can use complete method of ajax
Call your function get_name_from_id() in complete method instead of success

How to check json response taken longer than 5 seconds?

Below is the sample code of my function. in the for loop one by one product id is pass in the ajax function and get product price from the php file as response and write it and html.
for(var i=0; i < data.products.length; i++){
var doc = data.products[i];
$.ajax({ // ajax call starts
url: 'product.php',
data: { product_id: doc.id },
dataType: 'json',
success: function(data)
{
document.getElementById('price_price'+data.product_id+'').innerHTML = data.products_price;
}
});
}
I have found that sometimes it takes a more time for price to display. i want to check which record is taking time to load. how can check to detect when it takes longer than 5 seconds for the price to load?
Something like this....
var ajaxTime= new Date().getTime();
$.ajax({
type: "POST",
url: "some.php",
}).done(function () {
var totalTime = new Date().getTime()-ajaxTime;
// Here I want to get the how long it took to load some.php and use it further
});
Also, by the way, if you want to prevent sending (i+1) request, before (i) is completed, you'd maybe want to use syncronous ajax request instead of async.
Try to log timestamp beforesend and success or error
$.ajax({ // ajax call starts
url: 'product.php',
data: { product_id: doc.id },
dataType: 'json',
beforeSend: function() {
console.log(new Date().getSeconds());
}
success: function(data)
{
console.log(new Date().getSeconds());
document.getElementById('price_price'+data.product_id+'').innerHTML = data.products_price;
}
});
Use setTimeout, like this:
var timeoutTimer = setTimeout(function() {
// time out!!!.
}, 5000);
$.ajax({ // ajax call starts
url : 'product.php',
data : {
product_id : doc.id
},
dataType : 'json',
success : function(data) {
document.getElementById('price_price' + data.product_id + '').innerHTML = data.products_price;
},
complete : function() {
//it's back
clearTimeout(timeoutTimer);
}
});

Javascript/jquery iterate async problems

I would like to iterate through a certain amount of pages, and populate them with content using ajax calls. The problem is, when I put the ajax calls inside the iteration function it has problems with the synchronous nature of javascript. The iteration has already continued before the ajax call is completed. So I made a workaround where I made the ajax call in a setTimeout, which works fine. But I don't really like this method, and was wondering if there is an alternative (better) solution. (I know that jQuery provides a async: true option, however that did not work)
function populatePages(i) {
pageId = PageIds[i];
containerId = pageIdContainer[i];
$j.ajax({
type: 'GET',
dataType: 'html',
url: url,
data: { pageid: pageId, containerid: containerId },
success: function(data) {
//populate the DIV
}
});
}
i = 0;
x = 50;
$j.each(pagesIds, function(){
setTimeout("populatePages("+i+")", x);
x = x + 50;
i++;
});
Try this (not tested)
function populatePages(i) {
console.log('populatePages', i)
pageId = PageIds[i];
return $.ajax({
type: 'GET',
dataType: 'html',
url: '/echo/html',
data: { pageid: pageId},
success: function(data) {
}
});
}
function messy(index){
console.log('messy', index)
if(index >= PageIds.length){
return;
}
populatePages(index).always(function(){
console.log('complete', index)
setTimeout(function(){
messy(index + 1)
});//to prevent possible stackoverflow
})
}
PoC: Fiddle

Pausing for loop after every execution

i have a page, wherein i am using a ajax for inserting records... now in javascript i am using a for each loop to loop the html table and insert the rows in database. but happens is as foreach loop executes fast, it sometime, does not insert some records.. so i want to make the loop sleep for sometime once it has executed first and thereafter...
is there any way to pause the for loop.. i used setTImeout.. but it just delay it first time and not consecutive times...
here's my code.
function AddTopStories() {
$("#tBodySecond tr").each(function (index) {
$.ajax({
type: "POST",
url: "AjaxMethods.aspx/AddTopStoriesPosition",
data: "{'articleID':'" + $("td:nth-child(1)", this).text() + "','siteID':1}",
dataType: "json",
contentType: "application/json",
success: function (data) {
window.setTimeout(showSuccessToast(data.d), 3000);
},
error: function (data) {
window.setTimeout(showSuccessToast("Error:" + data.reponseText), 3000);
}
});
});
}
Please help me to resolve this issue... its utmost important.
*************************************UPDATED CODE AS PER THE CHANGES BY jfriend00*********
function AddTopStories() {
var stories = $("#tBodySecond tr");
var storyIndex = 0;
function addNext() {
if (storyIndex > stories.length) return; // done, no more to get
var item = stories.get(storyIndex++);
alert($("td:nth-child(1)", item).text());
addNext();
}
}
This just does not do anything... does not alert...
I'd recommend you break it into a function that does one story and then you initiate the next story from the success handler of the first like this:
function AddTopStories() {
var stories = $("#tBodySecond tr");
var storyIndex = 0;
function addNext() {
if (storyIndex >= stories.length) return; // done, no more to get
var item = stories.get(storyIndex++);
$.ajax({
type: "POST",
url: "AjaxMethods.aspx/AddTopStoriesPosition",
data: "{'articleID':'" + $("td:nth-child(1)", item).text() + "','siteID':1}",
dataType: "json",
contentType: "application/json",
success: function (data) {
addNext(); // upon success, do the next story
showSuccessToast(data.d);
},
error: function (data) {
showSuccessToast("Error:" + data.reponseText);
}
});
}
addNext();
}
Ugly, but you can fake a javascript 'sleep' using one of the methods on this website:
http://www.devcheater.com/

Categories

Resources