1

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);
AmShaegar
  • 1,403
  • 9
  • 18
Farzher
  • 11,368
  • 15
  • 57
  • 93

3 Answers3

3

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");
VisioN
  • 132,029
  • 27
  • 254
  • 262
  • 2
    +1, this is the approach I would use. As for a non-AJAX solution, however, this thread looks like what you want: http://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit – user428517 Nov 19 '12 at 15:39
  • @sgroves I don't think that function will work for my multidimensional object though. – Farzher Nov 19 '12 at 15:51
0

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();
Brian
  • 7,632
  • 2
  • 22
  • 32
0

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());
slashingweapon
  • 9,899
  • 3
  • 25
  • 46