Skip to content Skip to sidebar Skip to footer

Don't Redirect On Submitting Form

I have a simple HTML based form like shown below, which keeps refreshing the page on click.

Solution 1:

Use event not this

formSubmit(event)

And remove the unnecessary codes:

functionformSubmit(e){
    e.preventDefault(); //This will prevent the default click actionvar frm = $('#'+ $(this).data('name') +'');

    $.ajax({
        type: frm.attr('method'),
        url: '(url)',
        data: frm.serialize(),
        success: function (data) {
            console.log('Submission was successful.');
            console.log(data);
        },
        error: function (data) {
            console.log('An error occurred.');
            console.log(data);
        }
    });
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="register"action="#"method="POST"><divclass="input-group"><inputclass="form-control form-control-sm"placeholder="Email Address"name="email"type="text"><inputtype="hidden"name="form"value="register"><inputtype="hidden"name="type"value="websiteregistration"><spanclass="input-group-append"><buttontype="submit"class="btn btn-light"data-name="register"onclick="formSubmit(event)">Go!</button></span></div></form>

Solution 2:

Try to delete the type="submit" atribute and change it to type='button' and also change the argument from 'this' to 'event':

<button type="button" class="btn btn-light" data-name="register" onclick="formSubmit(event)">Go!</button>

Solution 3:

Give the type="button" instead of submit and also, remove the e.preventDefault(); and e.stopPropagation(); no need to add these two lines.

functionformSubmit(e){

    var frm = $('#'+ $(this).data('name') +'');

    $.ajax({
        type: frm.attr('method'),
        url: '(url)',
        data: frm.serialize(),
        success: function (data) {
            console.log('Submission was successful.');
            console.log(data);
        },
        error: function (data) {
            console.log('An error occurred.');
            console.log(data);
        }
    });

    returnfalse;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><!DOCTYPE html><html><head></head><body><formid="register"action="#"method="POST"><divclass="input-group"><inputclass="form-control form-control-sm"placeholder="Email Address"name="email"type="text"><inputtype="hidden"name="form"value="register"><inputtype="hidden"name="type"value="websiteregistration"><spanclass="input-group-append"><buttontype="button"class="btn btn-light"data-name="register"onclick="formSubmit(this)">Go!</button></span></div></form></body></html>

Post a Comment for "Don't Redirect On Submitting Form"