0

I am doing email verification on my website. When user submits the form, it starts ajax post request, which posts the email to PHP which compares it with a datebase.

Than still in the form verification process, I have ajax GET request, which should return from the same PHP file whether the email has already been used. But. Everything works fine when I proceed to the PHP, but GET request is always blank. URL of POST request is EmailDuplication.php but URL of GET is EmailDuplication?_=somerandomnumbers. Might that be the problem? I am not experienced in this, will be glad for any help. Here are the codes

JavaScript

function EmailSendForDupe()
    {
        $.ajax({ url: '/files/EmailDuplication.php',
        type: 'post',
        async: false,
        cache: false,
        timeout: 30000,
        data: {email: email.toString},
        success: function (){
         window.alert("email sent");
         }        
         });
    }

function EmailDuplication()
  {
    $.ajax({ url: '/files/EmailDuplication.php',
         type: 'get',
         async: false,
            cache: false,
            timeout: 30000,
         success: function (callback){
          console.log(callback.length);
          console.log(callback);

                    if (callback.length !== 0){
                        window.alert("Email is already in use");
                        return false;
                    }
                    else {
                        window.alert("Email valid");
                        return true; 
                    }
          }
          });
 }

PHP

<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
try{
   $conn = mysqli_connect($servername, $username,$password,$dbname);

}catch(MySQLi_Sql_Exception $ex){
echo("error in connection");
}
if(isset($_POST)){
    $email = $_POST['email'];
    echo "AHOJ";
    $Emailquery = "SELECT * FROM Members WHERE email='$email' ";
    $Emailresult = mysqli_query($conn,$Emailquery);
    $Emailcount = mysqli_num_rows($Emailresult);
    if($Emailcount == 0) {
}
else {
    echo "User Email is already in use.";   
}

}
?>
Twisty
  • 30,304
  • 2
  • 26
  • 45
klacek139
  • 13
  • 1
  • 4
  • Why aren't you checking for the valid email as part of the POST response? – Diodeus - James MacFarlane Jan 03 '19 at 18:46
  • Welcome to Stack Overflow. First, your PHP Code is vulnerable to SLQ Injection. Would advise addressing that first. The GET request will have extra data but this will not inpact it's usage as long as it's calling `EmailDuplication.php` properly. The extra data just ensures it's not reading from a cached version. Since you're calling the same script, but different verbs, it should be working as expected. – Twisty Jan 03 '19 at 19:04
  • ^^ "SQL" not SLQ, sorry. Please see: http://php.net/manual/en/security.database.sql-injection.php – Twisty Jan 03 '19 at 19:19

3 Answers3

0

Generally you want to use async: true.

Also, you do not want to allow the form submit to actually Happen, as that blows away your whole page (reloads the entire thing, if not navigates to somewhere else entirely). So in fact the blank get you could be seeing could be the form submit blowing away your page.

If you are sending ajax requests, the trigger for those simply needs to be a button with a click handler, not an actual submit (unless in that submit input you do something like "onclick='doMyAjax();return false;'" so that the submit action does not actually occur).

If you are actually uploading a file, which for the purpose you appear to be showing here dear goodness please don't let the client drive that functionality via files on their system, the upload post needs a target to post To, so it does not hit your page. For that, the classic embedding of an iframe is still the way to go. Ugh.

posting to an iframe

I have no idea why Two requests need to be sent to do the job. It should probably be just one POST (assuming the ultimate outcome here is you want to send an email if it is a valid email), and the server checks the email and then does the send if it is valid.

And do not use GET versus POST to distinguish what the server should do (such as verifying an email versus sending one) - the Request itself or the Url, for example include "action=verifyEmail" in your form data being passed up, to tell the server what to do rather than it assuming just because it's a POST.

Hopefully some of this is helpful.

