Farzher
Farzher

Reputation: 14593

How to submit an object of data via POST, not ajax

My data looks like this, it's just an object, with two objects in it (each representing the data of a form).

Object {x__sf: Object, x__mx: Object}
  x__mx: Object
    country_id: "1"
    input1: ""
    input2: ""
    ...
  x__sf: Object
    ...

I think I'll have to make a temporary form in memory and submit that? I'm not sure a safe way of looping through my data and adding hidden fields to the temporary form. Is there a function for this? Or better way?

I want to do this, but have it actually submit the page, because there's redirect logic serverside.

$.post('/whatever.php', data);

Upvotes: 1

Views: 532

Answers (3)

slashingweapon
slashingweapon

Reputation: 11317

You just want to stringify your data before you send it:

$.post('/whatever.php', JSON.stringify(data));

On the server side, you need to use the PHP json_decode() function:

json_decode(http_get_request_body());

Upvotes: 0

VisioN
VisioN

Reputation: 145458

But what is the problem with the following approach?

Server side:

<?php
// do some stuff
print "/redirect/to.php";
?>

Client side:

$.post("/whatever.php", data, function(data) {
    location.href = data;
});

Or even more advanced:

Server side:

<?php
// do some stuff
header("Content-Type: application/json");
print json_encode(array(
    "success" => "/redirect/to.php"
));
?>

Client side:

$.post("/whatever.php", data, function(data) {
    if (data.success) {
        location.href = data.success;
    }
}, "json");

Upvotes: 3

Brian
Brian

Reputation: 8626

Don't bother looping.... do something like this:

$('form').submit(function() {
  alert($(this).serialize());
  return false;
});

Or in you're case:

var data = $("#idOfForm").serialize();

Upvotes: 0

Related Questions