0

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).

3 Answers 3

4

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).

Sign up to request clarification or add additional context in comments.

1 Comment

I am running into same issues even with async-await .. any idea?
1

Well first off all i would not put the code directly in onClick just attach the handler $(selector).click(). regardless your code wont do what you are 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;
});

Comments

0
$(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
      });
   })
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.