V. Seles V. Seles - 4 months ago 20
Javascript Question

How to retrieve an error message from a php file to another php file?

I'm new to ajax and this is my first attempt to use it.

What I'm trying to do is create a small system to register an email and password to the database without updating the page and it worked just fine!

However, as you will notice on my 'register.php' file, there is a condition to not allow duplicate emails, as well as PDOException to prevent errors...so, how can I send a message (an alert or whatever) to my index page in case any of them occurs?

This is my .js file:

$(document).ready(function(){

$("#btnRegister").click(function(){

$.ajax({
type: 'post',
url: 'register.php',
data: { txtEmail: $("#frmEmail").val(), txtPassword: $("#frmPassword").val() }
}).done(function(){
$("#frmEmail").val('');
$("#frmPassword").val('');
$("#frmEmail").focus();
});
});
});


My 'register.php' file:

<?php

try
{
$handler = new PDO('mysql:host=127.0.0.1;dbname=register', 'root', '');
$handler -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$email = $_POST['txtEmail'];
$password = $_POST['txtPassword'];

$sql = "SELECT email FROM users WHERE email = ?";
$query = $handler -> prepare($sql);
$query -> bindValue(1, $email);
$query -> execute();

if(($query -> rowCount()) != 0)
die("Error: the inserted email already exists.");
else
{
$sql = "INSERT INTO users (email, pass) VALUES (?, ?)";
$query = $handler -> prepare($sql);
$query -> bindValue(1, $email);
$query -> bindValue(2, $password);
$query -> execute();
}
}
catch(PDOException $ex)
{
die("Error: " . $ex -> getMessage());
}

?>

Answer

Usually, your PHP file would return a response indicating the success or failre of the registration.

In your PHP file, instead of dieing when there is an error, you should return a json-encoded array containing the error message, for example:

if(($query -> rowCount()) != 0)
    echo json_encode(array('error' => "Error: the inserted email already exists."));
    exit;
else

Then in your javascript's done function, you can check for this message:

}).done(function(data){
    if (data.error) {
        alert(data.error); // or do something else
    } else {
        // every thing looks ok, do your thing
    }
});

I'd recommend always returning something from php, whether it's an error message as above, or simply json_encode(array('success' => true));. That way, you can be sure that the request has actually done what is expected, and not returned a blank page for another (bad) reason.

Note: if you have problems getting this to work, you might need to add dataType: 'json' to your ajax options (under type: 'post')