Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to a javascript callback function [duplicate]

Tags:

javascript

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);
}
like image 444
JIbber4568 Avatar asked Dec 02 '11 16:12

JIbber4568


3 Answers

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.

like image 179
Alex Turpin Avatar answered Sep 28 '22 02:09

Alex Turpin


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.

like image 40
Matt Ball Avatar answered Sep 28 '22 02:09

Matt Ball


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.

like image 28
Adam Rackis Avatar answered Sep 28 '22 02:09

Adam Rackis