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); 
							});
  });

1
  • 4
    You do the second request in the callback of the first. Commented Feb 27, 2015 at 16:14

2 Answers 2

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

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

1 Comment

Thanks for your time. I just edit my answer a little bit. How can I make sure append first, then run the .post.
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

2 Comments

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

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.