I am working on AJAX and PHP PDO to insert a post and display it by ajax without reloading the page. I have an issue, when I click on the post button the message inserts one time and displays. It’s a good process but after that when I add the new message and click on the post button the message inserts 2 times in the database and displays the same two times. Same when I create a new message again the message inserts four times (I think ajax running many times after the first insertion ) but if I refresh the page and enter a new message the message inserts and displays one time. That’s good but I don’t want to refresh for every entry.
AJAX code –
$(document).on("click", "#save", function (e) {
e.preventDefault();
var message = $("#message").val();
var form_data = new FormData();
form_data.append('message', message);
var property = document.getElementById('photo').files;
property = property[0];
if(property){
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
form_data.append("file",property);
}
var propertyv = document.getElementById('video').files;
propertyv = propertyv[0];
if(propertyv){
var name = propertyv.name;
var extension = name.split('.').pop().toLowerCase();
form_data.append("video",propertyv);
}
//Ajax call to send data to the insert.php
$.ajax({
type: "POST",
url: "insert_posts.php",
data: form_data,
contentType:false,
cache:false,
processData:false,
success: function (data) {
$(data).insertAfter(".message-wrap:first");
$("#message").val("");
$("#photo").val('');
$("#video").val('');
$('#body-bottom').hide();
$('#body-bottom-video').hide();
$("#form")[0].reset();
}
});
});
You can see the image above the first message is inserting one time but if I create a new second message and click on the post button it inserts two times then same for – 4, 8 times for the next entries.
I don’t want to refresh and the second message should be inserted one time like the first message.
More details –
The ajax code is in another JS file . I have inked to index.php page
<script src="ajax.js"></script>
2
Answers
The one() method is useful for every event type. I have changed the line above
Now, it's working.
For more reference - https://api.jquery.com/one/
try add e.stopPropagation(); after e.preventDefault();