I've read about the jQuery.ajax method and believe this should be what I need -- but so far can't get it to work.
I created a test mysql database with a table called "users", added rows to that table for "name" and "location", and then made sure I could save data to it using the command line, which I could. Then I made a test page with a button on it and added this copy to my scripts file (the $.ajax part comes straight from the jQuery api examples):
$('#button').click(function(){
saveData();
});
function saveData(){
$.ajax({
type: "POST",
url: "process.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data was saved: " + msg );
});
}
I do indeed get an alert message, "Data was saved", but nothing has actually been saved to my database. I must be doing something wrong with process.php, but not sure what. Here's the code in process.php (I set variables for database, db_host, user, etc that I don't display here):
// 1. Create a connection to the server.
$connection = mysql_connect($db_host, $db_user,$db_pwd);
// make sure a connection has been made
if (!$connection){
die("Database connection failed: " . mysql.error());
}
// 2. Select the database on the server
$db_select = mysql_select_db($database, $connection);
if (!$db_select){
die("Database selection failed: " . mysql.error());
}
// START FORM PROCESSING
if (isset($_POST['submit'])) { // Form has been submitted.
$name = trim(mysql_prep($_POST['name']));
$location = trim(mysql_prep($_POST['location']));
// INSERT THE DATA
$query = "INSERT INTO user ( name, location )
VALUES ( '{$name}','{$location}' )";
// Confirm if the query is successful.
$result = mysql_query($query, $connection);
}
It's has already been told by others, about using 'success' and 'error' which would be indeed a better method to capture the success/error callback. But that's really not the problem why nothing is inserted. Your Ajax call looks good besides that.
Another problem that i see is that you're only passing the following params:
data: { name: "John", location: "Boston" }
But in your PHP code you do check if a submit button was set:
if (isset($_POST['submit']))
This is obviously not the case because the only things that are sent are the things you pass in the 'data' attribute of the Ajax call. Instead use:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With