0

I have a piece of jQuery code as follow. When the button with id some_button is clicked, it gets some data (which is HTML code) from an url and then put the HTML it gets into some_div. The HTML it gets contains some buttons with class run and I want this buttons to be triggered automatically. With the following code, the run buttons are never trigger automatically when some_button is clicked for the first time, but works when it's clicked the second time. Another strange thing I notice is, when I use Chrome break points to step through the code, I find that it executes $(".run").trigger("click"); before executing $("#some_div").empty(); and $("#some_div").append(data.info);. Why is it executed in this order?

$("#some_button").click(function()
{
    //some code here
    $.get("/some_url", function(data){
      $("#some_div").empty();
      $("#some_div").append(data.info); 
    });
    $(".run").trigger("click");
});
user274602
  • 59
  • 1
  • 2
  • 7
  • Have you looked at the documentation for $.get? You should look at the done function: https://api.jquery.com/jquery.get/ (if using later than jquery 1.8 see then instead) – Mike Cheel Jul 16 '15 at 19:42
  • Just put it in the asynchronous callback where you have used `data`… – Bergi Jul 16 '15 at 19:44

1 Answers1

1

Docs on get might help you with this.

$("#some_button").click(function()
{
    //some code here
    $.get("/some_url", function(data){
      $("#some_div").empty();
      $("#some_div").append(data.info); 
    }).done(function() {
       $(".run").trigger("click");
    });    
});

In addition, $.get() implements the promise interface so you can leverage the .then(); functionality as well...

ODelibalta
  • 2,194
  • 1
  • 18
  • 28