adam Kiryk
adam Kiryk

Reputation: 1735

How can I pass data from jQuery to php for saving into a database?

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

Upvotes: 3

Views: 8483

Answers (6)

Imdad
Imdad

Reputation: 6032

Its a simple mistake. You left submit while posting to process.php while you are checking its existence before updating DB

$('#button').click(function(){
    saveData();
});

function saveData(){  
$.ajax({
       type: "POST",
   url: "process.php",
   data: { name: "John", location: "Boston",submit:"submit" }
    }).done(function( msg ) {
 alert( "Data was saved: " + msg );
    });
}

Upvotes: 0

w00
w00

Reputation: 26762

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' )

Upvotes: 3

Tim Hoolihan
Tim Hoolihan

Reputation: 12396

Since you aren't submitting via a traditional form, but using ajax, I suspect submit isn't part of the post. Check that by putting in the following else clause to your code. If you're hitting that die statement, then remove the if test

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);
} else {
  die("$_POST['submit'] didn't exist");
}

Upvotes: 0

Ferran
Ferran

Reputation: 14993

In this example, $_POST['submit'] is not set because you are no sending the form as usual, you are rsendin data with ajax and there isn't any variable called "submit".

This may work better:

if ((isset($_POST['name'])) && (isset($_POST['location']))) { // 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);
}

Upvotes: 1

Eonasdan
Eonasdan

Reputation: 7765

all that

.done(function( msg ) {
     alert( "Data was saved: " + msg );
});

is telling you is that the ajax request is done. Your probably need to look at .success instead. Additionally, your code doesn't show this so I'm assuming that it's not doing this but in order for msg to have anything in your php needs to actually return something. (PHP people help me out with this I'm a .Net guy helping with the JS :) )

Upvotes: 0

GDP
GDP

Reputation: 8178

"Done" doesn't mean "succeeded". Instead of done:, use this to see if it finished successfully or not:

success: function(data)
    {
       alert(data);
    },
error:function (xhr, ajaxOptions, thrownError){
        alert("Error Status: " + xhr.status + " Thrown Errors: "+thrownError);
    }

Upvotes: 0

Related Questions