3

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);
}
1
  • 1
    Proper indentation is important... Commented May 14, 2012 at 13:36

6 Answers 6

3

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' )
Sign up to request clarification or add additional context in comments.

2 Comments

That worked, so thanks! I hadn't realized that's what was going on with: if (isset($_POST['submit']))
@adamKiryk Then maybe it's a good idea to atleast accept this as an answer? :-)
1

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

Comments

0

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

Comments

0

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.