0

I have a form with multiple fields, whereby fields can be added.

The FORM is as follows:

<form id="myForm" action="myfile.php" >
<input . . > 

<select>. . . </select>

</form>

myfile.php has the following code:

foreach ($_POST as $key => $value) {

echo $key." takes the <b>".$value."</b> Value"; 

}

This simple code processes all the entries of the form regardless how many.

Now, what I want is:

When I click on the submit button, instead of sending the form's content to a script, to actually get that array and pass it AJAX without having to write every single key and its value manually.

I hope it makes sense

JanvierDesigns
  • 71
  • 1
  • 10
  • 1
    I think you missed this section out when you learned about ajax in jquery https://api.jquery.com/serialize/ – Popnoodles Mar 10 '14 at 01:02
  • possible duplicate of [jQuery Ajax POST example with PHP](http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php) – Popnoodles Mar 10 '14 at 01:04

2 Answers2

1

I think what you are looking for is serialize()

jQuery(function ($) {
    //submit handler
    $('#myForm').submit(function (e) {
        //prevent default submit
        e.preventDefault();

        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            ....
        })
    });
})
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • I just got an answer from http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php?rq=1 Thanks – JanvierDesigns Mar 10 '14 at 01:03
  • 1
    @JanvierDesigns Ok but I think unless you delete the question this answer should still be marked as the correct answer. – Popnoodles Mar 10 '14 at 01:07
0

You can use jQuery serialize() method

$("#myForm").submit(function(e){ //To listen submit event
    e.preventDefault(); //To prevent default browser action
    var data=$(this).serialize(); // To get form data
    $.post($(this).attr('action'),data,function(data){ //To perform post
         $('#result').html(data); //Result data
    });
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188