javascriptjquerycallbackjquery-callbackjquery-events

How to add a callback on click jQuery function?


I have an asynchronous problem and for solve it I think I must use a callback. I want to execute some code after the code that is inside of the click() function finishes. How can I do that?

$("#mybutton").click(function() {
    $.ajax({
      type: 'GET',
      data: {
        accion: "get_option_child",
        id: id
      },
      url: 'webservices.php',
      success: function(data) {
        var json = JSON.parse(data);
        // some code
      }
  });
});

Solution

  • Just add a call to your desired function at the end of the success handler for ajax:

    $("#agregar_opcion").click(function() {
      // ...
      $.ajax({
        // ...
        success: function(data) {
          // ...
          functionThatRunsAfterAjaxSuccess();
        }
      });
    });
    
    function functionThatRunsAfterAjaxSuccess() {
      // gets called once the ajax call happening on click is successful
    }