Multiple Ajax posts in a serial manner - javascript

I want to implement multiple ajax post requests. Suppose there are 3 posts. Then the 2nd post is dependent on the result from the first and the third post is dependedent on the result received from the 2nd post.
How do I place the 2nd ajax post method. Should it be done in the success handler
jQuery.ajax({
type : "post",
dataType : "json",
url : ajaxurl,
data : form_data,
async: false,
success: function(response) {
//2nd ajax post call to be placed here?
}
}
})
//or should 2nd ajax post call be placed after
I have seen some people also using jQuery.when() but I am not sure whether I could use that.
Since here I will have to check for when condition 3 times.
Thanks in Advance.

Something like this?
From https://api.jquery.com/jQuery.when/
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
// Each argument is an array with the following structure: [ data, statusText, jqXHR ]
var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
if ( /Whip It/.test( data ) ) {
alert( "We got what we came for!" );
}
});
a1, a2 being the results returned from the various callbacks?
(This will however execute your three callbacks (async), but return the results of all three)
Otherwise if you've got a dependency from request1 to request2 you can do something like this https://api.jquery.com/jQuery.ajax/
$.ajax("page1.php").done(function(a1) {
if (a1 == "something") { // if 2nd call dependent on results from 1st
$.ajax("page2.php").done(function(a2) {
}).fail(function() {
// handle with grace
});
}
}).fail(function() {
// handle with grace
});

Related

Javascript redirect on Ajax success

I have a quiz type application. Each question has two answers with a value of 1 or 2. When the quiz is complete, if they have a score lower than 10, they get redirected to a page.
This is my code for this part.
while (n < numResults) {
increment = minScore + (interval * n);
if (totalScore <= increment) {
if(totalScore <= 10) {
$.ajax({
method: "POST",
url: "handleData.php",
dataType: "json",
data: { answers: ansArray, page: window.location.href }
})
.done(function( msg ) {
window.location.href("www.page2.html");
});
}
return;
} else {
n++;
}
}
I have a few things I am trying to solve. Firstly, before the redirect, some data (answers and url) is posted to PHP so I can process it. One thing I pass is the current window url. The reason I do this is because the
url has a format like
www.page1.com?a=1&b=2&c=3
In PHP, I parse this url and grab the values.
My first problem is that although the data is successfuly sent to PHP and handled, and returns a response of Success, the done function never seems to fire, therefore no redirect occurs (I put an alert in this function
to ensure it is not firing). In PHP, after I process the data, I do this
var_dump($response); //Outputs Success
return json_encode($response);
The second thing I am trying to work out is the redirect url (page2.html). Within this page, I have a button. This button has a standard link, and then I need to give it some params from the initial url.
So this pages button might be something like
www.externallink.com?a=1&c=2
How can I get the original URLs params into a button on the redirected url?
Thanks
USE below function insted of done:
$.ajax({
method: "POST",
url: "handleData.php",
dataType: "json",
data: { answers: ansArray, page: window.location.href }
success:function(data){
window.location.href("www.page2.html");
});
})
For your 1st part:
Try putting the error function of jQuery ajax call. Sometimes when the return type of result does not match with the expected datatype of ajax call, then result comes in the response of error.
error: function (data, status, e) {
}
For your 2nd part:
Attach click event for the button in the handler and read the current URL query string using window.location.search and then redirect using
window.location = newURL + "extra query params";
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function(data, textStatus, jqXHR) {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert( "error" );
})
.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) {
alert( "complete" );
});
If you .done() callback never invoked, try to set debuggers or alerts inside .fail() or .complete() callback functions. Check if you have an error during ajax call and at all if the call has complete statement.
Here more information: http://api.jquery.com/jquery.ajax/

Javascript autocomplete with ajax call order

