-2

I am learning how to use ajax to check if registered email data already exists in the system. But when used, the result returned from success:function(data) is always the source code of the original php page (as shown in the image below). Here is my javascript code

    $(document).ready(function(){
    $("#email").change(function(){
        $.ajax({
            URL: "process-email.php",
            type: "post",
            data: {email:$(this).val()},
            success:function(res) {
                console.log(res);
            }
        })
    })
})

This is the destination for data processing

<?php
    include "config/config.php";
    $result = mysqli_query($conn,"SELECT * FROM tb_user WHERE email='" . $_POST['email'] . "'");
    if(mysqli_num_rows($result) <= 0)
    {
        echo "OK.";
    }else{
        echo "Already exist.";
    }
?>

And here is the data sent to my main site

enter image description here

Is there any way to fix it? Thanks everyone!

Duy Dai
  • 7
  • 4
  • 3
    Your code is wide open to [SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection) attack due to the use of raw user supplied data being used directly in the sql. To help mitigate this threat you should always use [Prepared Statements](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php). A really useful guide, with plenty of example code is [PHP Delusions](https://phpdelusions.net/) – Professor Abronsius Dec 31 '21 at 07:40
  • Yes but i'm just trying to see how ajax works. I'm still struggling with this error – Duy Dai Dec 31 '21 at 07:42
  • Are you sending the ajax request to the same page? – Professor Abronsius Dec 31 '21 at 07:44
  • I have moved the ajax request to the same page and I have looked carefully. But it still error – Duy Dai Dec 31 '21 at 07:46
  • "PHP AJAX" is a confusing term, AJAX is a browser technology. – Teemu Dec 31 '21 at 07:46
  • It can be source of the html page of 404 or something else that determines an error page, beside that, when you implement ajax u should "return" your desired result not echo it . Debug your code to figuring out where is your bug. – behzad m salehi Dec 31 '21 at 07:47
  • 1
    If the javascript that sends the ajax is within the same page as the PHP that processes the HTTP request then you need to flush the buffers before sending output otherwise the response will include all the HTML from that page which is what seems to be happening – Professor Abronsius Dec 31 '21 at 07:49
  • @behzadmsalehi What do you mean with "return the result"? The response is what PHP collects to the output buffer, it doesn't matter how the buffer is populated. – Teemu Dec 31 '21 at 07:50
  • I have split 2 php files to process – Duy Dai Dec 31 '21 at 07:50
  • @DuyDai Your code is not only insecure, it's broken. You need to use parameterized queries so that reserved characters such as quote marks don't just outright break the query. How do you know your problem isn't caused by this? It's actually *easier* and *faster* to do it the right way... you should. Whomever told you to concatenate/interpolate data into a query like this has no idea what they're doing, and their advice should not be trusted. – Brad Dec 31 '21 at 07:55
  • @DuyDai There is not enough information in this question to solve your problem. Who knows where this HTML is coming from... usually it's because it's your error page, but you only showed us the headers. – Brad Dec 31 '21 at 07:59

1 Answers1

1

It is still unclear to me whether the AJAX request is being sent to the same page but regardless the following might be of help as it does address a couple of points - namely the sql injection possibility, the flushing of buffers to ensure that only the correctly crafted response is sent and also that there no request is sent unless there is a valid email.

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['email'] ) ){
    
        # flush any previous content
        ob_clean();
        
        include "config/config.php";
        
        /*
            Create a Prepared Statement
            Bind the placeholder to the POSTed email & execute.
            Obtain the number of rows returned & close statement.
        */
        $sql='SELECT * FROM tb_user WHERE email=?';
        $stmt=$conn->prepare( $sql );
        $stmt->bind_param('s',$_POST['email']);
        $stmt->execute();       
        $stmt->store_result();
        
        $rows=$stmt->num_rows;
        
        $stmt->free_result();
        $stmt->close();
        
        
        # terminate with response message
        exit( $rows == 0 ? 'OK.' : 'Already exists.' );

    }
?>

Email validation function

const validateEmail=( email )=>{
  return String( email )
    .toLowerCase()
    .match(
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    );
};



$(document).ready(function(){
    $("#email").change(function(){
        let email=$(this).val();
        if( validateEmail( email ) ){
            /*
                No point sending the ajax request 
                unless the email is valid.
            */
            $.ajax({
                URL: "process-email.php",
                type: "post",
                data:{ 'email':email },
                success:function(res) {
                    console.log(res);
                }
            })
        }
    })
})
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46