Monday 3 September 2018

Ajax / PHP: call works correctly but does not alert PHP result

I use the below to pass data via Ajax (in jQuery) to a PHP page. The PHP page then inserts them into a MySQL db (if they don't exist already).

Everything works correct but I cannot get back the result that I echo in PHP.
I thought a simple alert would do here in the success function but I am not getting any alerts - neither when an insert is successful nor when I intentionally submit something that already exists.
Can someone please help me with this ?
Ajax:
$.ajax({
    type: "post",
    url: baseURL + "/ajax.php", // baseURL is the main URL, i.e. http://www.myurl.com
    cache: "false",
    data: {
        email: email,
        dob: dob
    },
    success: function(data){
        alert(data);
    },
    error: function(){
    }
});

PHP:
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
    die("Connection failed: " . $conn->connect_error);
}
$email = $_POST["email"];
$dob = $_POST["dob"];
$sql = "SELECT email FROM Users WHERE email = '" . $email . "'";
$query = $conn->query($sql);
if(mysqli_num_rows($query) > 0){
    echo "record already exists";
}else{
    $sql = "INSERT INTO Users (email, dob) VALUES ('" . $email . "', '" . $dob . "')";
    if ($conn->query($sql)) {
        echo 'update successful';
    }else{
        echo 'update failed';
    };
}
$conn->close();

Many thanks in advance, Mike

return it as a JSON , using json_encode
   <?php
    //....
    if(mysqli_num_rows($query) > 0){
        $str =  "record already exists";
    }else{
        $sql = "INSERT INTO Users (email, dob) VALUES ('" . $email . "', '" . $dob . "')";
        if ($conn->query($sql)) {
            $str = 'update successful';
        }else{
            $str = 'update failed';
        };
    }
$data = array('response' => $str);

header('Content-Type: application/json');
echo json_encode($data);

0 comments:

Post a Comment