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
Is there any way to fix it? Thanks everyone!
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.' );
}
?>
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);
}
})
}
})
})