views:

160

answers:

3

Hi All,

I have some submit buttons that are defined in the following manner:

<input id="add_200,231" type="submit" onclick="updatePage(401,27371,200,231)" value="Add"/>

The corresponding javascript function referenced in "onclick" looks like this :

function updatePage(slac,sci,tlac,tci) {
 var url = '/neighbouring?.state=add_cell&source=' + slac + ',' + sci +'&target='+ tlac + ',' + tci + '&dummy='+(new Date()).getTime();

 new Ajax.Request(url,{
  onComplete: triggerContentUpdate(slac,sci)  
 });
}

function triggerContentUpdate(slac,sci) {
 var updates = document.getElementsByClassName('update_on_add');
 for (var i = 0; i < updates.length; i++) {
  var uid = updates[i].id;
  var url = '/neighbouring?.state=update_template&divid=' + uid + '&source='+slac + ',' +sci + '&dummy='+(new Date()).getTime();
  var uAjax = new Ajax.Updater(uid,url,{ method: 'get'});

 }
}

The elements that need to be updated are tagged with "update_on_add" class tags.

When using Firebug, i can see that the Ajax.Request in updatePage() as well as the Ajax.Update in the triggerContentUpdate() functions are called at the same time. I would have expected triggerContentUpdate() to only be called after Ajax.Request has completed.

Am i missing something here ?

+2  A: 

Your line

onComplete: triggerContentUpdate(slac,sci)

should be

onComplete: function() { triggerContentUpdate(slac,sci); }

You're calling the function immediately and assigning its return value to the onComplete member.

Greg
A: 

Thank you Greg ! That sorted out the problem :-)

Thanks Arun for explaining this behaviour !

Hartmut Behrens
Hi Hartmut Behrens, I think you should mark answer as accepted by ticking the tick mark if you have accepted the answer
Arun P Johny
Can't find a tick mark anywhere on this page - where do i locate it ?
Hartmut Behrens
+3  A: 

The problem with your configuration is the callback you are registering is not a function reference it is a function call.

onComplete: triggerContentUpdate(slac,sci)

When javascript finds the above line it will call the function triggerContentUpdate with the given parameters and assign the return value of the function to onComplete property.

Greg has already sugested one way of handling this, there we are assigning an anonymous function reference to the the property onComplete.

Another way of handling this make the function triggerContentUpdate to return a function as given below

function triggerContentUpdate(slac,sci){
    return function(){
        //Your logic goes here. Both your variables slac and sci are available inside the returned function.
        //This uses the concept of javascript clousure
    }
}
Arun P Johny