0

I have a PHP script which is supposed to check my database where the user email that is input exists. I've got everything set up so that the script runs when the form is submitted but I think there must be something wrong with how my form is set up. It doesn't seem to recognize that a row exists. I've put in an email address I know for a fact exists; however, it doesn't seem to find it.

app.js

$(document).ready(function() {
    $("submit").click(function() {
        alert("This was a test.");
        $.ajax({
            type: "POST",
            url: "main_login.php",
            success: function(data) {
                alert(data);
                $(".message").text(data);
            }
        });
    });
});

main_login.php

<?php
    $conn = new mysqli('localhost', 'user', 'pass!', 'db');
    mysqli_set_charset($conn, 'utf8mb4');
    $check = "SELECT * FROM users WHERE email = '$_POST[email]'";
    $results = mysqli_query($conn, $check);
    $data = mysqli_fetch_array($results, MYSQLI_NUM);
    if($data == 1) {
        echo "Login successful";
    } else {
        echo "This account does not exist";
    }

    $conn->close();
?>

login.php

<div class="container login">
    <div class="panel panel-default login-panel">
        <div class="panel-heading">span class="log-h1">Sign-in</span>
        </div>
        <div class="panel-body">
            <form name="loginform" action="login.php" method="post">
            <div class="form-group">
                <label for="username">Email</label>
                <input type="email" class="form-control"
                 name="email" id="email" placeholder="Email address">
            </div>
            <div class="form-group" style="float: right;">
                <input type="submit" class="btn btn-primary" name="Submit" 
                 value="Sign-in">
            </div>
            </form>
            <span class='message'></span>
        </div>
    </div>
</div>

Again, everything works except for the verification that the email address I provided exists. I doesn't think it does no matter what I do.

7
  • you should first check whether the data you are sending to main_login.php from app.js is getting received or not. use the isset($_POST['email']) method. Commented Oct 24, 2015 at 22:19
  • 2
    Never ever pass a raw $_POST variable directly into a SQL string like that. Any input that includes a quote character will crash your program, and it makes it very easy for a hacker to do pretty much anything he wants to your database. Learn about parameterised queries using mysqli_prepare() to make your queries secure. Commented Oct 24, 2015 at 22:21
  • That said, you are not sending any data from your app.js. That is the reason your code is returning "account does not exist". take a look here : stackoverflow.com/questions/5046930/… Commented Oct 24, 2015 at 22:25
  • So essentially I need to add a data: { 'email':'email' }, to my $.ajax function? Commented Oct 24, 2015 at 22:28
  • On a side note, you should really escape the data from that post request. Commented Oct 24, 2015 at 23:05

3 Answers 3

1

try changing this

$check = "SELECT * FROM users WHERE email = '$_POST[email]'";

to

$check = "SELECT * FROM users WHERE email = '" . $_POST['email'] . "'";

also you want to change the if - fetch_row returns either null or an array (http://php.net/manual/en/mysqli-result.fetch-array.php) so what you want to do is if($data) instead of if($data == 1) as it never returns 1.

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

2 Comments

I still receieve the 'This account does not exist' note saying it wasn't found in the if statement.
Unfortunately, changing to if($data) brings the same results. I think there must be something wrong with my PHP and HTML check?
1

Modify your app.js

$(document).ready(function() {
    $("submit").click(function() {
        alert("This was a test.");
        var email = $("#email").val(); // This line...
        $.ajax({
            type: "POST",
            url: "main_login.php",
            data: {email : email}, // This line..
            success: function(data) {
                alert(data);
                $(".message").text(data);
            }
        });
    });
});

Modify your php:

<?php
    $conn = new mysqli('localhost', 'user', 'pass!', 'db');
    mysqli_set_charset($conn, 'utf8mb4');
    $check = "SELECT * FROM users WHERE email = '". $_POST['email'] ."'";
    $results = mysqli_query($conn, $check);
    $data = mysqli_fetch_array($results, MYSQLI_NUM);
    if($data == 1) {
        echo "Login successful";
    } else {
        echo "This account does not exist";
    }

    $conn->close();
?>

2 Comments

This change doesn't seem to run the PHP function anymore. I simply get a page refresh.
Yes you will but that's the way you set up your code... If you want to be notified if the email exists in the database then if it is then do some stuff and if it's not then do other stuff then you have to change the way this entire thing works... Ajax is asynchronous so js won't wait for it's response and submit the form.
0

There are a few things you need to change. You can have a look here and here

The main problem lies in your app.js

/* attach a submit handler to the form */
$("#formID").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get some values from elements on the page: */
  var $form = $( this ),
      url = $form.attr( 'action' );

  /* Send the data using post */
  var posting = $.post( url, { name: $('#emailID').val() } );

  /* Alerts the results */
  posting.done(function( data ) {
    alert('success');
  });
});

This is a better way of doing it where formIDis the id for your form and emailID is the id for your email input which you have to put into your html.

But a more simple way is not using a form, instead simple buttons and input fields with ids and then using

$("#buttonID").click(function() {
    var postData = $('#emailID').val();
    $.ajax({
        type: "POST",
        data : {'pd' : postData},
        url: "main_login.php",
        success: function(data) {
            alert(data);
            $(".message").text(data);
        }
    });

here emailID is the ID for the email input field and the buttonID if the ID for the button. Also, do include the jquery script into your html. Check for $_POST['pd'] in your php file.

your html can be as simple as

<input type="email" id="emailID"/>
<button id="buttonID">Click</button>

Note that your code has various security concerns.

EDIT:

main_login.php

<?php
   $conn = new mysqli('localhost', 'user', 'pass!', 'db');
   mysqli_set_charset($conn, 'utf8mb4');
   if(isset($_POST['pd'] && !empty($_POST['pd'])) {
          $check = "SELECT * FROM users WHERE email =" . $_POST[email];
          $results = mysqli_query($conn, $check);
          $data = mysqli_fetch_array($results, MYSQLI_NUM);
          $conn->close();
          if($data == 1) {
              echo "Login successful";
          } else {
              echo "This account does not exist";
          }
    }
    else { echo 'postdata not received'; }      
 ?>

Note that I have closed the db connection before sending the AJAX resopnse. Try keeping the response as the last line of the code while using AJAX as I have faced many problems in different situations if I keep some other code after AJAX response. But this is something you can ignore too if things work normal for you. Also do post the error you are getting while running the code.

1 Comment

Thank you so much for the detailed response. I have changed what you have posted along with a few other modifications; however, my page simply crashes now when I hit the submit button. I feel like there must be some error in my main_login.php causing this error.

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.