Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery form.serialize() returns an empty string

I've got a problem with the form.serialize() function in jQuery. When I try to submit my serialized form via AJAX, serialize() only returns me an empty string.

Perhaps there's a problem with my HTML outline:

<form id="category-dynamic" class="dynamic">
   <fieldset id="inner-fieldset">
      <legend id="new-category">
        <label for="category-name">Category Name: </label>
        <input type="text" name="category-name" value="" />
      </legend>
      <ul id="category-fields">
         <li>
           <label>Field #1:</label><br />
           <input type="text" name="fields[]" value="" />
         </li>
         <li>
           <label>Field #2:</label><br />
           <input type="text" name="fields[]" value="" />
         </li>
      </ul>
   </fieldset>
</form>

In my jQuery function I simply call:

$.post("processor.php", $('#category-dynamic').serialize(), function(data){
     // data handling here...
});
like image 431
n0pt3x Avatar asked May 28 '11 15:05

n0pt3x


2 Answers

A heads up for others who might encounter this problem. Apart from not being disabled, the <input> fields must also have name attribute for serialize() to work.

like image 174
RijulB Avatar answered Sep 24 '22 17:09

RijulB


I had a similar problem to this. When debugging the JavaScript I could see the input values within the form but when calling serialize() the resulting string was empty.

It turned out I was disabling my input elements on the form before calling serialize(). To fix it I changed the code to retrieve the form values before disabling, then use the form values string in the post method.

// Disabling the input fields breaks serialize, so get the values string first
var formValues = form.serialize();
form.find('input').attr('disabled', 'disabled'); 
// Now post the form to the server
$.post(this.action, formValues, function (data)
{
  //...
like image 41
robmzd Avatar answered Sep 22 '22 17:09

robmzd