4

I want to read all the post variables and their content from a form and post them using jquery's "$.post()". First of all, this won't do the job: $.post("myServer.com/test2.php", $('#myform').serialize()) because it would only send one variable which I'd have to parse on the php side.

Here is how I'd start:

function doIndirectPost() {
    variableWithTheFormPOSTData = {};
    $("#IdOfMyForm :input").each(function() {
        variableWithTheFormPOSTData[$(this).attr("name")] = $(this).attr("value");
    }
    document.getElementById("IdOfMyForm").submit();
    $.post("myServer.com/test2.php", variableWithTheFormPOSTData);
}

and then I'd like to use $.post() to post the data seperated in multiple variables (just like a normal form submit would do it... I read somewhere, that you could do that like this:

$.post('myserver.com/test2.php.php',{
    var1: content1,
    var2: content2
}

But I want it to be dynamic. This part:

    var1: content1,
    var2: content2

should autmatically contain all variable names and values of the form.

In the end I'd like to be able to get all POST variables like this:

foreach ($_POST as $key => $value)
{
    echo $key . "= " . $value;
}
user2743803
  • 51
  • 1
  • 3
  • Have you tried `serializeArray()`? – Ben Fortune Sep 04 '13 at 11:16
  • "First of all, this won't do the job: $.post("myServer.com/test2.php", $('#myform').serialize()) because it would only send one variable" — That simply isn't true. It would send all the successful inputs in the form, using the standard form encoding method, and PHP would decode it automatically and populate `$_POST`. – Quentin Sep 04 '13 at 11:28
  • really?? I was told that I'd have to use parse_str($_POST['serialize'], $data); on it. idk – user2743803 Sep 04 '13 at 12:16
  • That's only if you do something stupid like: `$.post('foo.php', { serialize: $('#myform').serialize() });` – Quentin Sep 04 '13 at 12:23

2 Answers2

5

Serialize doesn't send only one variable, it sends name value pairs of all input elements in the form. So

    $("#IdOfMyForm").on("submit", function () {
        $.post("myServer.com/test2.php", $("#IdOfMyForm").serialize(), 
                function(dataFromServer){
                   //server sent a response now do whatever you want to do after form has been submitted 
                   //or submit form regular way $("#IdOfMyForm").submit();
                 }
        );
        return false;
    });

Should work. Just remember to set name attribute of every input/select element in form.

codefreak
  • 6,950
  • 3
  • 42
  • 51
  • 1
    Nice and simple answer. Maybe you could even say: `$.post($("#IdOfMyForm").attr('action'),$("#IdOfMyForm").serialize(),` – soger Oct 28 '14 at 13:21
0

Have you tried it using JQuery's Ajax instead?

Like this answer here: jQuery Ajax POST example with PHP

Community
  • 1
  • 1
H Rangel
  • 54
  • 4