I have function which is call recursively by ajax complete callback, and I need to set parameters fot this function. But how do I transfer parameters in callback?
function poll(url, data, pollDelay, type){
$.ajax({ url: url, type: 'POST', data: data, success: function(data){
if(data != '' && type == 1) { //do answers
doOutput(data);
}
}, dataType: 'html', complete: pollTimeout = setTimeout('poll()', pollDelay), timeout: 30000 });
}
function doPoll() {
clearTimeout(pollTimeout);
poll('url/f.php', obj = { id: someId, data: somedata }, 10000, 1);
}
Thanks a lot
I'm assuming you're referring to your setTimeout call? Never pass a string to setTimeout.
pollTimeout = setTimeout(function() {poll(url,data,pollDelay,type);},pollDelay);
Note that your whole "complete" thing should be in such a function:
$.ajax({...
complete: function() {
pollTimeout = setTimeout(...);
}
...});
Related
I'm sending ajax call and getting an answer that I need from the first ajax then I want to pass my result to my nested ajax, my var (result) is null in the nested ajax/settimeout fun, can I pass it ? Am I missing something ?
$.ajax({
url: '#Url.Action("getCustomerGuidId", "Document")',
type: 'POST',
cache: false,
data: { "classNum": currentclassNum},
contentType:'json' ,
dataType:'text',
success: function (result) {
alert(result);**-> is fine - not null**.
// a or result is null when I hit the getCurrentDoc- function althought I get the data I need from getCustomerGuidId function
var a = result;-> tried to pass it to a new var..IDK.. I
thought it will help... it didn't.
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
contentType:'text',
data: a,-> here it's null
success: function (data) {
}
});
}, 2000);
},
error: function (result) {
alert("fail " + result);
}
});
You can try something like this will help to pass value to nested ajax call
function test(){
var myText = 'Hello all !!';
$.get({
//used the jsonplaceholder url for testing
'url':'https://jsonplaceholder.typicode.com/posts/1',
'method':'GET',
success: function (data) {
//updating value of myText
myText = 'welcome';
$.post({
'url':'https://jsonplaceholder.typicode.com/posts',
'method':'POST',
//data.title is the return value from get request to the post request
'data':{'title':data.title},
'success':function (data) {
alert(data.title +'\n' + myText);//your code here ...
}
});
}
});
}
An old question and you've likely moved on, but there's still no accepted answer.
Your setTimeout takes an anonymous function, so you are losing your binding; if you have to use a Timeout for some reason, you need to add .bind(this) to your setTimeout call (see below)
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
contentType:'text',
data: a,
success: function (data) {
}
});
}.bind(this), 2000);
At a guess you're using a Timeout because you want to ensure that your promise (i.e. the first ajax call) is resolving prior to making the nested call.
If that's your intention, you can actually scrap setTimeout completely as you have the nested call in the first ajax success call, which only runs once the promise has been resolved (providing there isn't an error; if so, jQuery would call error rather than success)
Removing setTimeout means you won't lose your binding, and a should still be result (hopefully a is an object, otherwise your second call is also going to experience issues...)
Lastly, after overcoming the binding issue you wouldn't need var a = result; you should be able to pass result directly to your nested ajax call.
Good luck!
In the nested ajax you send a as a param name, not as a param value.
So you can try the following (change param to actual param name which your server expects):
$.ajax({
url: '#Url.Action("getCustomerGuidId", "Document")',
type: 'POST',
cache: false,
data: { "classNum": currentclassNum},
dataType:'text',
success: function (result) {
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
data: {param: result},
success: function (data) {
}
});
}, 2000);
},
error: function (result) {
alert("fail " + result);
}
});
i have an issue and i need an idea for solve :)
I have 2 call to $.ajax
First, is asynch, and during a lot of time (1 minutes for example)
Second, is sync (in ajax async: false) and it response fast (5 sec for example)
Second call is in a loop (requests->response->print data, request->response->print data).
I need when first finish (success or error), stop second call.
I attach an example code:
var success = false;
$.ajax({
type: "POST",
url: urlRest,
data: {
data: dataSend
},
success: processOK,
error: processError
});
do {
$.ajax({
type: "POST",
url: urlData,
data: {
data: dataSend
},
async: false,
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(data, textStatus, jqXHR){
console.log("Error");
}
});
} while (!success);
I hope it's clear :)
I corrected an issue that would cause some errors, try this out.
let printData = function( input ){
let config = {
urlRest: '',
data: { data: {} },
loop: false,
callback: false
}
$.each(config,function(k,v){ config[k] = input[k] });
config.loop = false;
$.ajax({
type: 'POST',
url: config.urlRest,
data: config.data,
success: function( data ){
// Based on the response if you need to run again change config.loop to true and it will run again
// you can also alter anything your sending through
if( config.loop ) printData( config );
else if( typeof config.callback === 'function' ) callback();
},
error: function(){
// Based on the response if you need to run again change config.loop to true and it will run again
// you can also alter anything your sending through
if( config.loop ) printData( config );
else if( typeof config.callback === 'function' ) callback();
}
});
}
printData({
urlRest: '', // URL Here
data: data, // Data Object
loop: true, // Set this to true if you want it to loop
callback: function(){
console.log( 'Job Complete' );
}
})
You can run async calls in synchronous manner using SynJS:
function ajaxWrapper(ctx, url, data){
var res={done:false};
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result){
res.data=result;
},
error: function(){
res.error=true;
},
}).always(function(){
res.done = true;
SynJS.resume(ctx); // <-- tell caller that callback is finished
});
return res; // <-- return object that will hold the results
}
// function that is executed in synchronous manner
function myFunc(modules, urlRest, urlData) {
var success = false;
var res1 = modules.ajaxWrapper(_synjsContext, urlRest, urlData);
SynJS.wait(res1.done); // <-- wait for result from callback
do {
var res2 = modules.ajaxWrapper(_synjsContext, urlRest, urlData);
SynJS.wait(res2.done); // <-- wait for result from 2nd callback
} while (!success);
}
var modules = {ajaxWrapper: ajaxWrapper};
SynJS.run(myFunc,null, modules, "/", {}, function () {
console.log('done');
});
You can change the success value like this
$.ajax({
type: "POST",
url: urlRest,
data: {
data: dataSend
}
}).always(function() {success=true;});
Or you can create a self call function (after the second ajax finish, calls it again) but before the call its checks the success variable like #mplungjan did.
It is never a good idea to loop Ajax. You need to allow the call to return.
Here is an example that is NOT using async false
var firstDone = false,tId;
// call long ajax
$.ajax({
type: "POST",
url: urlRest,
data: {
data: dataSend
}
}).done(processOK);
}).fail(processError)
}).always(function() {firstDone=true; clearTimeout(tId);}); // stops the other loop
// setup function that can be looped
function callAjax() {
if (firstDone) return;
$.ajax({
type: "POST",
url: urlData,
data: {
data: dataSend
}
}).done(function(data, textStatus, jqXHR) {
console.log(data);
}).fail(function(data, textStatus, jqXHR) {
console.log("Error");
}).always(function() {
tId=setTimeout(callAjax,1000); // give the server time to recover
});
}
callAjax();
I am trying to execute a WCF service call, from function one(). Only once this is complete I want function two() to be executed. The issue I have is that function two() is invoked before function one() completes execution and the WCF service returns the result. How can I solve this please? I am using callback function, so I can't figure out why, given that the response does not exceed 3 seconds.
<script type="text/javascript">
var jsonGetFileResult = "";
function one(callback) {
setTimeout(function() {
//var jsonGetFileResult = "";
console.log('01: into one');
$.ajax({
type: 'GET',
url: ‘http: //wcf.google.com’, //this is the wcf call
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: {},
timeout: 10000,
success: function(data) {
jsonGetFileResult = stringifyNewsletter(data);
console.log('03: ' + jsonGetFileResult);
},
error: function(data) {
alert(error);
}
});
callback();
}, 3000);
}
function stringifyNewsletter(data) {
var removeHeader = JSON.stringify(data);
var file = removeHeader.split('"');
console.log('02: ' + file[3]);
return file[3];
}
function two(linkToNewsletter) {
window.open(linkToNewsletter, '_blank', 'location=yes');
return false;
}
/* now we make use of the callback */
one(function() {
alert(jsonGetFileResult);
// "one" triggers "two" as soon as it is done, note how "two" is a parameter
two(jsonGetFileResult);
});
</script>
You're invoking the callback outside of the ajax "success" function. The $.ajax() call is asynchronous — the call will return to your code essentially immediately, after launching the HTTP request and without waiting for it to finish.
If you move the line
callback();
to inside the "success" handler, then that will run after the HTTP request completes.
You need to put callback inside success function like that:
function one(callback) {
setTimeout(function() {
//var jsonGetFileResult = "";
console.log('01: into one');
$.ajax({
type: 'GET',
url: ‘http: //wcf.google.com’, //this is the wcf call
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: {},
timeout: 10000,
success: function(data) {
jsonGetFileResult = stringifyNewsletter(data);
console.log('03: ' + jsonGetFileResult);
callback();
},
error: function(data) {
alert(error);
}
});
}, 3000);
}
So I have had to modify some old existing code and add another ajax event to onclick
so that it has onclick="function1(); function2();"
This was working fine on our testing environment as it is a slow VM but on our live environment it causes some issues as function1() has to finished updating some records before function2() gets called.
Is there a good way to solve this without modifying the js for function2() as this the existing code which is called by other events.
Thanks
Call function2 upon returning from function1:
function function1() {
$.ajax({
type: "POST",
url: "urlGoesHere",
data: " ",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//call function2
},
error:
});
}
Or wrap them in a function that calls both 1 and 2.
You need to use always callback of ajax method, check out always callback of $.ajax() method http://api.jquery.com/jquery.ajax/.
The callback given to opiton is executed when the ajax request finishes. Here is a suggestion :
function function1() {
var jqxhr = $.ajax({
type: "POST",
url: "/some/page",
data: " ",
dataType: "dataType",
}).always(function (jqXHR, textStatus) {
if (textStatus == 'success') {
function2();
} else {
errorCallback(jqXHR);
}
});
}
I'm assuming you use Prototype JS and AJAX because of your tags. You should use a callback function:
function function1(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function function2(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function both() {
function1(function() {
function2();
});
}
Then use onclick="both();" on your html element.
Example: http://jsfiddle.net/EzU4p/
Ajax has async property which can be set false. This way, you can wait for that function to complete it's call and set some value. It actually defeats the purpose of AJAX but it may save your day.
I recently had similar issues and somehow calling function2 after completing function1 worked perfectly. My initial efforts to call function2 on function1 success didn't work.
$.ajax({
type: "POST",
url: "default.aspx/function1",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, // to make function Sync
success: function (msg) {
var $data = msg.d;
if ($data == 1)
{
isSuccess = 'yes'
}
},
error: function () {
alert('Error in function1');
}
});
// END OF AJAX
if (isSuccess == 'yes') {
// Call function 2
}
I found this question which is almost exactly the same: Return value from nested function in Javascript
The problem is that the function is passed to jQuery's $.ajax function. Here's what i have:
function doSomething() {
// Do some stuff here
console.log(getCartInfo());
}
function getCartInfo() {
var url = blog_location + '?reqCartData=1';
$.ajax({
url: url,
type: 'get',
success: function(data) {
return data; <------------- This
}
});
}
I need to return data to the doSomething function, if that makes sense. I tried to return the entire $.ajax function but that returned the whole object. Any ideas?
Send a callback function:
function getCartInfo(onSuccess) {
var url = blog_location + '?reqCartData=1';
$.ajax({
url: url,
type: 'get',
success: function(data) {
onSuccess(data);
}
});
}
getCartInfo(function(data) {
console.log(data);
});
try this
function doSomething(date) {
........your data
}
function getCartInfo() {
var url = blog_location + '?reqCartData=1';
$.ajax({
url: url,
type: 'get',
success: function(data) {
doSomething(data);
}
});
}