Reputation: 31
I've looked up a lot of tutorials and poked around on here but haven't found anything that addresses my specific issue. I am guessing I have a syntax error or logic error somewhere in my code. My issue is that whenever I submit the form, I get directed to the test.php page. The php is working correctly as it is returning the correct result but I just want that to run and display the submitted form information underneath. Any help would be greatly appreciated.
index.html
<html>
<head>
<title>Computer swap form</title>
</head>
<body>
<form method = "post" action = "test.php" id="computerForm">
Serial Number: <br>
<input name="serialnumber" type="text">
<button id = "sub"> Submit </button>
</form>
<!--display the response returned after form submit -->
<span id ="result"></span>
<script type="text/javascript" src = "https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>
test.php
<?php
$sn = $_POST['serialnumber'];
if(!isset($sn))
{
echo "error serial number not set";
}
else {
echo "$sn successfully saved";
}
?>
my_script.js
$("#sub").click( function() {
$.post( $("#computerForm").attr("action"),
$("#computerForm").serialize(),
function(info){ $("#result").html(info);
});
});
$("#computerForm").submit( function() {
return false;
});
Upvotes: 1
Views: 66
Reputation: 337743
To achieve what you require put all your logic in the submit
handler, and call preventDefault()
on the event argument provided to the handler function:
$("#computerForm").submit(function(e) {
e.preventDefault();
$.post(this.action, $(this).serialize(), function(info) {
$("#result").html(info);
});
});
Upvotes: 5