I have simple autocomplete input field with Javascript like this:
$('#search').on('keyup', function () {
var query = $(this).val();
$.ajax({
type: "GET",
url: "/search",
data: { query: query }
}).done(function (results) {
showSearchResults(results);
});
});
Sometimes first call takes more time then second or third and results are overridden.
How can I make sure that results only from the latest successful call are displayed?
I mean if I got response from call #3 - I no longer care about calls #1 and #2 and don't want them to override results of call #3.
Ajax function is in default asynchronous it means that many of functions can run on same time. If You wrote 3 letters it will run 3 times, after 3 keyups. If you want to run function in sequence just add setting async: false.
$.ajax({
type: "GET",
url: "/search",
async: false,
data: { query: query }
}).done(function (results) {
showSearchResults(results);
});
But i think You should add some delay, so function will not run immediately after every keyup, just after last one.
I suggest that you bind an incremental id to each ajax request that you send. When you get a response, just check that it carries last given id.
let lastXHRid=0; // tracker of last sent ajax request
$('#search').on('keyup', function () {
let reqXHR = $.ajax({ // create a variable out of $.ajax returned value
type: "GET",
url: "/search",
data: { query: $(this).val() }
});
lastXHRid++; // increment the XHR counter
reqXHR.id = lastXHRid; // attach id to the request
reqXHR.done(function(results, status, respXHR) {
if ( respXHR.id == lastXHRid ){ // compare id of received and last sent requests
showSearchResults(results);
}
});
});
(Edit: I initially suggested tracking the unix timestamp of last sent request, but as #seth-battis suggested in the comments, a sequence number is far enough. As a bonus, I also debugged my sample snippet!)

ajax give me same data when call too frequently

I have a bar code gun, when i scan a bar code it will run the below function, but when I scan 5-6 bar code too fast it will give duplicate data
Also I need async to be true, or else it would be slow
Is there a way to do fix that so i don't have duplicate data?
function getUnReadBox() {
$("#unReadBoxList").children().remove('li') ;
$.ajax({
dataType: "json",
url: xxxx.php ,
success: saveUnRead ,
error: function ( xhr , b , c ) {
$("#reportMsg").html ( "error" ) ; },
async: true });
}
function saveUnRead ( json ) {
var i ;
var new_item ;
var msg ;
for ( i in json ) {
new_item = '<li>' + json[i].PACKAGE_ID + "</li>" ;
$("#unReadBoxList").append ( new_item ) ;
scShipping.unReadBox ++ ;
$("#unReadBox").html ( msg ) ;
}
$("#unReadBoxList").listview('refresh') ;
}
Edit
I added
$("#unReadBoxList").children().remove('li') ;
var d = new Date();
var num = d.getTime();
var mySQL = scShipping.jsonUrl+'scTripUnRead.php?T='+scShipping.tripId+"&O="+scShipping.whichOp+"?date="+num ;
$.ajax({
dataType: "json",
url: mySQL ,
success: saveUnRead ,
error: function ( xhr , b , c ) {
$("#reportMsg").html ( "error" ) ; },
async: true });
}
but I still get duplicated data
I had the same issue than you before. The solution that I got was passing in a numeric timestamp as a parameter when calling the php program, or passing in a date as parameter. Something like, for example:
xxxx.php?date=2014-03-28 20:54:52:03
It worked for me, I hope it works for you too...
This happens may because the web browser cached the data you request,by avoiding this you can try these:
use POST instead of GET in your request. assign POST to type in the parameters of $.ajax method.
disable cache. assign false to cache in the parameters of $.ajax method.
append an additional parameter and value to the url,a random number or a timestamp,like this xxxx.php?t=Math.random() or xxxx.php?t=new Date(). these make sure your request urls are different, and the response data will not be cached.
just like #user3311636 suggested, you can add an extra parameter on your Ajax calling code. So the server or your browser would not cache the response.
Try it like this (it is #user3311636 answer, i just include whole function for clarity purpose)
$.ajax({
dataType: "json",
url: "xxxx.php?date=2014-03-28 20:54:52:03" ,
success: saveUnRead ,
error: function ( xhr , b , c ) {
$("#reportMsg").html ( "error" ) ; },
async: true });

How to handle two ajax request?

Hello i have sequence like this
$(document).ready(function() {
$("#ctl00_txtsearch").autocomplete({
source: function(request, response) {
$.ajax({
// Here is the code of autocomplete which is requesting
// data and binding as autocomplete
});
});
});
var aa=bindonload();
});
Here is the another function which i want to call on page load
function bindonload() {
$.get( "minicart.aspx#mydatacontent", function( data ) {
var resourceContent = data;
var mini=$(resourceContent).find('div#pnlminicart');
$('#smallcart').html(mini);
});
return false;
}
So , my actual problem is when page is loaded
first of all
bindonload()
called and then autocomplete if textbox have some values right?
But when page is loaded and suddenly i started to write into autocomplete textbox then untill bindlonload function gets executed autocomplete will not work.
I don't have idea how to handle it i have used async:true but its not working i don't want to wait for second process
Thanks in advance....
Well..what i guess..should be..you loaddata() should not be taking too much of time to load.
If there is any way to optimize , look of that.
If you ajax request has a dependency on the other, then you can not make it parallel
If you really intend to make parallel ajax requests, you have to make use of the following:
$.when($.ajax("URL1"), $.ajax("URL2"))
.then(myFunc, myFailure);
Hope it helps..
Note : The Ajax calls should not be dependent
Updated:
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 )
{
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
// Each argument is an array with the following structure:
[ data, statusText, jqXHR ]
var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It" if ( /Whip It/.test( data ) ) { alert( "We got what we came for!" );
}});
In the above example , you can see two ajax requests executes parallel
After the two requests are done, i.e on sucess of two functions , the add operation is being performed
Similarly , you can replace $.ajax("/page1.php") with your loaddata() and then
$.ajax("page2.php") with your Auto Complete request.
Both of them will execute Parallely

Combining then sorting 2 feeds

I have the following script which works fine:
url = 'http://external_source/feed_1.xml';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
values = data.responseData.feed.entries;
if (values[0]) {
for (i = 0; i <= values.length - 1; i++) {
document.write(values[i].title);
document.write(values[i].publishedDate);
}
}
}
});
I now have a second feed, i.e. url = 'http://external_source/feed_2.xml';, and I need to combine both feeds. I understand i can repeat the above process and have feed_1 display above feed_2, but I need to combine both feeds and sort the feed entries by publishedDate.
How would I go about doing that? Both feeds are structured exactly the same, they just have different values in title and publishedDate
Since you're using jQuery you can use jQuery.when. The example at the bottom of that page shows you how to callback after multiple async methods are finished.
Since you'll have both data returned, you can just concat the arrays and sort them thereafter:
$.when( $.ajax( "/page1.json" ), $.ajax( "/page2.json" ) ).done(function( a1, a2 ) {
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
// Each argument is an array with the following structure: [ data, statusText, jqXHR ]
var data = a1[0].responseData.feed.entries.concat(a2[0].responseData.feed.entries)
});

Categories