skip to Main Content

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) {
  $data = json_encode(0); 
} else {
  $data= json_encode(1);
}

mysqli_close($conn);

return data;

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 though. so if u have other solutions, I would really appreciate it. thank you!

2

Answers


  1. 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";
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search