Reputation: 205
I am having difficulty calling multiple instances of the same Ajax.Request function. (I'm using the Prototype framework). Here is the function:
function send_SMS(id)
{
status_id = 'status_link_' + id;
new Ajax.Request('sendSMS.php',
{
method:'post',
parameters: {link_id: id},
onCreate: function(){
$(status_id).update("sending...");
},
onSuccess: function(transport){
if (transport.responseJSON.success) {
$(status_id).update("sent");
} else {
$(status_id).update("unable to send");
}
},
onFailure: function(){
$(status_id).update("unable to send");
}
});
}
If I call this function twice with 2 different id numbers i.e.:
send_SMS("1");
send_SMS("2");
only the second ID is updated by the onSuccess function. The sendSMS.php file is successfully run twice (as the name suggests it sends an SMS message and indeed the 2 messages are successfully sent), but the onSuccess function seems to only be called the second time.
Is the javascript confusing the 2 instances?
Upvotes: 1
Views: 800
Reputation: 205
This is the working function:
function send_SMS(id)
{
new Ajax.Request('sendSMS.php',
{
method:'post',
parameters: {link_id: id},
onCreate: function(){
$('status_link_' + id).update("sending...");
},
onSuccess: function(transport){
if (transport.responseJSON.success) {
$('status_link_' + id).update("sent");
} else {
$('status_link_' + id).update("unable to send");
}
},
onFailure: function(){
$('status_link_' + id).update("unable to send");
}
});
}
Upvotes: 0
Reputation: 21532
I think this is because status_id is a global variable, and therefore enters in the context of your both calls within the callback where its reference is being called:
onSuccess: function(transport){
if (transport.responseJSON.success) {
$(status_id).update("sent");
} else {
$(status_id).update("unable to send");
}
}
The thing is, the onSuccess callback will compile when it is called, with its context at that moment. And at that moment, the status_id will be equal to "status_link_2", because most chance that your call to send_SMS("2");
will come before the return of the first sms_send call.
A solution would be to:
Upvotes: 1