Pieter Pieter - 1 year ago 106
HTML Question

How do I return a proper success/error message for JQuery .ajax() using PHP?

I keep getting the error alert. There is nothing wrong with the MYSQL part, the query gets executed and I can see the email addresses in the db.

The client side:

<script type="text/javascript">
$(function() {
$("form#subsribe_form").submit(function() {
var email = $("#email").val();

url: "subscribe.php",
type: "POST",
data: {email: email},
dataType: "json",
success: function() {
alert("Thank you for subscribing!");
error: function() {
alert("There was an error. Try again please!");
return false;

The server side:


mysql_select_db($database) or die( "Unable to select database");

$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['email'] ) : "";

if($senderEmail != "")
$query = "INSERT INTO participants VALUES (CURDATE(),'".$senderEmail."')";

$response_array['status'] = 'success';

echo json_encode($response_array);

Answer Source

You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.

    header('Content-type: application/json');
    echo json_encode($response_array);

Additional fix, you should check whether the query succeed or not.

    $response_array['status'] = 'success';  
}else {
    $response_array['status'] = 'error';  

On the client side:

success: function(data) {
    if(data.status == 'success'){
        alert("Thank you for subscribing!");
    }else if(data.status == 'error'){
        alert("Error on query!");

Hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download