Don't Redirect On Submitting Form July 11, 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 thisformSubmit(event) CopyAnd 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); } }); }Copy<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>CopySolution 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>Baca JugaAjax Login Form Gets Submitted Even If Info Is InvalidHow To Save Html5 Geolocation Data To Python Django Admin?Flex Container Vertical Overflowing Parent DivSolution 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; }Copy<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>Copy Share You may like these postsShorthand For .load() Ajax Links With LoaderAjax Wont Call Its Php Script While Another Php Script Is RunningMy Data Is Not Saving In Database Using AjaxIssue With Ajax Loading A Php Script, Called From An Onclick; Post a Comment for "Don't Redirect On Submitting Form"
Post a Comment for "Don't Redirect On Submitting Form"