2016-09-29 184 views
0

(對不起,我的英語)。Ajax代碼無法正常工作

我想做的是基本數據庫插入。實際插入部分工作正常的問題是index.php插入後重定向process.php。但它應該停留在同一頁面並清除所有字段我是什麼做錯了。

這是index.php文件

<!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> 

這是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(""); 
    }); 

} 

這是插入

<?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;} 

?> 
+0

您沒有提交來捕獲,但您需要阻止點擊的默認操作。 –

+0

**切勿存儲純文本密碼!**請使用PHP的[內置函數](http://jayblanchard.net/proper_password_hashing_with_PHP.html)來處理密碼安全性。如果您使用的PHP版本低於5.5,則可以使用'password_hash()'[兼容包](https://github.com/ircmaxell/password_compat)。確保你*** [不要越獄密碼](http://stackoverflow.com/q/36628418/1011527)***或在哈希之前使用其他任何清理機制。這樣做*更改密碼並導致不必要的附加編碼。 –

+0

感謝您的幫助和提示 –

回答

0

你試試這樣;

$("#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(""); 
    }); 
} 
+0

感謝您的幫助 –

+0

完全沒有。來自土耳其的問候:) –