I am trying basic database insert using ajax and inserting part works fine the problem is that page is getting redirected after inserting completed.I had came acroos this issue before and found a solution (changed the src part like below)
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
But that solution didt work this time what am i dıing wrong again?
this is index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="site.js"></script>
</head>
<body>
<form action="process.php" id="myForm"method="post">
<input type="text" name="uname"><br>
<input type="text" name="pass"><br>
<input type="text" name="fname"><br>
<input type="text" name="lname"><br>
<button id="submit" value="Insert"/> <br>
</form>
<div id="ack"></div>
</body>
</html>
and this is my script
$("#submit").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#ack").empty();
$("#ack").html(info);
clear();
});
});
$("#myForm").submit( function(event) {
event.preventDefault();
return false;
});
function clear() {
$("#myForm :input").each( function() {
$(this).val("");
});
}
The submit call doesn't really belong in the click handler, move it out and use event.preventDefault() if you want to avoid form submission by means other than the click handler you created.
$("#submit").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#ack").empty();
$("#ack").html(info);
clear();
});
});
$("#myForm").submit( function(event) {
event.preventDefault();
return false;
});
function clear() {
$("#myForm :input").each( function() {
$(this).val("");
});
}
Switch to a .submit() event handler:
$("#myForm").submit(function(event) {
$.post($("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#ack").empty();
$("#ack").html(info);
clear();
});
event.preventDefault();
});
Description
Code
$("#myForm").submit(function (event) {
$.post($("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function (info) {
$("#ack").empty();
$("#ack").html(info);
// instead of using the clear() function
// separately you may clear all the empty
// fields like this
$('#myform')[0].reset();
});
event.preventDefault();
});
Not sure if this will work with jQuery 1.8.2 but here is how I've accomplished this same thing in the past.
$('#myForm').on('submit', function(e) {
e.preventDefault();
var details = $('#myForm').serialize();
$.post('process.php', details, function(data) {
$('#ack').html(data);
$('#myForm').trigger("reset");
});
});