Ajax Form submit with preventDefault

后端 未结 4 833
予麋鹿
予麋鹿 2020-11-30 13:55

I have a normal HTML form in which it is supposed to prevent default form submit and post the values by Ajax. It is not working with my setup Please help me where I went wr

4条回答
  •  无人及你
    2020-11-30 14:20

    Is your page refreshing when you submit the form even with preventDefault()?

    1. On you form, put # in the action attribute and remove method.
    2. Modify your JS code

      var frm = $('#contactForm1'); frm.submit(function (ev) { ev.preventDefault(); $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { alert('ok'); } }); });

    Put preventDefault before your ajax fires. Whats happening on your code is, your form is being executed with the action and method supplied in HTML, therefore your JS cannot catch it.

提交回复
热议问题