So, I have two JavaScript functions:
function Generate() {
//Do something
$.ajax({data:{Svc: 'cpMain',
Cmd: 'Generate'
},
dataType: "text",
context: this,
success: genSuccess()
});
}
function genSuccess() {
//Do something
}
and in my c#, on Page_Init() I pick up the parameters from my AJAX callback to do something.
I want the order to be Generate(), callback, genSuccess(). But the order in which this is running is Generate(), genSuccess(), callback.
Am I missing something?
Provide the function reference of genSuccess to success, and not the return value of a call to genSuccess
success: genSuccess
Related
I'm not so much pro in javascript variable scopes and got stuck with one question.
If i have function which dose ajax call and then call my callback
function doAjaxFunc(param, callback)
{
$.ajax({
type: 'GET',
url: '/some/url/'+param,
success: function(data){
callback(data);
},
dataType:'json'
});
}
function someCallback1(ajaxResp){
// DO someting 1
}
function someCallback2(ajaxResp){
// DO someting 2
}
// exec
doAjaxFunc(1, someCallback1);
doAjaxFunc(2, someCallback2);
As ajax is async and it can be that sever will process param=1 case longer then param=2 is it possible that someCallback1 and someCallback2 will process not their responses. I mean callback argument value will be somehow mixed ?
If possible give some explanation details in answer
I mean callback argument value will be somehow mixed?
No. The callbacks will be called in completely separate invocations within scope of the originating AJAX success handler. There will be no cross-contamination of the data from either request.
Also, just as an aside, you can change this:
success: function(data){
callback(data);
},
To just this:
success: callback,
Check this example , i hope it is some helpful to understand scope in JavaScript
var isFirstCall=false;
function doAjax(param)
{
if(!isFirstCall)
{
//for example after do ajax
var millisecondsToWait = 1000;
setTimeout(function() {
console.log(param);
}, millisecondsToWait);
}
isFirstCall=true;
console.log(param);
}
doAjax('first call');
doAjax('second call');
Im trying to add an optional callback inside an AJAX successful execution, but I can't seem to get the callback to run when I want it to.
heres and example of my AJAX code
function someAjaxFunction(hosturl, callback){
$.ajax({
type: "GET",
url: hosturl,
data: {'something': 'code' },
dataType: 'json',
success: function(html){
var arr = $.map(html, function(val) { return val; });
if(arr[0] != 'false'){
console.log('1');
console.log('2');
if (callback) {
console.log('calling the callback')
callback();
}
console.log('3');
}else{
console.log('fail')
}
}
});
}
here is the callback and example of how the AJAX is being executed
function thisIsACallBack(){
console.log("i'm a callback");
}
someAjaxFunction("some url", thisIsACallBack);
If I run this code the console outputs.
1
2
3
i'm a callback
I can even remove the callback if-condition all together and I would still get the same output.
Also is here a better way to handle my Ajax return currently my response wrapped inside a json object. If the database can't find the object I have to place 'false' inside an array and convert it to a json object before echoing it back to ajax.
Couse you have to pass your callback as string to your function
someAjaxFunction("some url", thisIsACallBack); // <-- Wrong thisIsACallBack will be triggered after someAjaxFunction as some separate function call
like this
someAjaxFunction("some url", "thisIsACallBack()"); // <- Correct way
// Then call eval( callback ); inside Ajax success
....
success: function(html){
...
eval( callback );
}
your problem was that in case of this code someAjaxFunction("some url", thisIsACallBack); it was triggering someAjaxFunction then thisIsACallBack function as you written someAjaxFunction name not as string
UPDATE
if you have to pass params to your callback your option is
someAjaxFunction("some url", function(param1){
thisIsACallBack(param1)
); } );
...
success: function(html){
...
callback( yourArray );
}
JavaScript has many ways how you can pass callbacks depends on your need
Method for handling ajax
function ajaxMethod(){
return $.ajax({
url: ajaxUrl,
type: "POST",
dataType: "JSONP",
jsonpCallback: ajaxCallback
});
}
Calls to this method:
dD(ajaxMethod());
aA(ajaxMethod());
bB(ajaxMethod());
cC(ajaxMethod());
aa,bb,cc,dd method have
promise.success(function (response) {
console.log(response);
});
Now aA response is coming in bB function,,bb response in cc function and as simultaneous call is coming.
Also tried using async true nothing happens.
Any suggestions?
With jsonpCallback you are telling jQuery to use a specific function name for the callback function (instead of generating a unique one), so each time you call it, you overwrite the previous function.
Just remove jsonpCallback: ajaxCallback.
While you are at it, remove type: "POST",, it is incompatible with JSONP.
I think this is what you are after.
This code is using the returned promise to wait for the result then passing the result to your other function.
ajaxMethod().success(function(response)
{
dD(response);
});
ajaxMethod().success(function(response)
{
aA(response);
});
ajaxMethod().success(function(response)
{
cC(response);
});
ajaxMethod().success(function(response)
{
dD(response);
});
Your aA, bB, cC and dD methods can now be:
function <insertname>(response)
{
console.log(response);
}
If you want your request to come in the synchronous way, then try the following :
var callBack = $.Callbacks();
callBack.add(dD(ajaxMethod()));
callBack.add(aA(ajaxMethod()));
callBack.add(bB(ajaxMethod()));
callBack.add(cC(ajaxMethod()));
callBack.fire();
the above line of code will make sure the respective ajax call would get call.
I'm trying to get this function to work. I think the function is pretty self explanitory:
function FileExists(path){
var result = false;
$.ajax({
url: "http://mydomain.com/"+path,
type: "HEAD",
success:
function(){
result = true;
}
});
return result;
}
I need the anonymous function that is called upon success of the ajax post to set the variable "result" that was defined inside the FileExists function to true so that I can return that value from the FileExists function. I think I need a closure for this but they confuse the hell out of me.
Please help!
Thanks!
It's not a scoping issue, but rather because $.ajax is asynchronous, meaning that FileExists will return before $.ajax will complete. What you should be doing is to move all code that depends on result to inside the success callback.
Ajax calls are by default asynchronous, you can either use a callback function:
$.ajax({
url: "http://mydomain.com/"+path,
type: "HEAD",
success: function(){
callback(true);
}
});
Or make the call synchronously.
$.ajax({
async: false,
url: "http://mydomain.com/"+path,
...
I have a slow function that does an AJAX request:
function X(param1,param2){
var params={
type: "POST",
url: "./ajax/useful.php",
data: "param1="+param1+"¶m2="+param2,
success: function(msg){
//do something
}
};
var result=$.ajax(params).responseText;
}
Everything works fine when I call X("asdf","qwerty").
Now, what I want to do is to be able to call function X as follows:
function X(param1,param2,function(){alert('hi');}){
var params={
type: "POST",
url: "./ajax/useful.php",
data: "param1="+param1+"¶m2="+param2,
success: function(msg){
/////
//I want to be able call the function in the 3rd parameter (alert in this case)
/////
}
};
var result=$.ajax(params).responseText;
}
Now you might say why don't I just call alert('hi') directly inside the success. Sure I can do this, but I want to be able to vary what goes on inside the called function (not just a simple alert('hi'), depending on who's calling X.
You declare your X function like this:
function X(param1,param2,callback){
...use the callback like this:
success: function(msg){
callback();
}
...and call X like this:
X('a', 'b', function(){alert('hi');});
This works because your success handler is a closure over the data within your X function, including its arguments. It has a live reference to that information (even after X returns), and so later when the Ajax call completes, it can still use the callback argument. More on closures here: Closures are not complicated
function X(param1,param2,f){
var params={
type: "POST",
url: "./ajax/useful.php",
data: "param1="+param1+"¶m2="+param2,
success: function(msg){
f();
}
};
var result=$.ajax(params).responseText;
}
should work.
You can no call X like this:
X(param1,param2,function(){dowhatever})