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 blank insert.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 is insert.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.