views:

38

answers:

5

Why is it that I can never get JQuery serialize to work properly. I guess I must be missing something.

I can serialize a form data and it shows in an alert:

var forminfo = $j('#frmuserinfo').serialize();
alert(forminfo);

I then post to my PHP page thus:

$j.ajax({
  type: "POST", 
  url: "cv-user-process.php",
  data: "forminfo="+forminfo,
  cache: false, 
  complete: function(data) { 

  }
});

But WHENEVER (not the first time) I try to insert/update the data in the DB I only ever get 1 varaible passed:

Here is my PHP script:

$testit = mysql_query("UPDATE cv_usersmeta SET inputtest='".$_POST['forminfo']."' WHERE user='X'");

the data passed only ever gets the first variable. why?

I think it is more the way I deal with the php but it drives me nuts and always takes me far too long to find where I am going wrong.

A: 

In your php script have this at the top:

<?php
print_r($_POST);
exit;
?>

This should help you in finding out what could be going wrong for you.

zaf
A: 

You need to pass it a little differently, like this:

$j.ajax({
  type: "POST", 
  url: "cv-user-process.php",
  data: $j('#frmuserinfo').serialize(),
  cache: false, 
  complete: function(data) {    
  }
});

In your php don't use $_POST['forminfo'] but rather $_POST['nameOfTheInput']. Further, you should sanitize the input, like this:

$testit = mysql_query("UPDATE cv_usersmeta SET inputtest='".mysql_real_escape_string($_POST['nameOfTheInput'])."' WHERE user='X'");

This prevents SQL injection attacks, which I suggest you read more about :)

Nick Craver
A: 

I believe it's because you're wrapping the entire serialized form under the forminfo variable.

This would result in a form var such as forminfo=field1=val1&field2=val2 - so the whole thing comes to php as forminfo

You don't need to do that:

$j.ajax({
type: "POST", 
url: "cv-user-process.php",
data: forminfo,
cache: false, 
complete: function(data) { 

}
adam
A: 

And if you still need to send the whole serialized data, you must encode your string with escape() function. Like this:

$j.ajax({
  data: "forminfo="+escape(forminfo),
  ...
});
meze
A: 

I'd suggest you to ajaxForm/ajaxSubmit from http://jquery.malsup.com/form/ on the client side.

ThiefMaster