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);
}