2

I have a php file for comparing the inserted data in input element of HTML. then, if I click the button, I want to trigger it by JavaScript.

I have a sample code with php, if I used this in html file, this works perfectly fine, but then I have no idea on how to use this in JavaScript.

<?php
    include("php_functions/config.php");
    session_start();

    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 user_id  FROM user WHERE username = '$myusername' and password = '$mypassword'";
        $result = mysqli_query($db,$sql);
        $rows = mysqli_fetch_array($result);

        $count = mysqli_num_rows($result);

        // If result matched $myusername and $mypassword, table row must be 1 row
        if($count == 1) {
            $_SESSION['login_user'] = $myusername; 
            header("location: .php");
        } else {
            echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>',
            echo '<script type="text/javascript">',
            echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");',
            echo '}, 100);</script>';
        }
    }
?>

HTML:

<form action="" method="POST" id="index-login">
    <div class="form-group mb-lg">
        <label>Username</label>
        <div class="input-group input-group-icon">
            <input
                name="username"
                type="text"
                class="form-control input-lg"
                id="username"
            />
            <span class="input-group-addon">
                <span class="icon icon-lg">
                    <i class="fa fa-user"></i>
                </span>
            </span>
        </div>
    </div>

    <div class="form-group mb-lg">
        <div class="clearfix">
            <label class="pull-left">Password</label>
            <a href="#" class="pull-right">Lost Password?</a>
        </div>
        <div class="input-group input-group-icon">
            <input
                name="pwd"
                type="password"
                class="form-control input-lg"
                id="password"
            />
            <span class="input-group-addon">
                <span class="icon icon-lg">
                    <i class="fa fa-lock"></i>
                </span>
            </span>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-8">
            <div class="checkbox-custom checkbox-default">
                <input id="RememberMe" name="rememberme" type="checkbox" />
                <label for="RememberMe">Remember Me</label>
            </div>
        </div>
        <div class="col-sm-4 text-right">
            <button type="submit" class="btn btn-primary hidden-xs" id="signin">
                Sign In
            </button>
            <button
                type="submit"
                class="btn btn-primary btn-block btn-lg visible-xs mt-lg"
                id="signin1"
            >
                Sign In
            </button>
        </div>
    </div>

    <p class="text-center">
        Don't have an account yet? <a href="#">Sign Up!</a>
    </p>
</form>
4
  • so you want to compare username and password? Commented Mar 19, 2019 at 2:48
  • lots of dad ideas here, IE: dont sure plain text passwords .. but what does "use this in javascript" even mean here? Commented Mar 19, 2019 at 2:52
  • @tim, i want to get the value of the element in html using javascript sir, then the variable catch the element value will be sent in php variable. is that even possible sir? Commented Mar 19, 2019 at 2:56
  • Possible duplicate of Login form validation using javascript and php Commented Mar 19, 2019 at 3:03

2 Answers 2

1

First your code has alot of flops.

1.) You are saving password as plaintext, you will need to hash your password using php default password hashing mechanism.

2.) Your code is vulnerable to session Fixation attack. You can mitigate that using session regenerate_id as below

session_regenerate_id();

I will add it at your php script

3.) Session hijacking can only be prevented by ensuring that your site runs under https and not just http

4.) You are passing session username without sing htmlentities or htmlspecialchars functions. Remember to do that when displaying session username on welcomepage.php

To answer your question, You can do that with Jquery/Ajax.

In the code below, am submitting your form using signin id attributes as can be seen in the jquery/ajax code below.

The code below displays all the actions triggered by the ajax/jquerycode

<div id="loader"></div>
<div id="result"></div>

Remember to include jquery.min.js files to ensure that it works

so here is your login.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(document).ready(function(){


        $('#signin').click(function(){


    var username = $('#username').val();
    var password = $('#password').val();


            if(username==""){

                alert('please Enter username');


            }

     else if(password==""){

                alert('please Enter password');


            }

    else{

    $('#loader').fadeIn(400).html('<span>Please Wait, User is being logged</span>');

    var datasend = "username="+ username + "&password=" + password;

            $.ajax({

                type:'POST',
                url:'login.php',
                data:datasend,
                            crossDomain: true,
                cache:false,
                success:function(msg){

                    //empty username and password box after submission
                    $('#username').val('');
                    $('#password').val('');

                    $('#loader').hide();
                    $('#result').fadeIn('slow').prepend(msg);


                }

            });

            }

        })

    });


    </script>




