简体   繁体   中英

jQuery AJAX check if email exists in database not working

I am trying to use jQuery, AJAX, PHP, and MySQL to check if an email entered into a form already exists in a database. This is my current jQuery code :

$.post('check-email.php', {'suEmail' : $suEmail}, function(data) {
  if(data=='exists') {
    validForm = false;
    $suRememberMeCheckbox.css('top', '70px');
    $suRememberMeText.css('top', '68px');
    $signUpSubmit.css('top', '102px');
    $tosppText.css('top', '115px');
    $suBox.css('height', '405px');
    $suBox.css('top', '36%');
    $errorText.text('The email has been taken.');
    return false;
  };
});

And this is my PHP code:

<?php include("dbconnect.php") ?>
  <?php
    $sql = "SELECT email FROM users WHERE email = " .$_POST['suEmail'];
    $select = mysqli_query($connection, $sql);
    $row = mysqli_fetch_assoc($select);

    if (mysqli_num_rows($row) > 0) {
      echo "exists";
    }
?>

When I go through with the sign up form, when I use an email already in the database, the error text never changes to what I specified, but instead to some other error cases I have coded. Why is this not working! Thanks so much!

    Use This Code: Working Perfectly:    

    <?php 
        include("dbconnect.php");

            $sql = "SELECT email FROM users WHERE email = '" .$_POST['suEmail']."' ";
            $select = mysqli_query($connection, $sql);
            $row = mysqli_fetch_assoc($select);

            if (mysqli_num_rows($select) > 0) {
              echo "exists";
            }
?>

If its not changing that means you might have a error with your query. Check developer options on your browser under network. There you can see all ajax calls being made. Click on look at the response. Check to see if there was an error with your query.

Also you have to validate the form submission. Something like.

if($_SERVER['REQUEST_METHOD'] = 'POST')
{

//maybe send a token over with the form to prevent form spoofing 

 if($_POST['token'] === $_SESSION['token'])
 {
    // all your code goes in here
    // you provably want to check that is a real email also
      // check email input against regular expression

        if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
        {
            //if valid email to variable and escape data
            $e = sanitizeString($_POST['email']);
        }else 
            {
                /// if not a real email to errors array
                $reg_errors['email'] = 'Please enter a valid email address!';
            }

 }
}

You have to use prepare statements in your queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM