Почему моя контактная форма Ajax не получает электронные письма? - PullRequest
0 голосов
/ 17 февраля 2019

Я пытаюсь настроить контактную форму, но по какой-то причине она не работает, и я не уверен, почему.

Здесь есть форма контакта, мой ajaxform.js и функция parser_callback в моих функциях.php.

контактная форма

<div id="form-response">
</div>
<form class="contact-form" method="post" action="" id="ajaxContactForm">
<div class="upper-form">
<div class="contact-input"><input type="text" id="name" placeholder="Your name" required></div>
<div class="contact-input"><input type="email" id="mail" placeholder="Your mail" required></div>
</div>
<div class="contact-input"><textarea id="message" placeholder="Your message" rows="10" required></textarea></div>
<div class="lower-form">
<div class="contact-input"><span class="status"></span></div>
<div class="contact-input"><input id="submitButton" type="submit" value="Send"></div>
</div>
</form>

ajaxform.js

$(document).ready(function() {  
console.log( "ready!" );
    $( '#ajaxContactForm' ).submit(ajaxSubmit);

function ajaxSubmit(e){

e.preventDefault();
var name = $( "#name" ).val();
var mail = $( "#mail" ).val();
var message = $( "#message" ).val();
var replyText = $( "#form-response" );
var status = $( ".status" );

$( "#submitButton" ).attr("disabled", true);
status.html( 'please wait...' );
console.log(status);
function clearForm() {
    $( "#name" ).val( '' ); 
    $( "#mail" ).val( '' );
    $( "#message" ).val( '' );
}

    $.ajax({ //ajax request
         url: MyAjax.ajaxurl, //wp's own admin-ajax.php that will handle the request
         type: 'POST', //what kind of request: its a post-request, we are sending data to the server
         datatype: 'json', //what datatype received back, explicitly stated json wanted
         data: { //actual data sending
            "action": 'parser_callback', //what action to execute, in this case parser_callback in functions.php
            name: name,
            mail: mail,
            message: message,
            "nonce": MyAjax.nonce //send the nonce for security
         },
         success: function( response ) {
             status.html( response );
             replyText.html ( '<h2>Thanks for contacting me '+ name +'! I will get back to you as soon as possible.</h2>' );
             clearForm();
             $( "#submitButton" ).attr("disabled", false);
         },
         error: function( error ) {
             status.html( response );
             $( "#submitButton" ).attr("disabled", false);
         },
         beforeSubmit : function(arr, $form, options){
            arr.push( { "name" : "nonce", "value" : MyAjax } );
         }
    });
    return false;
    }
    });

parser_callback (в functions.php)

function parser_callback() {

        wp_send_json_error( 'You suck!' ); // to see if the ajax request to parser is successfully sent.

        if ( ! check_ajax_referer( 'ajax-contact-nonce', 'nonce' ) ) { // to see if nonce checks out
            return wp_send_json_error( 'Invalid nonce' );
        }

    if ( isset($_POST['name']) && isset($_POST['mail']) && isset($_POST['message']) ) { 
        $name = $_POST['name'];
        $mail = $_POST['mail'];
        $message = nl2br($_POST['message']);
        $to = "<mail@mymail.se>";
        $from = "<$mail>";
        $subject = 'Contactform from mysite.com sent';
        $message = '<b>Name:</b> '.$name.' <br><b>Email:</b> '.$mail.' <p>'.$message.'</p>';
        $headers = "From: $from" . "\r\n" . "Reply-to: $mail" . "\r\n" . "X-Mailer: PHP/" . phpversion();
        $headers .= "MIME-version: 1.0\n";
        $headers .= "Content-Type: text/html; charset=utf-8\n"; //Fixes ÅÄÖ in Sender name and Message


        if( mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=', $message, $headers) ) { //Fixes ÅÄÖ in subject 
            echo "success"; 

        } else { 
            echo "The server failed to send the message. Please try again later."; 
        } 
    } 
    exit();
    }
    add_action( 'wp_ajax_parser', 'parser_callback' );
    add_action( 'wp_ajax_nopriv_parser', 'parser_callback' );

Когда я проверяю свою форму, я не получаю ошибок (у меня добавлена ​​обработка отчетов об ошибках в functions.php), кроме "You suck!"json_error в сетевом журнале, который указывает, что ajax-запрос к функции парсера не выполнен успешно, хотя я не знаю почему.

Кроме того, отображается текст «Спасибо, что связались со мной ..», но эхо-запросы «Успех» или «Ошибка сервера» отсутствуют.Я не получаю никакой другой информации с помощью осмотра и / или консоли из инструментов Chrome.

...