1

I am trying to check if the username exists in my mysql database and if it does, php side does that check and echo backs "duplicate" which should then be recieved by ajax. However it is not recieving and when I try to do output on my developer tools, i get that front end value as undefined.

Here is my jquery ajax part:-

$("#create").click(function(e){


    e.preventDefault();
   $.ajax({
        type:'post',
        url:'usernameTest.php',
        data: {usr: $("#usr").val(),
            pwd: CryptoJS.MD5($("#pwd").val()).toString()
        },
        success: function(data){
            //console.log(data);
            if(data == "duplicate"){
                $("#userErrorDiv").html("User already exists. Please enter another one").css("color","red");
                console.log("duplicate data");
            }
            else{
                console.log("data not duplicate:"+data);
            }
        },
        error(err){
        console.log("error "+err);
        }
    });

Here is the php part:-

<?php

   function recieveFormData()
   {
     if (isset($_POST['usr'], $_POST['pwd'])) {
        global $connection;
        global $username;
        global $password;
        $username = $_POST['usr'];
        $password = $_POST['pwd'];

    }
  }

    /*do insertion if username not found */
    function insertIntoTable($username, $password){
        global $connection;
        $query="INSERT INTO users(username, password) VALUES('$username','$password')";
        $result=mysqli_query($connection,$query);

        if(!$result){
            die("Sorry. Query failed to execute ".mysqli_error());
        }

    }

    function connectToDatabase(){
        global $connection,$username;
        $connection=mysqli_connect("localhost","root","","usermanagement");
        if(!$connection){
            echo "Sorry! Cannot connect to the database";
        }
    }

    function readFromDatabase(){
        global $connection,$username;
        $query="SELECT * from users where username='$username'";

        $result=mysqli_query($connection,$query);
        if(!$result){
            die("query error");
        }
        if(mysqli_num_rows($result)!=0) {
            echo "duplicate";
            //return false;
        }
        else{
        while($row = mysqli_fetch_assoc($result)) {
           $usernameFromTable=$row['username'];
          // print_r($usernameFromTable);
           echo "<tr><td>".$usernameFromTable."</td><td>User</td><td></td></tr>";
        }
        }
        //return true;
    }

 recieveFormData();
 connectToDatabase();
 readFromDatabase();

 ?>

And this is the simple html im using:-

 <label for="usr">Username</label>
<input type="text" name="usr" id="usr">
<label for="pwd">Password</label>
<input type="password" name="pwd" id="pwd">
<button id="create" class="create" type="submit" name="create">Create</button>
<div id="userErrorDiv"></div>
Rajat Bansal
  • 183
  • 1
  • 14
  • 2
    [Your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements [for PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really not hard](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Nov 04 '15 at 18:52
  • 1
    You really should use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). – Jay Blanchard Nov 04 '15 at 18:54
  • Have you watched the request / response in the browser's console? – Jay Blanchard Nov 04 '15 at 18:54
  • @JayBlanchard : Yes i am able to successfully send username and password to the php and it is able to successfully echo a "duplicate" on the console. However, my front end data value is not catching that – Rajat Bansal Nov 04 '15 at 18:59
  • If it echos `duplicate` on the console then it will be in `data` unless you have other errors. – Jay Blanchard Nov 04 '15 at 19:01
  • Does your console log "duplicate" only? If so, try trimming the received data before comparing/evaluating it: `data = $.trim(data);`. Looks like it is doing nothing, but it actually does. – Justas Nov 04 '15 at 19:01
  • Why would renaming the variable help @entiendoNull? – Jay Blanchard Nov 04 '15 at 19:02
  • If i am removing the code from recieveData to connectToDatabase method and not calling recieveData method in that case, I get a response duplicate but in the success function if(data==="duplicate") is not working and it is evaluating the else part. As a result, my console prints "Data not duplicate:" duplicate. Any idea why having different methods is creating a problem and also why the else part is evaluating .? – Rajat Bansal Nov 04 '15 at 19:08
  • Did you trim the response as suggested by @Justas? – Jay Blanchard Nov 04 '15 at 19:10
  • 1
    Yesss it worked! it was trim method i needed and i wasnt aware of it. Still a newbie thats why. And thank you Jay for your suggestion regarding sql injection attacks. I will surely add that once i am done with all the basic part of the application. and thank you Justas for suggesting the trim method. One of you could add it as an answer. Many many thanks – Rajat Bansal Nov 04 '15 at 19:13

1 Answers1

1

To make the answer more visible, I add it here.

If after receiving response from Ajax request, console logs your echoed string and comparing it with itself does not work, use $.trim():

......
// Ajax execution
......
.success(function(response) {
    response = $.trim(response);
    if (response == 'expected response') {
        // Do stuff....
    }
});
Justas
  • 519
  • 8
  • 18