PHP代码在使用表单操作调用时有效,但在使用ajax时无效

时间:2017-02-27 17:54:02

标签: javascript php jquery ajax

使用表单操作从html页面运行时,登录验证的PHP代码正常工作,但是当使用ajax脚本运行时,它无法加载。

不涉及数据库的PHP代码似乎运行正常。

的JavaScript

< script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" > < /script> <
  script >
  $(document).ready(function() {
    $("#login").submit(function(event) { //Trigger on form submit
      $('#name + .throw_error').empty(); //Clear the messages first
      $('#success').empty();
      var postForm = { //Fetch form data
        'name': $('input[name=name]').val(),
        'password': $('input[name=password]').val() //Store name fields value
      };

      $.ajax({ //Process the form using $.ajax()
        type: 'POST', //Method type
        url: '.php', //Your form processing file url
        data: postForm, //Forms name
        dataType: 'json',
        success: function(data) {

          if (!data.success) { //If fails
            if (data.errors.name) { //Returned if any error from process.php
              $('.throw_error').fadeIn(1000).html(data.errors.name).append('<p>' + data.error + '</p>'); //Throw relevant error
              alert("Nope");
            }
          } else {
            $('#success').fadeIn(1000).append('<p>' + data.name + '</p>'); //If successful, than throw a success message
            alert("yes");
          }
        }
      });
      event.preventDefault(); //Prevent the default submit
    });
  }); < /script>

PHP代码

<?php
    $errors = array();
    $form_data = array();
   include("config.php");
   if (session_status() == PHP_SESSION_NONE) {
   session_start();}
        else{
      $_SESSION['ses']="Already in session":
       /* Write already in session code */
   }
   if($_SERVER["REQUEST_METHOD"] == "POST") {
      // username and password sent from form 

      $myusername = mysqli_real_escape_string($db,$_POST['username']);
      $mypassword = mysqli_real_escape_string($db,$_POST['password']);    

      $sql = "SELECT * FROM users WHERE user_name = '$myusername' and password = '$mypassword'";
      $result = mysqli_query($db,$sql);
      $row = mysqli_fetch_array($result,MYSQLI_ASSOC);


      $count = mysqli_num_rows($result);

      // If result matched $myusername and $mypassword, table row must be 1 row
        if (empty($_POST['name'])) { //Name cannot be empty
        $errors['name'] = 'Name cannot be blank';
    }

    if (!empty($errors)) { //If errors in validation
        $form_data['success'] = false;
        $form_data['errors']  = $errors;
    }
    else{
      if($count == 1) {
         $_SESSION['login_user'] = $myusername;

      }else {
         $error = "Your Login Name or Password is invalid";
         $_SESSION["error"] = $error;
      }
   }
   }
       echo json_encode($form_data);
?>

0 个答案:

没有答案