How to reset a form after submission (which is submitted using ajax)?
3 Answers
You can place this code in your AJAX response success
$(':input','#YourFormId')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
-
-
1I dont think there is any explanation needed for this but still since you are asking it will get all input fields with the form ID you have mentioned it will empty its value
val('')
, remove attributesremoveAttr('checked')
andremoveAttr('selected')
for checkbox and dropdowns and will ignore fields such as button by.not(':button, :submit, :reset, :hidden')
. Hopes this helps.– PriyankDec 28, 2017 at 6:05
You can reset it with jquery.
Use Below code
$("#form_id").reset();
You can do this with simple javascript as well.
document.getElementById("form_id").reset();
You can call this in ajax success method. so once your ajax call will be success it will reset the form.
-
-
I have overrided the core form which is present in Magento\Review\view\frontend\templates\form.phtml. you can refer from that– JaisaDec 28, 2017 at 9:00
Following code works fine for me to clear form data after submission using ajax.
Please add below the jquery code after ajax success response.
$('#your-form-id')[0].reset();
Full Sample Code
$('#quote-request-form').submit(function (event) {
$("#suc_msg").html('');
$("#err_msg").html('');
event.preventDefault();
var form = $(this);
var formData = form.serialize();
$.ajax({
type: 'POST',
url: '<?php echo $block->getUrl("quoterequest/index/quoterequest"); ?>',
data: formData,
showLoader: true,
cache: false,
success: function (response) {
console.log(response);
$('#quote-request-form')[0].reset(); //Clear form data
if(response.success != '')
{
$("#suc_msg").show();
$("#suc_msg").html(response.success);
}
else
{
$("#error_msg").show();
$("#suc_msg").html(response.error);
}
},
error: function (xhr, status, error) {
console.error(error);
}
});
});