Native Coder Native Coder - 3 months ago 11
jQuery Question

jQuery.serialize returns nothing (The Input elements DO have a name...)

For some reason I can't get jQuery to serialize my form. performing a google search just pointed me to a bunch of similar questions where the O.P. forgot to give the inputs a "name". But that's not my issue, as my inputs DO have a name...

$('#time_clock_form').serialize();


returns nothing on this form

<form id="time_clock_form" method="POST">
<label for="id">Enter last four ligits of SSN</label>
<input type="text" id="ssn" name="ssn" maxlength="4">
<input name="submit" value="Punch Timeclock" type="submit">
</form>


I've been ripping my hair out all morning. I even went as far as giving the inputs closing tags. (Obviously, that didn't work)

Here is where i am serializing the data

// When the user types in their ssn, punch the timeclock
$('#ssn').on('input', function(){

// When the user has input all 4 digits...
if($(this).val().length === 4){
// Disable the input (only until the AJAX request completes...)
$(this).prop('disabled', true);

console.log($('#time_clock_form').serialize());

// Send the AJAX request to punch the time clock
$.ajax({
url : 'AJAX_punchTimeClock.php',
data : $('#time_clock_form').serialize(),
success : function(Result){

// We can't use $(this) here because it would refer to the AJAX request, and not the input. Don't you just LOVE context errors?
$('#ssn').prop('disabled', false);

console.log(Result);
},
error : function(XHR, textError, error){

}

});
}
})

Answer

The issue is because you disable the input before you serialize it. serialize() doesn't work on disabled form elements. Change the order of those statements:

$('#ssn').on('input', function() {
    if ($(this).val().length === 4) {
        // serialize the form and store the output here
        console.log($('#time_clock_form').serialize());

        // then disable the form...
        $(this).prop('disabled', true);

        // ajax...
    }
});

Updated fiddle