vzhen
vzhen

Reputation: 11157

Remove the previous ajax called result?

I am using jquery and I have 2 ajax call function. When I call the first ajax request then the result will display at div id="result". Then I call the second ajax and I want it to display at div id="result" as well and replace the previous result which return from first ajax. From my tested, I still able to see the previous result under browser developer tools.

The second question is, if repeatly click will cause memory leak or not?

$.ajax({
  url: "ajax/func1",
  type: "post"
});

$.ajax({
  url: "ajax/func2",
  type: "post"
});

Upvotes: 2

Views: 3289

Answers (4)

Shriram
Shriram

Reputation: 21

You can use .html(' ') - html function with null string before the second result which will replace the first result as empty and then the result of the second ajax call will be replaced.

The following is the code:

$.ajax({

url:'someurl',

type:'post'

success: function(){

$("#result").html(result);

}

});

$.ajax({

url: "ajax/func2",

type: "post"

success: function(){

$("#result").html(' ');

$("#result").html(result);

}

});

Upvotes: 0

Nope
Nope

Reputation: 22339

Then I call the second ajax and I want it to display at div id="result" as well and replace the previous result which return from first ajax.

Using the html() method should replace the content with the returned result every time. You can assign the result to your div in the done callback for example.

$.ajax({
  url: "ajax/func1",
  type: "post"
}).done(function(result) { 
  $("#result").html(result);
});

$.ajax({
  url: "ajax/func2",
  type: "post"
}).done(function(result) { 
  $("#result").html(result);
});

done is essentially the same as success but if I understood the comments in the documentation correctly is might be deprecated soon.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

if repeatedly click will cause memory leak or not?

No, it should not cause a memory leak. All requests should execute after each other.

Upvotes: 1

Alexey Bychkov
Alexey Bychkov

Reputation: 581

If there are two ajax async request, second request can be completed before your first request. In this case you will see first result in the end. You should call second ajax request in success callback of your first request. For example:

 $.ajax({
  url:'someurl',
  type:'post'
  success: function(){
  // Insert smth in result div
  // call second ajax request
}

Upvotes: 1

Philippe Leybaert
Philippe Leybaert

Reputation: 171864

Javascript is essentially single-threaded, so your calls will never conflict or cause memory leaks. However, the timing is undetermined. The first call that completes will be executed first.

In other words, all asynchronous callbacks will happen on the same thread, sequentially.

Upvotes: 2

Related Questions