1

Let's say I have a login form, with 2 fields, email and password, first I want to check if the user email is actually registered or not, so I made a separate file named user_check.php with the PHP code to check if a user exists or not,

include_once('../../classes/user.class.php');
$User = new User();
if ($User -> UserExists($_POST['login_email']) === true) {
    echo true;
} else {
    echo false;
}

now from login page, I want to call in an AJAX request to actually check if the UserExists() method returns false or true, if it returns false I will just give an error message to the user, else the code will continue

$.ajax({
    url: 'ajax/login-handler/user_check.php',
    type: 'POST',
    data: {login_email: email.val()},
    cache: false,
    success: function(data) {
        if (data == 1) {
            alert('Exists');

        } else alert('Doesn\'t Exist');
    }
});

Should I do nested Ajax calls for other database checks inside success block if statements? Or if I need to do separate Ajax calls how can I pass one Ajax calls response to the other call?

Raahim Fareed
  • 501
  • 7
  • 17
  • 1
    jquery ajax request inside ajax request https://stackoverflow.com/questions/10089447/jquery-ajax-request-inside-ajax-request – Adam Mudianto May 24 '20 at 19:09

2 Answers2

0

If you have to make multiple asynchronous calls, I think the cleanest way would be to have an async function that awaits every asynchronous call you have to make. For example, using fetch, which supports well-formed Promises:

$(form).on('submit', (e) => {
  e.preventDefault();
  tryLogin()
    .catch((e) => {
      // handle errors
    });
});
const tryLogin = async () => {
  const userExists = await fetch('ajax/login-handler/user_check.php', {
    method: 'POST',
    body: JSON.stringify({ login_email: email.val() })
  });
  if (!userExists) {
    // doesn't exist, tell user and return
    return;
  }
  // user exists
  const someOtherResult = await fetch('ajax/login-handler/somethingElse.php', {
    method: 'POST',
    body: JSON.stringify({ foo: 'bar' })
  });
  // do stuff with someOtherResult
};
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

First create your login page, then create your username and password field. And put this code after the JQuery library.

$(document).ready(function(){
      $('#login').click(function(){

                    var usernameAdmin = document.getElementById("username").value;
                    var password = document.getElementById("password").value;
                    var dataString = 'usernameAdmin='+usernameAdmin+'&password='+password;
                    $.ajax({
                        type: "POST",
                        url: "controler/login.php",
                        data: dataString,
                        cache: false,
                        success: function(data)
                        {   
                                document.getElementById("login").disabled = false;  
                                window.location="admin/";

                        } 
                    });

            });
         });

Now create your Ajax file according to the code below and enjoy it

if(isset($_POST['usernameAdmin']))
{
     $username = $_POST['usernameAdmin'];
     $password = $_POST['password'];
     $c = $check->check_login_admin($username,$password);
     if($c == true)
            {
                echo 1;                                 
            }
            else
            {
                echo 0;
            }
}


protected function check_login_admin($username,$password)
    {   
            parent::__construct();      
            $sql = $this->_SELECT." `users` WHERE username=:u AND password=:p";     
            $r = $this->_DB->prepare($sql); 
            $r->bindValue(':u', $u);
            $r->bindValue(':p', $p);            
            $r->execute();
            $c = $r->rowCount();
            if($c == 1)
            {           
                foreach($r->fetchAll() as $row);
                    $_SESSION['log_true_admin']= true;                          
                    $_SESSION['name']= $row['name']." ".$row['family']; 
                    $_SESSION['id']= $row['id'];                                
                    return true;
            }
            else return false;  
    }

good luck my friend