Reputation: 73
I have a function where a user can a report a post, the user clicks the report button, and then promptly enters the information for the report. This works, the problem is if the page hasn't reloaded and the user decided to report a second post the data for that report enters the database twice. Why is this?
Here's the code:
$(document).ready(function() {
$(".report_post").click(function(e) {
var nid = $(this).attr("id");
$("#report_reason").dialog({
resizable: false,
height: 300,
width: 400,
modal: true,
});
$('.submit_report_post').click(function() {
var content = $("#report_content").val();
var type = "Post";
if ($('input[name="report"]:checked').length > 0 && (content != null &&
content != "")) {
var complaint = document.querySelector('input[name="report"]:checked').value;
alert('Reported!');
$.ajax({
type: 'POST',
url: 'php/report_post.php',
data: {
type: type,
nid: nid,
reason: complaint,
content: content,
},
cache: false,
success: function(data) {
$("#report_content").val("");
$("input[name='report']").prop('checked', false);
//$("#report_reason").dialog('close');
}
});
} else {
alert('Fill all of the information!');
}
});
e.preventDefault();
});
});
Upvotes: 0
Views: 68
Reputation: 207901
You're submitting your form twice, once the normal way and once via AJAX. You have e.preventDefault();
in your code which would normally stop the typical non-AJAX submission, however you never created the e
argument.
Change:
$('.submit_report_post').click(function() {
to
$('.submit_report_post').click(function(e) {
and this will make the form only submit through the AJAX code.
Upvotes: 2
Reputation: 834
You are binding click
on $('.submit_report_post')
every time you click on $(".report_post")
, you need to do it outside of first bind
$(document).ready(function() {
$(".report_post").click(function(e) {
var nid = $(this).attr("id");
$("#report_reason").dialog({
resizable: false,
height: 300,
width: 400,
modal: true,
});
e.preventDefault();
});
$('.submit_report_post').click(function() {
var content = $("#report_content").val();
var type = "Post";
if ($('input[name="report"]:checked').length > 0 && (content != null &&
content != "")) {
var complaint = document.querySelector('input[name="report"]:checked').value;
alert('Reported!');
$.ajax({
type: 'POST',
url: 'php/report_post.php',
data: {
type: type,
nid: nid,
reason: complaint,
content: content,
},
cache: false,
success: function(data) {
$("#report_content").val("");
$("input[name='report']").prop('checked', false);
//$("#report_reason").dialog('close');
}
});
} else {
alert('Fill all of the information!');
}
});
});
Upvotes: 0