I have a simple HTML based form like shown below, which keeps refreshing the page on click.
<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(this)">Go!</button> </span> </div> </form> And I am trying to stop it from redirecting when pressing the submit button.
(function($) { function formSubmit(e){ e.preventDefault(); //This will prevent the default click action e.stopPropagation(); 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; } }); I added return false to stop it from redirecting, aswell as PreventDefault, but the page still refreshes when sending the data (The data is being sent btw).
I also tried to do it with $().submit, but with the same results. (I have hidden the url out of security reasons, but the submit in itself works).
The name-data attribute is used because i have several of the same form on the page and like this I can make it reusable
submitevent of the form instead ofclickof a button.actionattribute from your form tag and then listen tosubmitevent of the form.<button type="submit"to<button type="button"