Ollie Clark
Ollie Clark

Reputation: 141

Submit data within multiple table rows separately with jQuery.ajax()

Currently I am able to submit my form as long as I only have one row within the table. If I add a second row it won't work and I get an error. What I want to achieve is to post the data within each table row separately, but with only a single button press. You can see my HTML mark-up below.

<form>
  <table>
    <tr>
      <td><input type="hidden" name="FirstName" id="FirstName" value="Bob">Bob</td>
      <td><input type="hidden" name="Surname" id="Surname" value="Hoskins">Hoskins</td>
    </tr>

    <tr>
      <td><input type="hidden" name="FirstName" id="FirstName" value="Bruce">Bruce</td>
      <td><input type="hidden" name="Surname" id="Surname" value="Wayne">Wayne</td>
    </tr>
  </table>
</form>

I've been told that I can use jQuery AJAX to submit the data. I'm wondering if there's a way to write this jQuery so that it targets the first table row, submits the data, then the second row, submits the data again, and so on until all the rows are submitted separately in a loop. Below is the basic code I have for submitting the data but it needs to work with my HTML.

$.ajax({
   type: "POST",
   cache: false, 
   url: "WuFoo.aspx",
   data: data,
   success: success
});

Upvotes: 1

Views: 2188

Answers (1)

FosterZ
FosterZ

Reputation: 3911

I think you can do this way, first apply an ID to your table and loop through each tr.

$('#TableID > tr').each(function() {
    var postData = {
    'FirstName':$(this).find('#FirstName').val(),
    'SurName':$(this).find('#Surname').val()
    };
    $.ajax({
    type: "POST",
    cache: false, 
    url: "WuFoo.aspx",
    data: postData ,
    success: success
    });
 });

EDIT : I have updated my answer, I'm not sure this is the best way to do, but this will work to post your data.

Upvotes: 1

Related Questions