Example we have a form like this
1 2 3 | <form action="user/login" id="login" method="post"> ... </form> |
We want validate with ajax, and if error, make form not submit. Right? But preventDefault, is not working inside the ajax.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $(document).ready(function () { $('#login').on('submit', function (event) { var $form = $(this); $.ajax({ data: $form.serialize(), type: 'POST', url: 'user/login_validate', success: function (data) { this.submit(); }, error: function (jqXHR) { alert(jqXHR.responseJSON.message); event.preventDefault(); } }); }); }); |
If we using the variable and then make return, it’s also not working.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $(document).ready(function () { $('#login').on('submit', function (event) { var valid = true; var $form = $(this); $.ajax({ data: $form.serialize(), type: 'POST', url: 'user/login_validate', success: function (data) { this.submit(); }, error: function (jqXHR) { alert(jqXHR.responseJSON.message); valid = false; } }); return valid; }); }); |
So, we need use context, to make ajax callback and submit the form.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | $(document).ready(function () { $('#login').on('submit', function (event) { event.preventDefault(); var $form = $(this); $.ajax({ context: this, data: $form.serialize(), type: 'POST', url: 'user/login_validate', success: function (data) { this.submit(); }, error: function (jqXHR) { alert(jqXHR.responseJSON.message); } }); }); }); |
Thank you very much. You have saved my life, because i couldn’t find this solution 😀
Greate post. Keep posting such kind of info on your blog.
Im really impressed by your site.
Hey there, You have done a fantastic job. I’ll definitely digg
it and in my view recommend to my friends. I’m sure they’ll be benefited from this web site.
Excellent blog! Do you have any tips for aspiring writers?
I’m planning to start my own website soon but I’m a little lost
on everything. Would you recommend starting with a free platform like WordPress or go
for a paid option? There are so many options out there
that I’m totally confused .. Any tips? Thanks!
For most recent news you have to go to see web and on the web I found this
website as a finest website for newest updates.