i have a form that fetches all the data from database and in order to update the datas that is fetched i need to serialize the data.
alert($("form").serialize());
and this is the output
tid=1&tname=T+Cap&tsize=XS&quantity=1&tprice=1200&tid=2&tname=Super&tsize=XS&quantity=1&tprice=2800&tid=3&tname=Dota+Tees&tsize=XS&quantity=1&tprice=700
how to retrieve this data in php in order for me to update the database?
-
@MichaelDoye still getting the last values of the $_POST datas. im using this $tid = $_POST['tid']; $tname = $_POST['tname']; $tsize = $_POST['tsize'];doy619– doy6192015年03月03日 18:07:27 +00:00Commented Mar 3, 2015 at 18:07
4 Answers 4
You have to combine functions $.submit() and $.post() or $.ajax():
$('form').submit(function() {
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data) {
console.log(data); // show response from the php script
}
});
return false;
});
Then in your PHP script you have to read your data from $_POST array. E.g.
$tid = $_POST['tid'];
To debug your incoming $_POST array use var_dump() or print_r().
If you want to send response to your javascript just pack whatever you want into variable and then just use die(json_encode());. E.g.:
$output = array('status' => true, 'message' => 'Success');
die(json_encode($output));
It also will be required to add to $.post() method attribute:
dataType : 'json'
Comments
In your PHP, at the top write this and you'll see what's happening.
//If method = GET
var_dump($_GET);
//If method = POST
var_dump($_POST);
exit();
This will show all variables that are being passed and stop the script so you can review on the page. Then just have your jquery put the response data in a div that you can view.
Comments
The problem seems to be that you are redefining your $_POST vars. They can not contain the same names/keys as you are sending them over currently. Essentially its like redefining a variable, it will no longer contain its previous value.
tid=1&tname=T+Cap&tsize=XS&quantity=1&tprice=1200&tid=2&tname=Super&tsize=XS&quantity=1&tprice=2800&tid=3&tname=Dota+Tees&tsize=XS&quantity=1&tprice=700
Notice how you have called tid and the other keys multiple times? Instead you would want to give them separate names,or pass an array of values to your PHP.
Example:
tid=1&tname=T+Cap&tsize=XS&quantity=1&tprice=1200&tid2=2&tname2=Super&tsize2=XS&quantity2=1&tprice2=2800&tid3**=3&tname3=Dota+Tees&tsize3=XS&quantity3=1&tprice3=700
Of course there are other ways of doing this as well.
Each key must have a unique identifier, other wise it will overwrite the previously defined $_POST value.
Instead of:
tid=1&
tid=2&
tid=3&
You would want:
tid1=1&
tid2=2&
tid3=3&
13 Comments
Looks like a job for PHP's parse_str() function. http://php.net/manual/en/function.parse-str.php