Rahul Kumar Rahul Kumar - 4 months ago 15
Ajax Question

form.serialize() not working

HTML Code

<div id="address" class="col s12">
<div class="row">
<form method="post" action="" id="addressDetails">
<div class="input-field col s6">
<textarea id="lAddress" name = 'lAddress' minlength='20' maxlength='100' class="materialize-textarea" class="validate" required length="100"></textarea>
<label for="lAddress" data-error="Must be between 20 to 100 Characters">Local Address</label>
</div>
<div class="input-field col s6">
<textarea id="pAddress" name = 'pAddress' minlength='20' maxlength='100' class="materialize-textarea" class="validate" required length="100"></textarea>
<label for="pAddress" data-error="Must be between 20 to 100 Characters">Permanent Address</label>
</div>
</form>
</div>
<div class="row center-align">
<button type="submit" name="submitAddress" form="addressDetails" class="waves-effect waves-light light-blue darken-1 btn updateProfile">Save Address Details</button>
</div>
</div>


JS Code

function updateProfile(event) {
console.log(this);
event.preventDefault();
form = $(this).closest('.col s12').find('form');
console.log($(form));
$.ajax('profile/updateProfile.php', {
type: "POST",
dataType: "json",
data: form.serialize(),
success: function(result) {
//console.log(result);
}
});
}

$(document).ready(function() {
$("button.updateProfile").on('click', updateProfile);
});


I check network AJAX calls using Chrome Debugger. None of the key value pairs are being passed.

There is no errors in Console Logs.

Answer

Your selector in closest() is incorrect. There should be no spaces and both values should be preceded by a . to signify a class selector. Try this:

var form = $(this).closest('.col.s12').find('form');

Working example