I’m having trouble working this out for inserting input values into database.
I have something like this
$("form#profileName").submit(function(){
var updateName = $(this).serialize();
$.post("update.php",{updateName: updateName},function(data){
alert(data);
});
return false;
});
In my PHP I have something like this
if(isset($_POST['updateName'])){
$fname = $_POST['updateName']['f_name'];
$mname = $_POST['updateName']['m_name'];
$lname = $_POST['updateName']['l_name'];
$altname = $_POST['updateName']['alt_nam'];
echo $fname." ".$mname." ".$lname." ".$altname;
}
its echoing out “f f f f” for some reason,
am I doing this correctly?
Thanks
Here’s some documentation on .serialize()
You’re basically serializing it twice.
I’m going to take a wild guess and say that the reason it’s outputting “f f f f” is because the
$_POST['updateName']is now a single string. Each individual character in PHP is accessed like this$string[n]. I suppose it’s interpreting blank as 0, and gives you the first character, which is in fact “f”.Here’s how it should look like:
or, in my opinion, the beautiful and clean way,
And the PHP
$_POSTvariable will now have several values, which are accessed like this:Also note that in the PHP script, you might have to use
urldecode()orrawurldecode()on your variables, depending on how you send the data in the JS (encodeURI()orencodeURIComponent()).In this case,
serialize()has it’s own internal encodeURI(), so there is no need for it, but the PHP might need to decode it.If you’re still having problems after you’ve fixed the 2xSerialize, just change the PHP script to decode the encoded data:
Sidenote:
If you’ve got an ID attr on the form, why not use:
$("#profileName").submit(...)?Makes more sense if you ask me.
Debugging
Depending on what browser you’re using, you can check what XHR is sending to/recieving from the server. In Firefox you can use the plugin called Firebug (XHR panel is under Net->XHR)
Mike also mentioned debugging in Chrome:
Final solution
The solution should now look something like this:
Javascript:
PHP script “update.php”: