Reputation: 681
I have the following ajax call for sending a form into a mysql database through a php file hosted on a server:
<script type"text/javascript">
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var fname = $('#fname').attr('value');
var lname = $('#lname').attr('value');
$.ajax({
type: "POST",
url: "jquery-ajax-control.php",
data: "fname="+ fname + "&lname=" + lname,
success: function(){
$('form#submit').hide();
//$('form#submit :input').val("");
$('div.success').fadeIn();
}
});
return false;
});
});
</script>
And my php:
<?php
include ("db.php");
// CLIENT INFORMATION
$fname = htmlspecialchars(trim($_POST['fname']));
$lname = htmlspecialchars(trim($_POST['lname']));
$addClient = "INSERT INTO clients (fname,lname) VALUES ('$fname','$lname')";
mysql_query($addClient) or die(mysql_error());
?>
On success function I want to retrieve an alert message from php or mysql to be sure that data is inserted in the database because the ajax it will be successful even if the connection it's down and I have the php file hosted on another server. How could I do that? Thank you!
Upvotes: 1
Views: 2033
Reputation: 1764
First of all, calling php from another server will give you error if you do not make the call with jsonp.
And for next part, if your php file get any error due to connection down you can send the error via response from php and getting it from jquery ajax callback function success.
Also you can get the message in callback function and show it through javascript alert message.
Upvotes: 0
Reputation: 2469
Have the jquery-ajax-control.php script return this information (perhaps encoded in a JSON string) and then parse it in the success function.
Here's an example that would display the output of the PHP script in an alert (if the request was successful):
$.ajax({
type: "POST",
url: "jquery-ajax-control.php",
data: "fname="+ fname + "&lname=" + lname,
success: function(message) {
alert(message);
}
});
You'd just need to alter your PHP script to return a message based on what happens.
You could also amend your PHP script to return the correct HTTP status code (e.g. a 500 if there was an error) and check for that, using the various callback functions jQuery allows to the ajax method.
Upvotes: 1