In my test work, I want to send data to DB by pressing "Save" button and stay at the same page. But this button after sending data to DB opens /file.php and shown "Success". I tried to solve the task by JS I found, but it doesn`t work.
$('#sub').click( function() {
$.post( $('myForm').attr('action'), $('#myForm :input').serializeArray(), function(info){ $('result').html(info);} );
clearInput();
});
$('myForm').submit(function() {
return false;
});
function clearInput() {
$('#myForm :input').each( function() {
$(this).val('');
});
}
<html>
<head>
<title>
OneTwoThree
</title>
</head>
<body>
<form id='myForm' action="db.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<button id="sub">Send</button>
</form>
<span id="result"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script/myjs.js" type="text/javascript"></script>
</body>
</html>
Callable PHP file:
<?php
$conn = mysql_connect('localhost','root','');
$db = mysql_select_db('mytestbd');
$name = $_POST['name'];
$age = $_POST['age'];
$q = "INSERT INTO `post`(`number`, `sometext`) VALUES ('$age','$name')";
if(mysql_query($q))
echo "Success";
else
echo "Fail";
?>