<form action="" method="POST">
    <div class="form-group mb-lg">
        <label>Username</label>
        <div class="input-group input-group-icon">
            <input
                name="username"
                type="text"
                class="form-control input-lg"
                id="username"
            />
            <span class="input-group-addon">
                <span class="icon icon-lg">
                    <i class="fa fa-user"></i>
                </span>
            </span>
        </div>
    </div>

    <div class="form-group mb-lg">
        <div class="clearfix">
            <label class="pull-left">Password</label>
            <a href="#" class="pull-right">Lost Password?</a>
        </div>
        <div class="input-group input-group-icon">
            <input
                name="pwd"
                type="password"
                class="form-control input-lg"
                id="password"
            />
            <span class="input-group-addon">
                <span class="icon icon-lg">
                    <i class="fa fa-lock"></i>
                </span>
            </span>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-8">
            <div class="checkbox-custom checkbox-default">
                <input id="RememberMe" name="rememberme" type="checkbox" />
                <label for="RememberMe">Remember Me</label>
            </div>
        </div>
        <div class="col-sm-4 text-right">

<div id="loader"></div>
<div id="result"></div>
<div id="fadeoutResult"></div>

            <button type="submit" class="btn btn-primary hidden-xs" id="signin">
                Sign In
            </button>
            <button
                type="submit"
                class="btn btn-primary btn-block btn-lg visible-xs mt-lg"
                id="signin1"
            >
                Sign In
            </button>
        </div>
    </div>

    <p class="text-center">
        Don't have an account yet? <a href="#">Sign Up!</a>
    </p>
</form>

login.php

<?php
    include("php_functions/config.php");
    session_start();

    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 user_id  FROM user WHERE username = '$myusername' and password = '$mypassword'";
        $result = mysqli_query($db,$sql);
        $rows = mysqli_fetch_array($result);

        $count = mysqli_num_rows($result);

        // If result matched $myusername and $mypassword, table row must be 1 row
        if($count == 1) {

//prevent session fixation attack
session_regenerate_id();

            $_SESSION['login_user'] = $myusername; 
            header("location: .php");
        } else {
            echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>',
            echo '<script type="text/javascript">',
            echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");',
            echo '}, 100);</script>';
        }
    }
?>

Finally, in case if the form does not get submitted, you can remove just tis two the form elements <form> </form> and it will work

Updated section

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(document).ready(function(){


        $('#signin').click(function(){


    var username = $('#username').val();
    var password = $('#password').val();

            if(username==""){

                alert('please Enter username');


            }

     else if(password==""){

                alert('please Enter password');


            }

    else{

    $('#loader').fadeIn(400).html('<span>Please Wait, User is being logged</span>');

    var datasend = "username="+ username + "&password=" + password;

            $.ajax({

                type:'POST',
                url:'login.php',
                data:datasend,
                            crossDomain: true,
                cache:false,
                success:function(msg){

                    //empty username and password box after submission
                    $('#username').val('');
                    $('#password').val('');

                    $('#loader').hide();
                    $('#result').fadeIn('slow').prepend(msg);
                    $('#fadeoutResult').delay(5000).fadeOut('slow');

                }

            });

            }

        })

    });


    </script>




    <div class="form-group mb-lg">
        <label>Username</label>
        <div class="input-group input-group-icon">
            <input
                name="username"
                type="text"
                class="form-control input-lg"
                id="username"
            />
            <span class="input-group-addon">
                <span class="icon icon-lg">
                    <i class="fa fa-user"></i>
                </span>
            </span>
        </div>
    </div>

    <div class="form-group mb-lg">
        <div class="clearfix">
            <label class="pull-left">Password</label>
            <a href="#" class="pull-right">Lost Password?</a>
        </div>
        <div class="input-group input-group-icon">
            <input
                name="password"
                type="password"
                class="form-control input-lg"
                id="password"
            />
            <span class="input-group-addon">
                <span class="icon icon-lg">
                    <i class="fa fa-lock"></i>
                </span>
            </span>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-8">
            <div class="checkbox-custom checkbox-default">
                <input id="RememberMe" name="rememberme" type="checkbox" />
                <label for="RememberMe">Remember Me</label>
            </div>
        </div>
        <div class="col-sm-4 text-right">

<div id="loader"></div>
<div id="result"></div>
<div id="fadeoutResult"></div>

            <button type="submit" class="btn btn-primary hidden-xs" id="signin">
                Sign In Now
            </button>

            </button>
        </div>
    </div>

    <p class="text-center">
        Don't have an account yet? <a href="#">Sign Up!</a>
    </p>

login.php

<?php

/*
//testing post data....
if($_POST['username'] != '' && $_POST['password'] !='') {

        // username and password sent from form 
       echo $myusername = $_POST['username'];
       echo $mypassword = $_POST['password']; 

}


*/



    include("php_functions/config.php");
    session_start();
