Pieter Pieter - 10 days ago 7
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();

$.ajax({
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;
});
});
</script>


The server side:

<?php
$user="username";
$password="password";
$database="database";

mysql_connect(localhost,$user,$password);
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."')";
mysql_query($query);
mysql_close();

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

echo json_encode($response_array);
?>

Answer

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

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

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

if(mysql_query($query)){
    $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.