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>
10
  • 2
    Your script is at risk for SQL Injection Attacks. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really not hard. Commented Nov 4, 2015 at 18:52
  • 1
    You really should use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. Commented Nov 4, 2015 at 18:54
  • Have you watched the request / response in the browser's console? Commented Nov 4, 2015 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 Commented Nov 4, 2015 at 18:59
  • 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 Commented Nov 4, 2015 at 19:13

1 Answer 1

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....
    }
});
Sign up to request clarification or add additional context in comments.

Comments

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.