if($_POST['username'] != '' && $_POST['password'] !='') {

        // username and password sent from form 
       echo $myusername = mysqli_real_escape_string($db,$_POST['username']);
        echo $mypassword = mysqli_real_escape_string($db,$_POST['password']); 



        //$sql = "SELECT user_id  FROM user WHERE username = '$myusername' and password = '$mypassword'";
        $sql = "SELECT * FROM user WHERE username = '$myusername' and password = '$mypassword'";
        $result = mysqli_query($db,$sql);
        $rows = mysqli_fetch_array($result);

        $count = mysqli_num_rows($result);

        // If result matched $myusername and $mypassword, table row must be 1 row
        if($count == 1) {

//prevent session fixation attack

session_regenerate_id();

            $_SESSION['login_user'] = $myusername; 
            header("location: welcome.php");
        } else {
            echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>',
            echo '<script type="text/javascript">',
            echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");',
            echo '}, 100);</script>';
        }

    }


?>
Sign up to request clarification or add additional context in comments.

11 Comments

Hi Ma'am, your code works fine. but there is an error that my variables now in php are undefined.
what variable is undefined. give me the full error details
can you remove this line of code if($_SERVER["REQUEST_METHOD"] == "POST") { and replace it with if($_POST['username'] != '' && $_POST['password'] !='') {
You can also try remove form elements open and close <form action="" method="POST" ></form> and see what happens
ahm! Yes Ma'am, I did it earlier, But I have a question about the passed values into php. is it really passed? because, nothing is happening, on the code.
|
0

There are many ways to collect data from a form, in my opinion the most practical is to use FormData. And the way to communicate javascript with php code is to use ajax. Please look at the following example.

HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Document</title>
    </head>
    <body>
        <form action="" method="POST" name="index-login" id="index-login">
            <div class="form-group mb-lg">
                <label>Username</label>
                <div class="input-group input-group-icon">
                    <input
                        name="username"
                        type="text"
                        class="form-control input-lg"
                        id="username"
                    />
                    <span class="input-group-addon">
                        <span class="icon icon-lg">
                            <i class="fa fa-user"></i>
                        </span>
                    </span>
                </div>
            </div>

            <div class="form-group mb-lg">
                <div class="clearfix">
                    <label class="pull-left">Password</label>
                    <a href="#" class="pull-right">Lost Password?</a>
                </div>
                <div class="input-group input-group-icon">
                    <input
                        name="pwd"
                        type="password"
                        class="form-control input-lg"
                        id="password"
                    />
                    <span class="input-group-addon">
                        <span class="icon icon-lg">
                            <i class="fa fa-lock"></i>
                        </span>
                    </span>
                </div>
            </div>

            <div class="row">
                <div class="col-sm-8">
                    <div class="checkbox-custom checkbox-default">
                        <input
                            id="RememberMe"
                            name="rememberme"
                            type="checkbox"
                        />
                        <label for="RememberMe">Remember Me</label>
                    </div>
                </div>
                <div class="col-sm-4 text-right">
                    <button
                        type="submit"
                        class="btn btn-primary hidden-xs"
                        id="signin"
                    >
                        Sign In
                    </button>
                    <button
                        type="submit"
                        class="btn btn-primary btn-block btn-lg visible-xs mt-lg"
                        id="signin1"
                    >
                        Sign In
                    </button>
                </div>
            </div>

            <p class="text-center">
                Don't have an account yet? <a href="#">Sign Up!</a>
            </p>
        </form>

        <script src="app.js"></script>
    </body>
</html>

JavaScript (app.js)

// You can access a form by its name,
// for example if the form had the name 'form' you could access it through
// `const form = document.forms.form`
// in your case by using the same name id value should be accessed thus
const indexLogin = document.forms["index-login"];

indexLogin.addEventListener("submit", handleSubmit);

function handleSubmit(event) {
    // Prevent submit form
    event.preventDefault();

    // Get data from inputs. Here this refer to the current form
    const formData = new FormData(this);

    // Inspect data collected
    // for (const [key, value] of formData.entries()) {
    //     console.log(key, value);
    // }

    // Send form to php file
    fetch("file.php", {
        method: "POST",
        body: formData
    })
        .then(response => response.json())
        .then(json => {
            // do something
        })
        .catch(error => console.error(error.message));
}

But, your data will be visible through devtool in the network panel. I guess that will require another question.

I hope I have interpreted your question properly.

1 Comment

Hi! Your solution returns this login.js:87 Unexpected token < in JSON at position 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.