简体   繁体   中英

Email being sent out multiple times

I have written a javascript code which handles inputs from a contact form. Using Ajax I send the input information to the backend to send out an email.

However, it seems that my code is somehow sending multiple emails out instead of one. The "Email is sent" message is showing a few times.

Could anyone tell me what went wrong?

JAVASCRIPT CODE:

$(document).on('click', '.individual_contact', function(e) {
    e.preventDefault();
    var user_name = $('span#user-name').text();
    var recipient_name = $(this).attr('data-ind');
    console.log('recipient_name='+recipient_name);

    $("div#content").hide('fast');
    $("#section-form").show('fast');
    $("#section-form #recipient").attr('data-contact', recipient_name);
    $("#section-form #recipient").attr('placeholder', 'TO:  '+recipient_name.toUpperCase());
    $("#section-form #name").val('FROM:  '+user_name.toUpperCase());

    $('.submit_icontact').click(function(e) {
        var subject = $('input#subject').val();
        var message = $('textarea#message').val();

        e.preventDefault();
        var form = new FormData();
        form.append('user_email', ajaxobject.user_id);
        form.append('user_name', user_name);
        form.append('recipient_name', recipient_name);
        form.append('subject', subject);
        form.append('message', message);
        form.append('action', 'contact_individual');
        console.log(form);

        $.ajax({
            type: 'POST',
            url: ajaxobject.ajaxurl,
            enctype: 'multipart/form-data',
            cache: false,
            contentType: false,
            processData: false,
            data: form,
            dataType: 'json',
            success: function(response) {
                console.log('Email is sent');
            },
            error:function(err){
                console.log('err,error')
            }
        });
    });
})

Each time you click on a .individual_contact you add another event listener to .submit_icontact .

Move your .submit_icontact click event out of your .individual_contact click handler

Change:

$('.submit_icontact').click(function(e) {

To:

$('.submit_icontact').unbind().click(function(e) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM