Ajax Form submit with preventDefault

后端 未结 4 813
予麋鹿
予麋鹿 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.

    0 讨论(0)
  • 2020-11-30 14:26
    $('#submit').click(function(e){
    
        //call ajax
    
    e.preventDefault();
    })
    
    0 讨论(0)
  • 2020-11-30 14:35

    set the submit button as type="button" instead of type="submit",

    and let's say the submit button has id submit-button. you can submit the form in javascript like this:

    $("#submit-button").click(function(){ 
     //send ajax
    })
    
    0 讨论(0)
  • 2020-11-30 14:38

    Wrap your code in DOM Ready

    $(function () {
        var frm = $('#contactForm1');
        frm.submit(function (ev) {
            $.ajax({
                type: frm.attr('method'),
                url: frm.attr('action'),
                data: frm.serialize(),
                success: function (data) {
                    alert('ok');
                }
            });
            ev.preventDefault();
        });
    });
    
    0 讨论(0)
提交回复
热议问题