I've been trying to work out how to pass additional parameters to a javascript callback function.
In similar posts users have succeeded using anonymous function (these are new to me so I may have been doing them wrong) but I just can't get them to fire.
The below is what I have now, I need to be able to pass the itemId to the function "ajaxCheck_Callback" as well as the response.
Hope this makes sense.
Thanks for the help.
function delete(itemId)
{
selectpage.ajaxCheck(itemId, ajaxCheck_Callback);
}
Function ajaxCheck_Callback(response)
{
alert(response);
alert(itemId);
}
Thanks for the help guys. I now get undefined on my alert whereas previously this was alerting correctly.
function delete(itemId)
{
selectpage.ajaxCheck(itemid, function () {ajaxCheck_Callback(itemid); });
}
function ajaxCheck_Callback(response)
{
alert(response);
alert(itemId);
}
The way is usually done is to use an anonymous function.
function deleteItem(itemId) {
selectpage.ajaxCheck(itemId, function() { ajaxcheck_Callback(itemId); });
}
function ajaxCheck_Callback(response)
{
alert(response);
}
Careful with your syntax, there are some errors in there. The function
keyword has a lower-case f
and you can't have a function named delete
, that's a reserved keyword.
As your question mentions, you can do it using an anonymous function:
function deleteItem(itemId)
{
selectpage.ajaxCheck(itemId, function ()
{
ajaxCheck_Callback(itemId);
});
}
// Note, lowercase 'f' in 'function'
function ajaxCheck_Callback(response)
{
alert(response);
}
It can also be done using a named function, which you might find more readable:
function deleteItem(itemId)
{
function onAjaxCheck()
{
ajaxCheck_Callback(itemId);
}
selectpage.ajaxCheck(itemId, onAjaxCheck);
}
N.B. as @Xeon06 points out, delete
is a reserved word, so that is not a valid function name.
Create an anonymous function, which calls your callback, and supplies the needed parameter.
function deleteItemById(itemId)
{
selectpage.ajaxCheck(itemId, function() { ajaxCheck_Callback(itemId); });
}
The anonymous function will create a closure over itemId
, and therefore will still have access to this value even after the original call to delete has long since ended.
For completeness, also note that delete
is a reserved word in JavaScript; you need to name this function something else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With