2015-10-17 146 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

雅肯定。很高兴它帮助你:) –