Don't Redirect On Submitting Form March 27, 2023 Post a Comment 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) Copy And remove the unnecessary codes: function formSubmit(e){ e.preventDefault(); //This will prevent the default click action 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); } }); }Copy <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="register" action="#" method="POST"> <div class="input-group"> <input class="form-control form-control-sm" placeholder="Email Address" name="email" type="text"> <input type="hidden" name="form" value="register"> <input type="hidden" name="type" value="websiteregistration"> <span class="input-group-append"> <button type="submit" class="btn btn-light" data-name="register" onclick="formSubmit(event)">Go!</button> </span> </div> </form>Copy 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. function formSubmit(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); } }); return false; }Copy <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> </head> <body> <form id="register" action="#" method="POST"> <div class="input-group"> <input class="form-control form-control-sm" placeholder="Email Address" name="email" type="text"> <input type="hidden" name="form" value="register"> <input type="hidden" name="type" value="websiteregistration"> <span class="input-group-append"> <button type="button" class="btn btn-light" data-name="register" onclick="formSubmit(this)">Go!</button> </span> </div> </form> </body> </html>Copy Share Post a Comment for "Don't Redirect On Submitting Form"
Post a Comment for "Don't Redirect On Submitting Form"