tags:

views:

233

answers:

1

I am having an issue with ajax sending values to my PHP script for processing.

Here is the simplified ajax I am using;

$.post("register_user.php", { lastname: "gather", username: "johnny" } );

This is the PHP Code:

$lastname = $_POST['lastname'];
$username = $_POST['username'];

**** Mysql Insert into DB code Here *****

My situation is more complex with more values to be sent, but what am I doing wrong? I have pin pointed it to the Ajax because when I put in values manually instead of the $_POST vars in the PHP it works fine. It is loading the page correctly because my php script sends blank values to the database.

Please help! Here is my last post regarding the issue: http://stackoverflow.com/questions/1250157/jquery-ajax-issue

EDIT

I have changed the code and put serialize in it. It successfully gets all of the form fields but it is not posting to the database, it is throwing blanks still. I know my PHP code is good. Firebug says 304 Not Modified.

+2  A: 

Two things:

Did you try changing your data being sent to use the jQuery's form Serialize function?

$('form :input').serialize()

This will take all text, checkboxes, radio buttons, etc and add them to an appropriate value to be sent. You just have to make sure the inputs are named according to your variables in your PHP file.

Also, a tip: Wrap the $_POST assignments in a simple check:

// only allow AJAX POSTs
if (!empty($_POST) && isAjax())
{
  // code here
}
function isAjax() {
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
    ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
}
Jim Schubert
thank you for your persistence Jim you are helping me a lot :) i did serialize before when you suggested it but it didnt work for some reason.
Chris B.
Jim Schubert
since the post vars are being gathered correctly i dont see what the issue is. This is my current ajax:$.post("register_user.php", $('form').serialize() );
Chris B.
I think its not even posting, firebug, my new love says "GET process.js" it never says "POST register_user.php" like i would expect it to.
Chris B.
make sure the last line in $('form').submit(function() { } is return false; If that's not the case, go through your form's html and make sure the input tags are in the format: input name="firstname" type="text" and that they match the casing of your variables in your PHP file. If your inputs are missing name="whatever", serialize() doesn't seem to actually "POST" since it doesnt have keys for your values. Following this convention is a small price to pay for jQuery actually building the query text for you.
Jim Schubert