John Fantastico
  • 332
  • 1
  • 7
  • Thanks very much for the comment. Alerts are still blanks if I set return false so I don't get redirected. I am using POST request to post the user email to PHP. PHP checks whether the email is already in database. Than GET request obtains the response and if there is none than it proceeds to registration process. As I said it works if I get over the alerts to the PHP page, but that is not what I am interested in. I need the alerts to show Email is already in use or Email valid if its OK. But I am getting Email valid all the time :( tried what you adviced me but no change. Any ideas? – klacek139 Jan 03 '19 at 19:22
  • Well according to your php code, for one thing if it is not a POST, nothing is done. ("if(isset($_POST)){ ...." ) , and there seems to be an extra } at the end of your php code. – John Fantastico Jan 03 '19 at 19:27
  • The GET cannot obtain the response of the POST. The response comes back In the post response, or it is lost (think of it as, the server does One request and then hangs up on you). – John Fantastico Jan 03 '19 at 19:33
0

First, I would advise cleaning up your PHP and making sure it is not vulnerable to SQL Injection.

<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
$returnData = new array();
$conn = mysqli_connect($servername, $username,$password,$dbname);
if (mysqli_connect_errno()) {
  $returnData['SQL Error'] = "Connect failed: %s\n", mysqli_connect_error();
  header('Content-Type: application/json');
  echo json_encode($returnData);
  exit();
}
if(isset($_POST['email'])){
  // POST
  $email = mysqli_real_escape_string($conn, $_POST['email']);
  $resultData["AHOJ"] = true;
  $Emailquery = "SELECT * FROM Members WHERE email='$email' LIMIT 1;";
  $Emailresult = mysqli_query($conn,$Emailquery);
  $Emailcount = mysqli_num_rows($Emailresult);
  if($Emailcount == 0) {
    $resultData['inUse'] = false;
    $resultData['email'] = $_POST['email'];
  } else {
    $resultData['inUse'] = true; 
  }
} else {
  // GET
  $resultData["AHOJ"] = false;
  $resultData['inUse'] = true;
}
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($returnData);
die();
?>

This will return JSON details back to your jQuery script and can be more helpful than plain text.

I also use mysqli_real_escape_string() to help escape any potential injection attempts. I would advise switching to Prepared statements: http://php.net/manual/en/mysqli-stmt.prepare.php

In your JavaScript, you will want to make a few changes too.

function EmailSendForDupe(email){
  $.ajax({
    url: '/files/EmailDuplication.php',
    type: 'post',
    cache: false,
    timeout: 30000,
    data: {
      email: email.toString()
    },
    dataType: "json",
    success: function (json){
      console.log(json);
      if(json.inUse == false){
        alert("Email Sent to " + json.email);
      } else {
        alert("There may have been an error: " + json.error);
      }
    }        
  });
}

function EmailDuplication(email){
  $.ajax({ url: '/files/EmailDuplication.php',
    type: 'get',
    data: {
      email: email.toString()
    },
    dataType: "json",
    cache: false,
    timeout: 30000,
    success: function (json){
      console.log(json);
      if (json.inUse){
        window.alert("Email is already in use");
      } else {
        window.alert("Email valid");
      }
    }
  });
}

Hope this helps.

Twisty
  • 30,304
  • 2
  • 26
  • 45
0

you are missing to handle GET Request Data.if some try to using get URL then your code don't have any condition to handle it. check modified code.

<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";

try{
   $conn = mysqli_connect($servername, $username,$password,$dbname);

}catch(MySQLi_Sql_Exception $ex){
echo("error in connection");
}

if(isset($_POST)){
    $email = $_POST['email'];
    echo "AHOJ";
    $Emailquery = "SELECT * FROM Members WHERE email='$email' ";
    $Emailresult = mysqli_query($conn,$Emailquery);
    $Emailcount = mysqli_num_rows($Emailresult);
    if($Emailcount == 0) {
    }else {
    echo "User Email is already in use.";   
    }
  }else{
   echo " Get Method Data";
 }
?>

Please try it and give your feedback.