doy619
doy619

Reputation: 11

Jquery Ajax Serialize data to PHP

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?

Upvotes: 0

Views: 169

Answers (4)

Roman Hocke
Roman Hocke

Reputation: 4239

Looks like a job for PHP's parse_str() function. http://php.net/manual/en/function.parse-str.php

Upvotes: 0

wrxsti
wrxsti

Reputation: 3494

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&

Upvotes: 0

marian0
marian0

Reputation: 3337

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'

Upvotes: 2

b3tac0d3
b3tac0d3

Reputation: 908

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.

Upvotes: 0

Related Questions