user2489311
user2489311

Reputation:

How to assign a JQuery event handlers to a specific event

I have the following Javascript function called Howto that is executed when a button is pressed:

function howto(){

   $('#elementtoupdate').ajaxSend(function() {
       //Code to execute
   });

   $('#elementtoupdate').ajaxComplete(function() {
       //Code to execute
   });

   $('#elementtoupdate').load('serverside/file_path.php')
}

Using JQuery the function assigns two JQuery Global Ajax Event Handlers, they are initiated when the any AJAX calls are initiated. Then the function continue and calls a JQuery .load function, and any code inside the Global Ajax Event Handlers is initiated.

However, as the name the word Global suggests they are also initiated by other Jquery AJAX calls. This unfortunately is undesirable as I have other AJAX calls in the script. I need the code to be executed only when $('#elementtoupdate').load('serverside/file_path.php') is executed.

What is the best way of doing this?

Upvotes: 1

Views: 73

Answers (2)

LeGEC
LeGEC

Reputation: 52236

You should accept David Hedlund's answer. For the sake of completeness :

you can change :

function howto(){

   $('#elementtoupdate').ajaxSend(function() {
       //code to be executed before send
   });

   $('#elementtoupdate').ajaxComplete(function() {
       //code to be executed after completed
   });

   $('#elementtoupdate').load('serverside/file_path.php')
}

to :

function howto(){
    //code to be executed before send

    $('#elementtoupdate').load('serverside/file_path.php', function(){
        //code to be executed after completed
    })
}

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129832

load has callbacks on its own that are not global:

.load( url [, data ] [, complete(responseText, textStatus, XMLHttpRequest) ] )

Thus:

$('#elementtoupdate').load('serverside/file_path.php', function() {
  // complete
});

Upvotes: 4

Related Questions