Brandon Mcq
Brandon Mcq

Reputation: 585

Submitting a html form with an unknown amount of fields with ajax

I have a form made up of pairs of text fields. The user can create as many pairs as they want and fill out the fields. Rows of fields are added to the bottom of the table. Here is a sample of the format:

<form id="dataForm">
<table id="textTable">
<tbody>
<tr>
  <td><h2>Dancer</h2></td>
  <td><h2>Place</h2></td>
</tr>
<tr>
  <td><input type="text" name="Dancer0" size="15" id="Dancer0"></td>
  <td><input type="text" name="Place0" size="15" id="Place0"></td>
</tr>
<tr>
  <td><input type="text" name="Dancer1" size="15" id="Dancer1"></td>
  <td><input type="text" name="Place1" size="15" id="Place1"></td>
</tr>
</tbody>
</table>
<input type="button" id="newRow" value="New Row" accesskey="/" onclick="moreFields();">
<input type="button" value="Update" name="Submit" onclick="submitForm(this.form);">
</form>

The trouble I am having is getting the form to submit properly to an external php page using ajax. This is the function I'm using right now:

function submitForm(form)
{
jQuery.ajax({
    type: "POST",
    url: <?php echo '"'.dirname(curPageURL()).'/ResultsUpdater.php"' ?>,
    data: form.serialize(),
    success: function(msg){
        alert(msg);
    }
});
return false;
}

On other examples I've seen them use $ to denote jQuery, and it would be put in front of "form": $(form).serialize() and $.ajax({... but my server doesn't like the $. I've also tried jQuery.form.serialize(), but that does not work either. The error I get in the console is always along the lines of "TypeError: 'undefined' is not an object (evaluating 'jQuery.form.serialize')"

If I could submit a bunch of key-value pairs to the php file (which from what I understand serialize() does), that would be great.

You can try out the form here

Just select one of the drop down items to see the form.

Thanks

Upvotes: 0

Views: 1264

Answers (1)

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

You can do it like this instead:

jQuery("#dataForm").serialize();

I've tried it successfully on the page you referenced.

Since $ is undefined on your page, my best guess is that you load some script which resets $ to undefined. The best way then is to fall back to use jQuery instead, since $ is just an alias for jQuery.

Upvotes: 3

Related Questions