user2743803
user2743803

Reputation: 51

Simulate html form POST using ajax/jquery

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;
}

Upvotes: 4

Views: 7058

Answers (2)

codefreak
codefreak

Reputation: 7131

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.

Upvotes: 5

H Rangel
H Rangel

Reputation: 54

Have you tried it using JQuery's Ajax instead?

Like this answer here: jQuery Ajax POST example with PHP

Upvotes: 0

Related Questions