1

I have two contact forms in my theme, one of them saves the contact information in a custom post and send emails to user and admin, and is working great. The other has to send the email, but not save anything.

The problem is that, the second contact form has an empty response, the request has a status code: 200 ok, the emails are sent, but in the form i get the error message not the success, even when the form has been submitted successfully. In the inspector, in headers are ok, but in response empty.

Hope you can help me (and understand my problem, my english is terrible)

Thanks,

Code in contact-form

<form id="mayorInscriptionForm" class="mayor-inscription-form" action="#" method="POST" data-url="<?php echo admin_url('admin-ajax.php'); ?>">

    <div class="form-group">
        <input class="mayor-form-control" type="text" placeholder="Nombre y Apellidos" id="name" name="name">
        <small class="form-control-msg">Nombre y Apellidos requerido</small>
    </div>

    <div class="form-group">
        <input class="mayor-form-control" type="text" placeholder="Teléfono" id="phone" name="phone">
        <small class="form-control-msg">Teléfono requerido</small>
    </div>

    <div class="form-group">
    <input class="mayor-form-control" type="email" placeholder="Email" id="email" name="email">
    <small class="form-control-msg">Email requerido</small>
    </div>


    <div class="form-group">
    <textarea class="mayor-form-control" name="notes" id="notes" placeholder="Observaciones"></textarea>
    </div>

    <div class="text-center">
    <button type="submit" class="btn btn-submit btn-green uppercase">Enviar</button>

    <small class="form-info-loading form-control-msg js-form-submission">Procesando, por favor espere...</small>
    <small class="form-info-loading form-control-msg js-form-success">Mensaje Enviado</small>
    <small class="form-info-loading form-control-msg js-form-error">Ha ocurrido un problema, por favor intente m&aacute;s tarde.</small>
    </div>
</form>

code in main.js

$('#mayorInscriptionForm').on('submit', function(e){
    e.preventDefault();

    $('.error').removeClass('error');
    $('.js-show-feedback').removeClass('js-show-feedback');

    var form = $(this);
    var name = form.find('#name').val(),
        phone = form.find('#phone').val(),
        email = form.find('#email').val(),
        notes = form.find('#notes').val(),
        ajaxurl = form.data('url');

    if( name === '') {
        $('#name').parent('.form-group').addClass('error');

        return;
    }
    if( phone === '') {
        $('#phone').parent('.form-group').addClass('error');

        return;
    }
    if( email === '') {
        $('#email').parent('.form-group').addClass('error');

        return;
    }

    form.find('input, button, textarea').attr('disabled');

    $('.js-form-submission').addClass('js-show-feedback');


    $.ajax({

        url : ajaxurl,
        type: 'post',
        data : {
            name : name,
            phone : phone,
            email : email,
            notes : notes,
            action: 'mayor_save_user_inscription_form'
        },

        error : function( response ) {
            $('.js-form-submission').removeClass('js-show-feedback');
            $('.js-form-error').addClass('js-show-feedback');
            form.find('input, textarea, button').removeAttr('disabled');
        },

        success : function( response ) {
            if( response == 0 ) {

                setTimeout(function(){
                    $('.js-form-submission').removeClass('js-show-feedback');
                    $('.js-form-error').addClass('js-show-feedback');

                    form.find('input, textarea, button').removeAttr('disabled');
                },1500);

            }else {

                setTimeout(function(){
                    $('.js-form-submission').removeClass('js-show-feedback');
                    $('.js-form-success').addClass('js-show-feedback');

                    form.find('input, textarea, button').removeAttr('disabled').val('');
                },1500);

            }
        }
    });

code in ajax.php

function set_html_content_type() {
    return 'text/html';
}
add_filter( 'wp_mail_content_type', 'set_html_content_type');    
add_action( 'wp_ajax_nopriv_mayor_save_user_inscription_form', 'mayor_save_inscription');
add_action( 'wp_ajax_mayor_save_user_inscription_form', 'mayor_save_inscription');
function mayor_save_inscription() {

    $name = wp_strip_all_tags($_POST["name"]);
    $phone = wp_strip_all_tags($_POST["phone"]);
    $email = wp_strip_all_tags($_POST["email"]);
    $notes = wp_strip_all_tags($_POST["notes"]);

        $to = get_bloginfo( 'admin_email' ). "\r\n";
        $subject = 'Formulario de Inscripción - '.$name;
        $message = '<div>
        <p>Hola, hemos recibido una nueva inscripción a web, los detalles son:</p>
        </br>
        <p><b>De:</b> '.$name.', '.$email.'</p>
        <p><b>Teléfono:</b> '.$phone.'</p>
        <p><b>Observaciones:</b> '.$notes.'</p>
        </br>
        </br>
        <p>Gracias, web</p>

        </div>';


        $headers[] = 'From: <'.$to.'>';
        $headers[] = 'Reply-To: '.$title.' <'.$email.'>';
        $headers[] = 'Content-Type: text/html: charset=UTF-8';

        wp_mail($to, $subject, $message, $headers);

        $to2 = $email;
        $admin_email = get_bloginfo( 'admin_email' ). "\r\n";
        $subject2 = 'Confirmación Formulario Inscripcion web';
        $message2 = '<div>
        <p>Hola, hemos recibido tu inscripción a web, los detalles son:</p>
        </br>
        <p><b>De:</b> '.$name.', '.$email.'</p>
        <p><b>Teléfono:</b> '.$phone.'</p>
        <p><b>Observaciones:</b> '.$notes.'</p>
        </br>
        </br>
        <p>Gracias, web</p>

        </div>';

        $headers2[] = 'From: <'.$admin_email.'>';
        $headers2[] = 'Reply-To: <'.$admin_email.'>'; 
        $headers2[] = 'Content-Type: text/html: charset=UTF-8';

        wp_mail($to2, $subject2, $message2, $headers2);



    die();
}
0

jQuery AJAX will trigger an error event not only when it receives an HTTP status code indicating a problem with the request, but also if jQuery fails to parse the response body. Since you're using die() without sending any response body, it's likely that jQuery is choking on the "empty" response.

Using wp_send_json_success() instead of die() should alleviate the issue.

  // ...
  $success = wp_mail($to2, $subject2, $message2, $headers2);

  if( $success )
    wp_send_json_success( null, 200 );
  else
    wp_send_json_error( array( 'message' => 'We\'re sorry, your message could not be sent at this time. Please contact an administrator' ), 500 );
}

Also consider implementing check_ajax_referer() and using sanitization functions to increase the security of your form.

  • Hi, your answer works great, thank you! I have other questions: 1- should i remove the error message from de js file, and leave the one in the ajax file (Like: We/re sorry... ). And 2- about the sanitization functions: i'm using wp_strip_all_tags, do you recommend to use the sanitization function instead? or should i use both, in that case, how? sorry for all of this questions, i'm just a wordpress beginner and have a lot to learn. Thanks – Chefuss Apr 16 '17 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.