So I was learning ajax and followed some codes I found online but didn't know how to pass the value from the PHP.
so this is my email.php
$conn = mysqli_connect($servername, $username, $password, $db);
$email=$_POST['email'];
$query = "SELECT * FROM registration WHERE email = '$email'";
$result = mysqli_query($conn,$query);
$count = mysqli_num_rows($result);
if($count==0){
echo json_encode(0);
}
else{
echo json_encode(1);
}
mysqli_close($conn);
and this is my ajax
$.ajax({
url: "email",
type: "POST",
data: {
email: email,
},
cache: false,
success: function(data) {
alert("data: " data); //i tried this one to check what is in data but it's not the values from the echo in PHP
if (data == 0) {
$('#message').html('available');
} else if (data == 1) {
$('#message').html('not available');
}
}
});
Your help would be much appreciated! Thank you!
[!] EDIT [!]
sorry my problem was different. i have a template.php
file for the whole HTML and where all my PHP files are included. here is the part:
if(isset($_GET["route"])){
if ($_GET["route"] == 'home' ||
$_GET["route"] == 'email' ||)
{
include "modules/".$_GET["route"].".php";
}
now the value in alert(data)
is the whole thing in the template.php
and the 0
or 1
at the end. what I did to solve this problem is: data.slice(-1)
lol not a good practice tho. so if u have other solutions, I would really appreciate it. thank you!
CodePudding user response:
You don't have to encode the number. Just pass the number as a string to the echo statement.
$conn = mysqli_connect($servername, $username, $password, $db);
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query = "SELECT * FROM registration WHERE email = '$email'";
$result = mysqli_query($conn,$query);
$count = mysqli_num_rows($result);
if($count==0){
echo "0";
} else{
echo "1";
}
mysqli_close($conn);
} else {
echo "1";
}
CodePudding user response:
You have to make changes to the php file
$data = json_encode(0);
Then return the encoded data in your php file like this
return $data;
So whenever you make a request to the file it will have a return type that can be accessed in ajax.