I am new to Ajax and hope someone can help me with this.
I use the below Ajax call in an onclick event in jQuery in order to pass data to a PHP file which inserts it into a MySQL db.
In the PHP file I echo one of the following depending on the outcome of the SQL INSERT: "record already exists", "update successful", "update failed"
.
So far everything works as intended but I could not find a way to tell this back to the user. In order to update the user I would like to alert or show them what PHP returns here, e.g. "Error: record already exists".
I checked several websites but couldn't find the right approach and the below does not work.
Can someone help me with this and also provide a short explanation ?
My Ajax call (in jQuery):
$.ajax({
url: "ajax.php",
type: "post",
cache: "false",
data: {
email: email,
dob: dob
},
success: function(data) {
// update successful
console.log(data);
},
error: function(){
// update failed
alert('Error: ' + data); // here I would like to communicate back to the user
}
});
Update: Here is the relevant part of my PHP that echoes the outcome:
$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';
};
}
Many thanks in advance, Mike