Search code examples
javascriptasp.netcallbackpagemethods

Callback function with parameters


I'm using AJAX Page Methods, but I can't seem to be able to pass the needed parameters:

  function getFavStatus() {
    //favs is a list of DOM <imgs> that I want to modify their img.src attribute
    for (i = 0; i < favs.length; i++) {
      PageMethods.isFavorite(favs[i].alt,setFavImg(favs[i]));
    }
  }

  function setFavImg(fav, response) {
    fav.src = response;
  }

The problem that I can't figure out is how to use the "response" from PageMethods, AND pass the DOM object to the callback function.

I've also tried doing something like this:

 function getFavStatus() {
    for (i = 0; i < favs.length; i++) {
      PageMethods.isFavorite(favs[i].alt, function (response) {
                favs[i].src = response;});   
      );
    }
  }

In this case, the response works properly, but i is always > favs.length, because it has already iterated through the loop...

Edit: My PageMethods.isFavorite signature is:

[System.Web.Services.WebMethod]
public static string isFavorite ( string p_id )

Can anyone point me in the right direction?

Thanks!


Solution

  • Try this out:

    PageMethods.isFavorite(favs[i].alt, 
      function (response, ctx) {
           /* success callback */
           ctx.src = response;
      },
      function(response) { /* failed callback */ },
      favs[i] /* context */);
    

    The context is passed to the callbacks, so you can pass in the reference to the image to the callbacks, and set it in the callback there.

    The original issue is that the page methods is asynchronous, so the callback isn't firing until after the loop completes. Hence the last item being affected.

    HTH.