Get all Form values - working with jquery ajax in PHP

11,252

Solution 1

var $results = '';

foreach ($_POST as $key => $value) {
    echo $results .= "$key = $value;";
}

// $results holds the posted values

Solution 2

  foreach($_POST as $form_key => $form_val){ }

you will not want to query each time inside this loop, however. Instead append each time to a string that you will query with afterwards.

Share:
11,252
user469453
Author by

user469453

Updated on June 26, 2022

Comments

  • user469453
    user469453 almost 2 years

    I'm using this jquery to serialize my form and pass it to a PHP script called write.php;

    $("form").submit(function(){
    
        var_form_data = $(this).serialize();
    
        $.ajax({
           type: "POST",
           url: "write.php",
           data: var_form_data,
           success: function(msg){
             alert( "Data Saved: " + msg );
           }
        });
    
    });
    

    Normally, lets say I had a form with the fields Address F_name and S_name, I'd do something like this to get the values into PHP vars;

    $Address = $_POST["Address"];
    $F_name = $_POST["F_name"];
    $S_name = $_POST["S_name"];
    

    I'd then go onto persist these to the DB

    However, this particular form is liable to change on a regular basis. Therefore, I'd like to be able to get at all of the data that was passed through the ajax request in the form of a string that I can explode or an array.

    I can then loop through the items in the array and persist them to the DB one by one (i think!).

    I hope this makes sense, if I have missed anything or you would like me to explain further please let me know.

    As always - all help is very much appreciated.