2

How to reset a form after submission (which is submitted using ajax)?

3 Answers 3

4

You can place this code in your AJAX response success

$(':input','#YourFormId')
     .not(':button, :submit, :reset, :hidden')
     .val('')
     .removeAttr('checked')
     .removeAttr('selected');
2
  • can you explain
    – Jaisa
    Dec 28, 2017 at 6:01
  • 1
    I 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 attributes removeAttr('checked') and removeAttr('selected') for checkbox and dropdowns and will ignore fields such as button by .not(':button, :submit, :reset, :hidden'). Hopes this helps.
    – Priyank
    Dec 28, 2017 at 6:05
0

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.

2
  • could you please post html code of your form ? Dec 28, 2017 at 6:50
  • I have overrided the core form which is present in Magento\Review\view\frontend\templates\form.phtml. you can refer from that
    – Jaisa
    Dec 28, 2017 at 9:00
0

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);
            }
        });
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.