2015-10-17 82 views
0

我嘗試在成功驗證表單後進行ajax請求。如果我刪除,url: 'loginprivate.php' PHP代碼工作,但驗證不。如果我添加,的驗證工作,但PHP代碼不是。無論如何,成功的Ajax請求後重定向不工作。我怎樣才能使這個工作,也許與$(form).ajaxSubmit();當是的,我應該在哪裏添加這條線?jquery驗證後的ajax請求

$(document).ready(function() { 
     $('#myform').validate({ // initialize the plugin 
      rules: { 
       username: { 
        required: true, 
        minlength: 2, 
        maxlength: 30 
       }, 
       password: { 
        required: true, 
        minlength: 3, 
        maxlength: 30 
       } 
      }, 
      submitHandler: function (form) { // for demo 
       $.ajax({ 
    type: 'post', 
    url: 'loginprivate.php', //url where you want to post the stuff. 
    data:{ 
     username: 'root', 
     password: '' 
    }, 
    success: function(res){ 
     //here you will get res as response from php page, either logged in or some error. 
     window.location.href = "http://localhost/localcorps/main.php"; 
    } 
}); 
       return false; // for demo 
      } 
     }); 
    }); 

我的PHP代碼:

if(isset($_POST["submit"])) 
    { 
      $hostname='localhost'; 
      $username='root'; 
      $password=''; 

      unset($_POST['password']); 
      $salt = ''; 
      for ($i = 0; $i < 22; $i++) { 
        $salt .= substr('./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', mt_rand(0, 63), 1); 
      } 
      $_POST['password'] = crypt($_POST['password'],'$2a$10$'.$salt); 
      $new = 0; 
      try { 
        $dbh = new PDO("mysql:host=$hostname;dbname=search",$username,$password); 
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line 
        $sql = "INSERT INTO users (username, password) 
        VALUES ('".$_POST["username"]."','".$_POST["password"]."')"; 
        if ($dbh->query($sql)) { 
          echo "New Record Inserted Successfully"; 
        } 
        else{ 
          echo "Data not successfully Inserted."; 
        } 
        $new = $dbh->lastInsertId(); 
        $dbh = null; 
      } 
      catch(PDOException $e) 
      { 
        echo $e->getMessage(); 
      } 
      if ($new > 0) 
      { 

       $t = time() + 60 * 60 * 24 * 1000; 
       setcookie("username", $_POST['username'], $t); 
       setcookie("userid", $new , $t); 
      } 
     else 
      { 

      } 
    } 
+0

顯示PHP代碼。沒有意義的是不發送真正的價值作爲數據。檢查瀏覽器開發工具網絡中的實際請求以獲取更多線索。狀態500? – charlietfl

+0

我編輯我的問題;) – Bodoppels

+0

請檢查下面的答案,在數據中添加一個字段。它會工作 –

回答

1

進出口你的Ajax添加此

data:{ 
    username: 'root', 
    password: '', 
    submit: true,// add this line as you are checking in php file. 
}, 
+0

謝謝在此之後我搜索了任何日子,我接受你的答案在9分鐘內。 :) – Bodoppels

+0

雅肯定。很高興它幫助你:) –