1

I want to append first, then run ajax to update the data and then do the search. See the code below. I want to put a code like if append, then run $.post. How can I do that in jquery, thanks?

$('<span />', { class: 'result_tag', text: href }).insertBefore($input);
         
 $('.result_tag').append(' ');

//make sure append first and then run .post

$.post("member_search.php", {
 search_text: $(".result_tag").text()

     }).done(function()
{       
$.post("member_search.php", {
       search_text: $(".result_tag").text()
},
  function(data){
 $("#find_members").html(data); 
       });
  });
conan
  • 1,327
  • 1
  • 12
  • 27

2 Answers2

2

The $.post() function returns a promise. You can call the done() function on this promise. The done() function takes a callback function which will be executed after the post to the server is done:

$.post("update.inc.php", {
      tag : $(this).closest("a").text(),
      users_id : $("#users_id").val()
    }).done(function(){

      // your second post goes here

    });
Simon
  • 296
  • 4
  • 17
  • Thanks for your time. I just edit my answer a little bit. How can I make sure append first, then run the .post. – conan Feb 27 '15 at 16:42
1

You can use $.ajax and its Event beforeSend like this:

$.ajax({
  url: "http://fiddle.jshell.net/favicon.png",
  data: 'search_text='+$(".result_tag").text(),
  beforeSend: function( xhr ) {
    $('.result_tag').append(' ');
  }
})
  .done(function( data ) {
    //now do your other ajax things
  });

Hope this will help you.

More Details are given in jQuery DOC

Ashish Awasthi
  • 1,484
  • 1
  • 19
  • 34
  • Thanks! It will append first,. but could not search the text. If I put append on the top of the ajax. it will append first and do the search, however, after several attempt, it broke. I don't know why. So, do you have a way to say that, if append was initial, then run the ajax? – conan Feb 27 '15 at 23:54
  • you can check that append is done successfully in beforeSend if its not then you can return false, and ajax request will be aborted. Read the doc it has everything that you need. ;) – Ashish Awasthi Feb 28 '15 at 11:13