Nexz
Nexz

Reputation: 93

Ajax dependent text field and dropdown menu (Php and Javascript)

I'm a student and still new with Javascript and php, i need to make a login page for my website that can check user input in the database using ajax.

Example: When the user enter their username and password into the field given,the system will automatically check in database either the user exist or not and return the data needed such as user responsibilty from the response table to the dropdown menu below, then they can login into the system. Below is my basic coding:

Config.php:

e$host = "localhost";
$User = "root"
$Pass = "passw";
$db = "skm_spm";

Login.php:

<?
require ("config.php");

$conn=mysqli_connect($host,$user,$pass,$db);

   $duser="select * from tab_user where user_name = '".$_POST["Lname"]."'";
   $uresult=myqli_query($conn,$duser);

       if(!$uresult)
                  die("Invalid query: ".mysqli_error());
            else 
                if(mysqli_num_rows($uresult)== 0){
                    echo "User does not exist";
                    }
                    else
                    {
                    $row=mysqli_fetch_array($result,MYSQL_BOTH);
                    if($row["User_Password"] == $_POST["Lpass"])
                        {
                            $dresp="select resp_id,resp_name from tab_resp";
                            $result2 = mysqli_query($conn,$dresp);

                        }
                    else
                    {
                    }
                }
?>

      <html>
      <b>Login</b><br>
      Name : <input type = "text" name="Lname" id="Lname" placeholder="Username"/><br>
      Password: <input type = "password" name="Lpass" id="Lpass" placeholder="password"/><br><br>
        <div class = "optresp">
              <select name="sresp" id="sresp">
                   <option>--Responsibility--</option>
                       <?
                        while (mysqli_fetch_array($result2)){
                        echo "<option  value='$row[1]'>$row[1]</option>";
                       ?>
              </select>
        </div>
      </html>

I have learn on internet and try to code with my understanding,but still failed. I need a php ajax coding that can work with code above. Thank you.

Upvotes: 1

Views: 630

Answers (2)

Nitish Jha
Nitish Jha

Reputation: 1

You need to make ajax call on blur of username to check if user exists in database and on success of that you can make one more ajax to check for password match of that particular user. This will give you both cases whether a user exixts or not if exixts then does the password match or not only after that user will be logged in and then you can show the responsibilities of that particular user.

For username:

$('#Lname').blur(function(){

$.ajax({
 url:'url where query for matching username from database',
 data:'username collected from input on blur',
 type:'POST',
 success:function(data){
  //Code to execute do on successful of ajax
 }
 })
})

For Password:

The ajax call remains the same only url, data and response changes

Upvotes: 0

Thomas Smyth
Thomas Smyth

Reputation: 522

I will provide you with some code from my recent project and hopefully you will be able to understand it and adapt it to your needs.

Firstly, you should have the login form in a separate file to the PHP login code. Then have button on the page or an enter events that run a Javascript function, in my case Login(). In this Javascript function the text within the input fields are saved to two variables and some basic checks are done on them to ensure that they have been filled in. Next, the PHP login function file (it has no visible content in just processes some data in PHP) using the $.post line. This also passed the two input variables (under the same name) to the PHP file. You can also see that depending on what is returned/echoed from the PHP file as "data" several possible outcomes may occur (Login Success, Account Banned or Invalid Login). I personally call these outcomes error messages or success messages, for example error message 6 for incorrect password/username.

//FUNCTIONS
function Login(){
    var StrUsername = $("#txtUsername" ).val();
    var StrPassword = $("#txtPassword").val();
    if (StrUsername == "" && StrPassword == ""){
        $('#pError').text('Enter your Username and Password!');
    }
    else if(StrUsername == ""){
        $('#pError').text('Enter your Username!');
    }
    else if(StrPassword == ""){
        $('#pError').text('Enter your Password!');
    }
    else{
        $.post('https://thomas-smyth.co.uk/functions/php/fnclogin.php', {StrUsername: StrUsername, StrPassword: StrPassword}, function(data) {
            if (data == 0){
                window.location.href = "https://thomas-smyth.co.uk/home";
            }
            else if (data == 1){
                window.location.href = "https://thomas-smyth.co.uk/banned";
            }
            else if (data == 6){
                $('#pError').text('Username & Password combination does not exist!');
            }
        });
    }
}

Next the PHP function file. Firstly, the variables passed by the Javascript are collected using $_POST. My SQL class is then pulled into the file, this does all my SQL DB connections. I then have my SQL statement that will search to see if the account exists. Notice the ? in it. This prevents SQL injections as the variables is bound into the statement through the SQL server meaning it won't allow people to put SQL code within my input fields to break my database. I then check whether the account exists, if it doesn't I save data to 6, which will cause the error message 6 in the Javascript to run when data is returned. I have a field in my database that contains a rank. If the login is correct then I create a SESSION variable to store their username and rank in. This is later used on pages to check whether they are logged in before displaying a page (this speeds up navigation as it means that the DB doesn't need to be searched everytime the user switches page, however does bring some issues like if you ban a user while they are logged in they will stay logged in until their session dies). You could use this on your dropdown menu to ensure the user is logged in and/or get their username. Finally, I return 0 or 1, so that the Javascript then re-directs them to the correct page.

<?php
//Retrieves variables from Javascript.
$StrUsername = $_POST["StrUsername"];
$StrPassword = $_POST["StrPassword"];

require "sqlclass.php";
$TF = new TF_Core ();

    $StrQuery = "
    SELECT Username, Rank FROM tblUsers 
    WHERE Username = ? AND Password = ?";

if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
    $statement->bind_param('ss',$StrUsername,$StrPassword);
    $statement->execute ();
    $results = $statement->get_result ();

    if($results->num_rows == 0){
        $data = 6;
    }
    else {

        while ($row = $results->fetch_assoc()) {
            //Other groups
            if ($row["Rank"] == "Developer" || $row["Rank"] == "Staff" || $row["Rank"] == "Cadet"){
                session_start();
                $_SESSION["LoginDetails"] = array($StrUsername, $row["Rank"]);
                $data = 0;
            }
            //Banned
            else if ($row["Rank"] == "Banned"){
                session_start();
                $_SESSION["LoginDetails"] = array($StrUsername, "Banned");
                $data = 1;
            }
        }
    }
}

echo $data;
?>

Hopefully this helps you. Please say if you need more help!

Upvotes: 2

Related Questions