tags:

views:

50

answers:

3

Okay, so I have a snippet of code from a website containing a button:

    <button type="button"
            onclick="laser(); $.post('sheepDB.php', { vic: vic, num: numVics });">
    Activate Her Powers!
    </button>

However, when I click the button the first time, the first function executes, but if I click it a second time, both the first function AND the Ajax call are executed. How do I get onclick to execute them sequentially? (laser() determines the values sent by the Ajax request, so it must be sequential).

+2  A: 

Javascript does execute sequentially. However, AJAX is asynchronous (hence the A), which means that Javascript execution continues while the AJAX request is taking place. If you trigger your onclick a second time before the first AJAX request completes, it is possible that the first AJAX request will not complete before the second click (and thus look like it's only happening once).

Daniel Vandersluis
+1  A: 

Well first off i wouldnt put the code directly in on click just attach the handler $(selector).click(). regardless youre code wont do what youre trying to do... you need something like this as your handler:

$(selectorForButton).click(
  function(e){
  e.preventDefault(); // dont fire the normal event

  /* youll probably have to rework laser if it depends on `this` referring to the dom element    
   * clicked in this example lets say it returns a hash of vic and num vics...
   */
  var _this = $(this);
  var data = laser(this);
  // check if this is already sending a post request
  if(!_this.data('activated')){
     $.post('sheepDB.php', data, function(){
       // this is important - we need to set it to false so we now on the next click that
       // post innt in the process of doing its thing
        _this.data('activated', false);
     });
  }

  return false;
});
prodigitalson
A: 
$(document).ready(function () {
   $('#yourButtonId').click(function() {
      // collect your values into a json object
      var someData = {
         x: '',
         y: '',
         z: ''
      };

      //execute post
      $.post('someUrl', someData, function(data, textStatus) {
         // callback
      });
   })
})
cj_battista