I am using Visual Studio 2010 and MVC 3 with AJAX/JQuery. The issue I am having is that the code is posting something twice. It only happens when you post something, then do it again.
Here is my JS:
$(document).ready(function () {
BindEvents();
});
function BindEvents() {
$('#OpenCommentDialog').click(function (event, ui) {
var id = $(this).attr('data');
$('#NewCommentDialog').dialog({
open: function (event, ui) {
$('#BugID').val(id);
var form = $('form', '#NewCommentDialog');
form.submit(function (e) {
var comment = form.serialize(true);
CreateComment(comment);
return false;
});
}
});
$('#NewCommentDialog').dialog('open');
return false;
});
}
function CreateComment(comment) {
if (comment != null) {
$.post('/Comments/Create/', comment, function (data) {
if (data == 'Success') {
var id = $.parseQuery(comment);
GetComments(id.BugID);
$('#NewCommentDialog').dialog('close');
}
});
}
}
function GetComments(id) {
$('#Comments').find('tr').remove();
$.getJSON('/Comments/GetComments', { id: id }, function (data) {
if (data != null) {
if (data.length > 0) {
$('#CommentListTemplate').tmpl(data).appendTo('#Comments');
}
}
});
}
My HTML page has a JQuery dialog box that calls a CreateCommentPartial.cshtml file. When the user fills it out, it calls the "CreateComment" function, which then calls the "GetComments" and refreshes the comments after the new one is posted.
Now, here's the issue. If you click the "Create Comment" link again, without reloading the page and fill out the form, the "CreateComment" is fired twice and "GetComments" is fired twice as well. Firebug shows me this as well.
What am I doing wrong here? If you reload the page (F5) after posting it doesn't do this. But it defeats the purpose. One should be able to submit a comment multiple times without reloading the page.
Where have you declared the above script? I had a similar problem with a script that was added to the page by a partial view. Somehow the script was added to the page for each click of a button thus multiplying the script and the number of posts (each copy of the script firing once). I solved the problem by putting the script in a separate .js file and referencing it in the master page