Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
810 views
in Technique[技术] by (71.8m points)

validate login form with php and AJAX

This is my first time using AJAX with php and I have a login form . When I submit I want to check my mongodb database to see if the submitted username exists . If it does login succesfully else alert('user does not exist'); . However I do not know how to implement this completely and I need our help .

My code :

login.php

 <form action = "index.php" method = "POST" name= "logForm">
      <label for="username">Username:</label>
      <input type="username"  id="username" placeholder="Enter username" name="username" required/>
  </form>
 

script.js

$("#logForm").submit((e)=>{
    var usernameForLog = $("username").val();
    var passwordForLog = $("password").val();
    $.ajax({
      url:'validateUser.php',
      type:'post',
      data:{
          submitLogin:1,
          username: usernameForLog ,
          password: passwordForLog,
      }
    })
  });

validateUser.php

 <?php
  
  require '../vendor/autoload.php';

  $m = new MongoDBClient("mongodb://127.0.0.1/");
  $db = $m ->ECommerce;

  $collection = $db->users;
  
  if(isset($_POST["submitLogin"])){

    $uname = $_POST['username'];
    $pwd = $_POST['password'];
    $cursor = $collection->find(array('userName' => $uname ));
    
    
    $document = 0;
    foreach ($cursor as $doc){
        $document = $document +1;
    }

    if($document == 0){
      echo "<script> alert(No account found !); </script>";
      header('../php/index.php');
    }

    else{
      session.start();
      $_SESSION['user']= $uname;
    }

    

  }


?>

If I submit my form I just get redirected to index.php with no check .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...