I have a for loop in java script :
for(i=1;i<=10;i++){
$.ajax({
type: "GET",
url: "insert_names.php",
success: function (data) {
// some codes
}
});
}
this script send all of ajax request Simultaneously !
But It makes problem for me ...
how can i can prevent continue for loop when ajax is working ?
If you need the requests to be executed in serial instead of parallel, you can do that with a little re-structuring. Don't make the AJAX requests synchronous, just use the response of each request to invoke the next one.
Consider a structure like this:
function sendRequest() {
$.ajax({
type: "GET",
url: "insert_names.php",
success: function (data) {
// some codes
}
});
}
Now the request is wrapped in a function that you can invoke. So invoke it in response to the previous request:
function sendRequest() {
$.ajax({
type: "GET",
url: "insert_names.php",
success: function (data) {
// some codes
sendRequest();
}
});
}
It's starting to look like a standard recursive pattern, so all you need now is a terminating condition. Similar to the original loop, just use an incrementing value:
var i = 1;
function sendRequest() {
$.ajax({
type: "GET",
url: "insert_names.php",
success: function (data) {
// some codes
i++;
if (i <= 10) {
sendRequest();
}
}
});
}
Then just invoke it once to start it:
sendRequest();
Now the request should be invoked 10 times as expected (unless my math is off by one, but that should be easy to correct), each request happening in response to the previous request.
With asynchronous programming, don't try to make it synchronous. Instead, perform actions in response to the callbacks.
Related
I have two js files i.e. myJs1.js and myJs2.js .
From myJs1.js a method of myJs2.js is called.
I want to return r1 and r2 into results(in myJs1.js)
I have tried this:
I declared r1 and r2 variables before the ajax call and
after the ajax call I added:
return [r1,r2];
But it return r1 and r2 as undefined.
When I researched the issue I came across that adding async: false could work but it has so many issues (like browser freezing). Even so I tried it and still was not able to get the values of r1 and r2.
Note: I am uing AJAX for the first time so bear that in mind.
EDIT: There is an ajax call in Js1 in which on success event the method is called. I want to access the result to call another method in the js1
EDIT:LOOK HERE FOR THE CODE
myJS1:
function method()
{
$.ajax({
type: "GET",
dataType: "json",
url: "http://127.0.0.1:8000/***/***",
success: function(response){
result=methodOfmyJs2(response);
load1(r1); //r1 from result
load2(r2); //r2 from result
}
})
}
myJs2 :
function methodOfmyJs2(data)
{
$.ajax({
type: "GET",
data:SomeData,
dataType: "json",
url: "http://127.0.0.1:8000/***/***",
success: function(response){
r1=anotherMethodFromThisJS1(response);
r2=anotherMethodFromThisJS2(response);
result=[r1,r2]
}
})
}
I need to access the value of r1 and r2 to call load1 and load2 method of myJs1.
Ajax calls are asynchronous by default, meaning ajax call function jQuery.ajax() wont wait for the HTTP response to come back before returning.
To get the data after the HTTP response has arrived we have to provide a callback, that's success function. If you want to get this data inside another function just call that function inside success callback.
Following is the code:
//JS1.
function processResponse(r1, r2) {
// do processing here with r1 and r2
}
//JS2.
function methodOfmyJs2()
{
$.ajax({
type: "GET",
data:somedata,
dataType: "json",
url: "http://127.0.0.1:8000/****/****",
success: function(response){
r1=anotherMethodFromThisJS1(response);
r2=anotherMethodFromThisJS2(response);
//calling the success callback
processResponse(r1, r1);
}
});
}
There's another option if you really want to do it, you can make your Ajax call synchronous like below.
$.ajax({
type: "GET",
url: remote_url,
async: false,//now call is synchronous
success : function (data) {
}
});
Now jQuery.ajax() will wait till HTTP response has arrived, then you can return [r1, r2] from methodOfmyJs2().
However you should avoid making synchronous calls as it will make the JS thread wait freezing the UI.
You could use a callback instead.
[EDIT]
myJS1:
function method () {
$.ajax({
type: "GET",
dataType: "json",
url: "http://127.0.0.1:8000/***/***",
success: function (response) {
methodOfmyJS2(function (r1, r2) {
load1(r1);
load2(r2);
});
}
});
}
myJS2:
methodOfmyJs2 (callback) {
$.ajax({
type: "GET",
data: somedata,
dataType: "json",
url: "http://127.0.0.1:8000/****/****",
success: function (response) {
var r1 = anotherMethodFromThisJS1(response);
var r2 = anotherMethodFromThisJS2(response);
callback(r1, r2);
});
}
$.ajax returns promise, which can be chained with then
function getAjaxOutput() {
request1().then(function(data){
// get data from request 1 and pass to request 2
return request2(data);
})
.then(function(data){
// get data from request2
$('#output').text(JSON.stringify(data));
})
return false;
}
try it
https://jsfiddle.net/je7wf4ww/
and if u want to return plain result from getAjaxOutput - u simply can't (without making request sync of course) - u need to return promise which is a wrapper around ajax call and chain it again with then
I usually like to organize my code so that one function fires a bunch of other
functions, like this:
/**
* GET MESSAGES:
*/
$(function() {
$.ajax({
url: '/messages',
method: 'GET',
dataType: 'json',
success: function(messages) {
if (messages.length > 0) {
keyedMessages = keyFork(messages);
reversedMessages = reverse(keyedMessages);
crushedMessages = crush(reversedMessages);
getFriendships(messages, crushedMessages);
}
mail.template.airmail();
}
});
});
However, if I need to do a second Ajax request inside one of the nested
functions I can't return the data because of the scope of the Ajax request
and it makes my code inconsistent and hard to follow, sort of broken up all over the place. For example, if one of the functions
invoked above fires a second Ajax request for friendships anything I write
after that will be broken from the communication chain due to the request and it seems impossible to return anything:
/**
* GET FRIENDSHIPS:
*/
function getFriendships(messages, crushedMessages) {
$.ajax({
url: 'friendships',
method: 'get',
dataType: 'json',
success: function(friendships) {
addKey(crushedMessages, friendships);
filteredCrushedMessages = filterUnconfirmedSender(crushedMessages);
filteredCrushedMessages.forEach(function(filteredCrushedMessage) {
mail.sidebar.builder.messengers(filteredCrushedMessage);
});
mail.snailMail.onload();
}
});
}
If I try to return the data it doesn't work. Consequently I'll have to
continue invoking functions inside the nested request, every time I need to make another nested ajax request it breaks the chain. This makes my
code very hard to read. Are there any solutions to this problem or is
code that uses Ajax requests just hard to read?
You could store the data on a DOM element, then use jQuery Custom Events to get it done.
There's even support for passing arguments to your event handler:
https://learn.jquery.com/events/introduction-to-custom-events/#naming-custom-events
If I try to return the data it doesn't work.
Not appear jQuery promise returned from either function at Question ?
Try utilizing return statement , $.when.apply(this, arrayOfPromises) to return array of jQuery promise object from getFriendships
function getFriendships(messages, crushedMessages) {
return $.ajax({
url: 'friendships',
method: 'get',
dataType: 'json',
success: function(friendships) {
addKey(crushedMessages, friendships);
filteredCrushedMessages = filterUnconfirmedSender(crushedMessages);
mail.snailMail.onload();
return $.when.apply($
, filteredCrushedMessages.map(function(filteredCrushedMessage) {
return mail.sidebar.builder.messengers(filteredCrushedMessage);
})
);
}
});
}
// e.g.,
getFriendships(messages, crushedMessages)
.then(function success() {
console.log(arguments)
}, function err(jqxhr, textStatus, errorThrown) {
console.log(errorThrown)
})
I'm running a long polling ajax that returns status of request. If failed, I need the ajax to stop. The ajax is written like this:
function someFunction(url){
$.ajax({
url: url,
success: function(data){
if(data.status == 'FAILED'){
//Need this ajax to stop
}
}
});
}
$('some-button').on('click',function(
var url = 'server-url';
someFunction(url);
));
I have to use the someFunction() function as this long polling method is being used by multiple other parts of the code. What should I be doing to stop this function?
try something like this
function someFunction(url){
$.ajax({
url: url,
success: function(data){
if(data.status != 'FAILED'){
//Need this ajax to stop
}
}
});
}
your ajax request is already completed in success. but if status is failed and you want to stop further execution of code than you can use not !
$.ajax returns a wrapped xhr object. Simply use:
var req = $.ajax...
..
req.abort()
var ajaxReq = null;
ajaxReq = $.ajax({
url: url,
success: function(data){
if(data.status == 'FAILED'){
//Need this ajax to stop
}
}
error: function (x, y, z) {
ajaxReq.abort();
}
});
And you can use ajaxReq.abort() to stop ajax call.
I have a strange issue in JQuery AJAX..
My Steps sequence are as follows:
1) I have a JS Function which I am calling on Button Click Event:
function Click()
{
//I am performing some Validations then making an AJAX Request:
$.ajax({
type: "POST",
url: url,
context: window,
data: datatoPost,
contentLength: contentLength,
async: true,
success: function (response) {
callbackFn(response);
},
error: function (msg) {
this.error = msg;
}
});
// The callback function is called on Successfull AJAX Request
// i.e. callbackFn (See below)
// I am then checking the window.IsValid which I have set in below function;
if (window.IsValid == true) {
// Then Perform another AJAX Request
}
else {
// do nothing
}
}
function callbackFn(response)
{
if(response == 'Valid')
{
window.IsValid = true;
}
else
{
window.IsValid = false;
}
}
2) Now, The Problem is while server is processing the First AJAX Request then the code written after that i.e.
if (window.IsValid == true) {
// Then Perform another AJAX Request
}
else {
// do nothing
}
}
is executed
3) I get window.IsValid = false as first AJAX Request's callback function i.e. callbackFn(response) is not called yet and Even after a Valid response of first AJAX request my second ajax request is not getting executed as window.IsValid variable is not still got set in callback function as callback is not called yet due to server is processing the request.
Please help me I am stuck..
you should then use
async: false,
in you ajax function call. Which is not recomended. The better thing will be to use
if (window.IsValid == true) {
// Then Perform another AJAX Request
}
else {
// do nothing
}
}
within your callback function.
Because your post is asynchronous, the script continues to execute whilst the ajax request is being processed.
Instead, you need to move your tests for window.IsValid into the success function:
function Click()
{
//I am performing some Validations then making an AJAX Request:
$.ajax({
type: "POST",
url: url,
context: window,
data: datatoPost,
contentLength: contentLength,
async: true,
success: function (response) {
callbackFn(response);
if (window.IsValid == true) {
// Then Perform another AJAX Request
// best done as another function.
}
else {
// do nothing
}
},
error: function (msg) {
this.error = msg;
}
});
}
I have this function that makes an ajax call. I'm describing the problem in the last chunk of code comments.
function doop(){
var that = this;
var theold = "theold";
var thenew = "thenew";
$.ajax({
url: 'doop.php',
type: 'POST',
data: 'before=' + theold + '&after=' + thenew,
success: function(resp) {
if(resp == 1) {
$(that).siblings('.theold').html(thenew);
}
}
});
// I have some code here (out of the ajax) that **further** changes
// the .theold's html beyond what it was changed inside ajax success
// but the change depends on whether the resp (inside the success
// function) returned 1 or not, so this code out here depends on the ajax
// so it looks like I have to turn this ajax call into a sync ajax
return false;
}
Based on the problem as described in the code comments, what changes are best for this situation?
You need to set async: false for synchronous requests like this:
function doop(){
var that = this;
var theold = $(this).siblings('.theold').html();
var thenew = $(this).siblings('.thenew').val();
$.ajax({
async: false,
url: 'doop.php',
type: 'POST',
data: 'before=' + theold + '&after=' + thenew,
success: function(resp) {
if(resp == 1) {
$(that).siblings('.theold').html(thenew);
}
}
});
// some other code
return false;
}
see here for details
Either set the Ajax call to synchronous as stefita pointed out, or just move your code into the success callback. Why can't you do this? Even if it's another Ajax call it still can be done - you can nest them. With the information given by you so far (I can't see the problematic code, nor I have enough domain knowledge about your project) I don't see a problem, really.
I prefer to use callback to do the job because it achieves exactly the same result without actually making it synchronous. I use success:callback and then pass in the callback as a parameter.
function getData(callback) {
$.ajax({
url: 'register/getData',
data: "",
dataType: 'json',
success: callback
});
}
I then call this function like this:
getData(function(data){
console.log(data); //do something
});