html - AJAX not preventing redirection to PHP page

With the help of AJAX, I've been trying to prevent the automatic redirection to a blank PHP page after submitting a form, but I'm not managing. The data submitted to the form is being entered into the MySQL table, but upon clicking submit, I'm always redirected to the blankinsert.php
page.
Here is the HTML form:
<tr>
<td></td>
<form class = "ajax" action = "insert.php" method="POST">
<td><input type="text" class = "inputs" name = "dcs" id = "dcs"/></td>
<td><input type="text" class = "inputs" name = "qty" id = "qty"/></td>
<td><input type="text" class = "inputs" name = "rate" id = "avg"/></td><td></td>
<td><div style = "position: relative;"><input type="submit" onclick="add_new_entry();" id = "submit"/></div></td>
</form>
<td></td>
<tr>
Here is the jQuery function:
$(document).ready(function() {
$('form.ajax').submit(function(event) {
event.preventDefault();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success = function(response) {
alert(response);
}
});
return false;
});
});
Here isinsert.php
:
<?php
include "db_connect.php";
$code = 4;
$dcs = mysqli_real_escape_string($conn, $_POST['dcs']);
$qty = mysqli_real_escape_string($conn, $_POST['qty']);
$rate = mysqli_real_escape_string($conn, $_POST['rate']);
$total = $qty * $rate;
$sql = "INSERT INTO entries VALUES ('$code',
'$dcs','$qty','$rate','$total');";
// $conn is the connection
mysqli_query($conn, $sql)
mysqli_close($conn);
?>
Please let me know of the changes that I should make so that I'm not redirected to the PHP page after submitting the form.
Let me know if I should provide any other code snippets.
Thanks a lot.
Answer
Solution:
So there is a neat trick where you can addreturn false;
on the onclick function to prevent the page from submitting. I think the issue in here is that you submit the form already before you prevent it from submitting, what you could do otherwise is creating a click event before the submit part which needs to prevent the submittion of the formm OR use the jquery $.post en instead of the submit event
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the metadata storage is not up to date, please run the sync-metadata-storage command to fix this issue.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.