Reputation: 12530
I'm using jQuery to POST a form without leaving the page it's on. The PHP page the form is being POSTed to sends an email and echos a '1' for success or a '0' for failure.
I would like to retrieve the contents of that PHP page ('1' or '0') and display it in an alert box on the page with the form (the page we stay on, even after POSTing).
I have tried this:
$(document).ready(function(){
var $form = $('#confirmationForm');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
alert(response);
},'json');
return false;
});
});
The form is POSTed just fine, and the PHP script functions as normal (the email is sent), but no response is displayed.
Upvotes: 0
Views: 5052
Reputation: 2585
You have to echo the response from the php script and you are done
For example
if(mysql_query($query))
$response_array['status'] = 'success';
else
$response_array['status'] = 'error';
header('Content-type: application/json');
echo json_encode($response_array);
?>
On the client side
success: function(data) {
if(data.status == 'success')
alert("Thank you you succeeded");
else if(data.status == 'error')
alert("Oops there was an error!");
},
Hope you got my point.
Cheers!!!
Upvotes: 3