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.

Jacob Johnson
  • 551
  • 1
  • 6
  • 20
  • 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. – Sajib Acharya Oct 24 '15 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. – Spudley Oct 24 '15 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 : http://stackoverflow.com/questions/5046930/jquery-send-string-as-post-parameters – Sajib Acharya Oct 24 '15 at 22:25
  • So essentially I need to add a `data: { 'email':'email' },` to my `$.ajax` function? – Jacob Johnson Oct 24 '15 at 22:28
  • On a side note, you should really escape the data from that post request. – Rivers Oct 24 '15 at 23:05
  • Unrelated to code working: your label for email has `for="username"`. Is that right? –  Oct 25 '15 at 01:15
  • To test if it is actually finding it the email or not: var_dump the query, and than run just the query in phpmyadmin or a sql shell. Var_dump like so: `var_dump("SELECT * FROM users WHERE email = '$_POST[email]'");` take result of that and run it to see what you get –  Oct 25 '15 at 01:25

3 Answers3

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.

Nur Bar
  • 731
  • 2
  • 8
  • 16
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();
?>
TipuZaynSultan
  • 783
  • 4
  • 16
  • This change doesn't seem to run the PHP function anymore. I simply get a page refresh. – Jacob Johnson Oct 24 '15 at 22:21
  • 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. – TipuZaynSultan Oct 25 '15 at 06:33
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.

Community
  • 1
  • 1
Sajib Acharya
  • 1,666
  • 5
  • 29
  • 54
  • 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. – Jacob Johnson Oct 24 '15 at 23:25