0

I have a form that requires 'authorization' - where the user needs to enter one of the authorization codes stored in a database to be able to submit the form (basically a password). I'm trying to use AJAX with PHP to both display (using Bootstrap's feedback glyphicons) a tick or cross depending on whether or not the user entered a valid value and allow or prevent form submission. If the user did not enter a valid value, form submission is prevented.

My code below currently isn't working, any help would be greatly appreciated.

HTML:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.min.js"></script>

<form name="auth_form" id="auth_form" method="post" action="action.php">
    <p>Please enter authorisation code.</p>

    <div class="form-group has-feedback" name="auth_code" id="auth_code">

        <input class="form-control" id="auth_code_input" autocomplete="new-password" name="auth_code_input" type="password" required>
        <span class="form-control-feedback glyphicon" id="statusIcon"></span>

    </div>
    <button class="btn btn-success btn-ok" name="Submit" id="submit" type="Submit">Submit</button>
</form>

JS:

<script>

    $(document).ready(function() {

        // Validate on blur and display 'cross' icon in span if invalid, tick if valid
        $('#auth_code_input').blur(function() {
            if (!ValidateInput()) {
                e.preventDefault();
            }
        });

        // Validate on submit and prevent form submission if invalid
        $('#auth_form').on('submit', function(e) {
            if (!ValidateInput()) {
                e.preventDefault();
            }
        })
    });


    // AJAX to check the auth-code server-side

    function ValidateInput() {

                var given_code = document.getElementById('auth_code_input').value;

                $.ajax({
                        url: 'checkauth.php',
                        type: 'POST',
                        data: given_code
                    });

                .done(function(response) {

                            var response = valid;

                            if valid = '1' {

                                $('#statusIcon').removeClass('glyphicon-remove').addClass('glyphicon-ok');
                                IsValid = true;

                            } else {

                                $('#statusIcon').removeClass('glyphicon-ok').addClass('glyphicon-remove');
                                IsValid = false;
                            }

                        }

                .fail(function() {
                            IsValid = false;
                            $('#auth_code_input').val('Something went wrong, please try again.');
                });

            return IsValid;

        });

</script>

checkauth.php

<?php

error_reporting(E_ALL);
ini_set( 'display_errors', 1);

$given_code = $_REQUEST['given_code'];

include 'pdo_config.php';

$valid = '0';

try {

    $conn = new PDO($dsn, $user, $pass, $opt);

    $stmt = $conn->prepare("SELECT instructor_id, auth_code FROM tbl_instructors WHERE auth_code = :given_code;");
    $stmt->bindParam(':given_code', $given_code);
    $stmt->execute();

    $row = $stmt->fetchColumn();

    if ($row == 1) { // row equals one, means auth-code corresponds to an instructor and is valid

        $valid = '1';

    } else {

        $valid = '0';

    }

    echo valid;

}
catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
m87
  • 4,445
  • 3
  • 16
  • 31
sinesine
  • 183
  • 1
  • 11
  • 1
    "isn't working" *how*? In what way is this failing? Describe the problem. – David Aug 03 '17 at 13:33
  • Can you please share the error that occur under Console or on document. I think you forgot to pass parathesis() in If condition under ValidInput function. Change into if(valid){ } – Sachin Kumar Aug 03 '17 at 13:36
  • @David It's not producing any results or changes and I can't identify why. – sinesine Aug 03 '17 at 13:36
  • 2
    AJAX is executed asynchronously, so `IsValid` will be returned before you get the response from PHP. – Prerak Sola Aug 03 '17 at 13:36
  • @sachin kumar Console states unexpected token `.` on the line `.done(function(response) {` – sinesine Aug 03 '17 at 13:38
  • @sinesine: Then this sounds like a good opportunity to familiarize yourself with debugging. Client-side, you can use your browser's debugging tools to place breakpoints in the code and step through the client-side code as it executes. You can observe the runtime values and behavior. Does the code do what you expect it to do? Where does it deviate? Is the AJAX request made? What is the server's response? Is it the response you expected? Debug and narrow down the problem. – David Aug 03 '17 at 13:38
  • Ohh remove ; before .done and check – Sachin Kumar Aug 03 '17 at 13:39
  • @sachin kumar Console now states that line 60, if valid = `'1' { is an unexpected identifier.` – sinesine Aug 03 '17 at 13:40
  • @David Thanks, I'll have a go at breaking it down. Just thought that someone may have been able to point out something I'm clearly missing. – sinesine Aug 03 '17 at 13:41
  • @Prerak Sola How can I solve this? – sinesine Aug 03 '17 at 13:42
  • @sinesine: To be honest, you're missing a number of things. The JavaScript code has a variety of syntax errors as well as a significant asynchronous bug pointed out in a previous comment above. For the syntax errors, just keep looking at the browser's console and correcting them. For the asynchronous bug, this is answered here: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – David Aug 03 '17 at 13:42
  • Still not adding () in If condition and try to return 1 or 0 without single quotes and check also without single quotes. Or simply you can pass if(valid){} and in checkauth.php simply return true/false. – Sachin Kumar Aug 03 '17 at 13:43
  • Manipulate the form submission in `done` and `fail` callback functions or create another function and call it from `done` or `fail` callback functions. – Prerak Sola Aug 03 '17 at 13:47
  • @sinesine change if valid = '1' to if (valid == '1') – Fakebounce Aug 03 '17 at 14:07

1 Answers1

0

found some errors in your js, function ValidateInput() {, plz update your code from below one.

function ValidateInput() {

                var given_code = document.getElementById('auth_code_input').value;

                $.ajax({
                        url: 'checkauth.php',
                        type: 'POST',
                        data: given_code
                    });

                .done(function(response) {



                            if (response == '1') {
                                $('#statusIcon').removeClass('glyphicon-remove').addClass('glyphicon-ok');
                                IsValid = true;

                            } else {
                                $('#statusIcon').removeClass('glyphicon-ok').addClass('glyphicon-remove');
                                IsValid = false;
                            }

                        }

                .fail(function() {
                            IsValid = false;
                            $('#auth_code_input').val('Something went wrong, please try again.');
                });

            return IsValid;

        });

if it still not work, then plz add async: true in your ajax call like this,

 $.ajax({
        url: 'checkauth.php',
        type: 'POST',
        data: given_code,
        async: true                

    });

It will work definitely