event.preventDefault () conflicting in Contact form!

0

Just look at my problem. I have a normal contact form using PHPMailer which in one project worked perfectly, all return messages were using CSS only, without JS. But now in this new project I want to use a JS to make the messages look nicer.

Then I used the following js:

// Contact form
var form = $('#main-contact-form');
form.submit(function (event) {
    event.preventDefault();
    var form_status = $('<div class="form_status"></div>');
    $.ajax({
        url: $(this).attr('action'),
        beforeSend: function () {
            form.prepend(form_status.html('<p>Enviando Email...</p>').fadeIn());
        }
    }).done(function (data) {
        form_status.html('<p class="text-success">Obrigado por entrar em contato!</p>').delay(3000).fadeOut();
    });
});

When I submit the form, the message Thanks for contacting me! appears with the effect of delay and fadeOut , but does not send anything Now, if I remove the event.preventDefault () it will display the same message, only fast, without using the delay and send the form with all the data. p>

Where is the problem?

    
asked by anonymous 16.04.2017 / 05:20

2 answers

0

When you use event.preventDefault(); the form does not send. That is, ajax runs only by calling the url url: $(this).attr('action'), with no data ...

What you should do is send form data with ajax.

And then you have to put the text Obrigado por entrar em contato! somewhere, because I do not see where form_status is added to the DOM.

Example:

var form = $('#main-contact-form');
form.submit(function (event) {
    event.preventDefault();
    var form_status = $('<div class="form_status"></div>');
    $(this).prepend(form_status);
    $.ajax({
        url: $(this).attr('action'),
        data : $(this).serialize(),
        beforeSend: function () {
            form_status.html('<p>Enviando Email...</p>').fadeIn();
        }
    }).done(function (data) {
        form_status.html('<p class="text-success">Obrigado por entrar em contato!</p>').delay(3000).fadeOut();
    });
});
    
16.04.2017 / 12:17
0

Using event.preventDefault() you cancel your submit and go straight to .done() , your message pops up and adds because your action is trying to redirect you to your page, try to put a return false on your submit to avoid redirection, like this:

var form = $('#main-contact-form');
form.submit(function (event) {
    event.preventDefault();
    var form_status = $('<div class="form_status"></div>');
    $(this).prepend(form_status);
    $.ajax({
        url: $(this).attr('action'),
        data : $(this).serialize(),
        beforeSend: function () {
            form_status.html('<p>Enviando Email...</p>').fadeIn();
        }

    }).done(function (data) {
        form_status.html('<p class="text-success">Obrigado por entrar em contato!</p>').delay(3000).fadeOut();
    });
    return false;
});
    
04.04.2018 / 00:46