ali ak ali ak - 2 months ago 8
PHP Question

Ajax code not working properly

(sorry for my english).

What I want to do is to basic database insert .Actually inserting part works fine the problem is index.php redirects process.php after inserting.But It should stay at the same page and the clear all the fields What am I doing wrong.

this is index.php file

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>

</head>
<body>
<form action="process.php" id="myForm" method="post">
UserName <input type="text" name="uname"><br>
Pass <input type="text" name="pass"><br>
FirstName <input type="text" name="fname"><br>
LastName <input type="text" name="lname"><br>
<button id="submit" value="register"></button>


</form>
<div id="ack">Ack</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="site.js"></script>
</body>
</html>


this is the site.js

$("#submit").click( function() {

$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {

$("#ack").empty();
$("#ack").html(info);
clear();
});

$("#myForm").submit( function() {
return false;
});
});

function clear() {

$("#myForm :input").each( function() {
$(this).val("");
});

}


And this is for inserting

<?php
require("config.php");
$uname =$_POST["uname"];
$pass = $_POST["pass"];
$fname = $_POST["fname"];
$lname = $_POST["lname"];

$insert=$db->prepare("insert into users (uname,pass,fname,lname) values(?,?,?,?)");
$insert->bind_param("ssss",$uname,$pass,$fname,$lname);
if($insert->execute()){
echo "ok";
}
else
{$db->error;}

?>

Answer

You try it like this;

$("#myForm").submit( function() {
    return false;
    });

$("#submit").click( function() {

$.post( $("#myForm").attr("action"),
    $("#myForm :input").serializeArray(),
    function(info) {

        $("#ack").empty();
        $("#ack").html(info);
        clear();
    });
});

function clear() {

    $("#myForm :input").each( function() {
        $(this).val("");
    });
}