Carlos Veloz Carlos Veloz - 2 months ago 5
Ajax Question

Ajax result seems to concatenate to previous results

I have an ajax function that upload a comment to a form which returns the same string and if it success, the comment is pretended to a comment box and the comment input text is cleaned.

The problem is that if the user add another comment the function with add this new comment + the past comment to the comment box, where the first comment is already displayed.

i have a walk around where before the pretend i empty the comment box but this is not the best behavior.

this is my ajax function:

$("#formContent").submit(function(e){

e.preventDefault();

var formdata = new FormData(this);

$.ajax({
url: "php/comment_form.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(result){
$("#new_comments").empty();
$(result).hide().prependTo("#new_comments").fadeIn(1000);
$("input").empty();
},error: function(){
alert("Error");
}
});
});


So for example i add a comment : "Hello"

The div#new_comments will display:

Hello


(Thats the result from the php form)

But if i add a new comment: "World"
Then the div#new_comment will show:

World
Hello
Hello


And so..

Why is this happening?
I tried add a var with the result like

var comment = result;

Then after the comment is prepend:

var comment = "";

But it doesn´t work.

Any ideas?

Answer

Try .html("")

$("#new_comments").html("")
Comments