0

I am trying to work out a submit contact form through ajax but somehow i fail in process and i can't figure out, every combination i try it returns 0 for some reason.

This is my form

<form name="sentMessage" id="contactForm" novalidate>
            <div class="form-group wow fadeInUp">
                <input type="text" class="form-control" placeholder="Your Name *" id="name" name="name" required data-validation-required-message="Please enter your name.">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group wow fadeInUp">
                                <input type="email" class="form-control" placeholder="Your Email *" id="email" name="email" required data-validation-required-message="Please enter your email address.">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group wow fadeInUp">
                                <textarea class="form-control" placeholder="Your Message *" id="message" name="message" required data-validation-required-message="Please enter a message."></textarea>
                                <p class="help-block text-danger"></p>
                            </div>
                        <div class="clearfix"></div>
                        <div class="col-lg-12 wow fadeInUp">
                            <div id="success"></div>
                            <button type="submit" class="btn btn-danger btn-lg">Send Message</button>
                        </div>
                </form>

And this is the ajax script in included.

 $("input,textarea").jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {
        // additional error messages or events
    },
    submitSuccess: function($form, event) {
        event.preventDefault(); // prevent default submit behaviour
        // get values from FORM
        var name = $("input#name").val();
        var email = $("input#email").val();
        var message = $("textarea#message").val();
        var firstName = name; // For Success/Failure Message
        // Check for white space in name for Success/Fail message
        console.log(name + email + message);
        if (firstName.indexOf(' ') >= 0) {
            firstName = name.split(' ').slice(0, -1).join(' ');
        }
        var data = $form.serialize();
        console.log(data);
        $.ajax({
            url: ajax_contact.ajaxurl,
            dataType: 'json',
            action: 'ajax_contact',
            data: ajax_contact.data,
            cache: false,
            success: function(data) {
                console.log(data);
                if(data.status == "success") {
                    // Success message
                    $('#success').html("<div class='alert alert-success'>");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>");
                    $('#success > .alert-success').append("<strong>" + data.message + "</strong>");
                    $('#success > .alert-success').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                }
                if(data.status == "error") {
                    // Error message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>");
                    $('#success > .alert-danger').append("<strong>" + data.message + "</strong>");
                    $('#success > .alert-danger').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                }
            },
            error: function() {
                // Fail message
                $('#success').html("<div class='alert alert-danger'>");
                $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>");
                $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                $('#success > .alert-danger').append('</div>');
                //clear all fields
                $('#contactForm').trigger("reset");
            },
        })
    },
    filter: function() {
        return $(this).is(":visible");
    },
});

And i properly added to functions.php

function ajax_contact() {
try {
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) {
  throw new Exception('Bad form parameters. Check the markup to make sure you are naming the inputs correctly.');
}
if (!is_email($_POST['email'])) {
  throw new Exception('Email address not formatted correctly.');
}
$website_email = !empty(get_theme_option('contact_email')) ? get_theme_option('contact_email') : get_bloginfo('admin_email');
$subject = 'Website Contact Form from: '.$_POST['name'];
$headers = 'From: '.get_bloginfo('name').' Contact Form ' .$website_email;
$send_to = $website_email;
$subject = get_bloginfo('name') . " Contact Form: " .$_POST['name'];
$message = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: " . $_POST['name'] . "\n\nEmail: " . $_POST['email'] . "\n\nMessage:\n". $_POST['message'] . "";

if (wp_mail($send_to, $subject, $message, $headers)) {
  echo json_encode(array('status' => 'success', 'message' => 'Contact message sent.'));
  exit;
} else {
  throw new Exception('Failed to send email. Check AJAX handler.');
}
} catch (Exception $e) {
echo json_encode(array('status' => 'error', 'message' => $e->getMessage()));
exit;
}
die();
}
add_action( 'wp_ajax_ajax_contact', 'ajax_contact' );
add_action( 'wp_ajax_nopriv_ajax_contact', 'ajax_contact' );

function ajax_contact_js() {
wp_localize_script('ajax-contact', 'ajax_contact', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'ajax_contact_js');

And i also enqueued all the scripts that needed in separate function, so i don't get any errors and seems that everything is included and properly added but in function it fails somehow and i always get response 0.

  • A simple suggestion, but try print_r($_POST); at the beginning of the ajax_contact function to see if anything is coming back. If you see your posted data, then there's an issue with your if/else/try statements. Since you're seeing 0 come back I'm guessing the earlier if statements are throwing the exception but not returning any data to the ajax script. – Tom Aug 3 '17 at 7:47
  • @Tom it looks like function is not receiving anything from $_POST when i try to print_r i get empty array like none of inputs are caught, but that's confusing because if i do console.log(name) the ajax looks like it caught that input. – Aleksandar Đorđević Aug 3 '17 at 21:40
2

The action: 'ajax_contact' part in:

var data = $form.serialize();
console.log(data);
$.ajax({
    url: ajax_contact.ajaxurl,
    dataType: 'json',
    action: 'ajax_contact',
    data: ajax_contact.data,

is most likely the cause here, that your ajax request is failing.

Move the action part into the data set instead.

Since you're serializing the form data, you could try to add:

<input type="hidden" name="action" value="ajax_contact" />

into your form.

Also make sure the data attribute:

data: ajax_contact.data,

is getting the serialized data, but not the undefined ajax_contact.data.

You can try with manual json string instead for testing.

ps: also consider using nonce for extra security.

0

At the end i made it working like this.

<form name="sentMessage" id="contactForm" method="post" action="<?php echo admin_url('admin-ajax.php'); ?>" role="form" data-toggle="validator">
                            <div class="form-group wow fadeInUp">
                                <input type="text" class="form-control" placeholder="Your Name *" id="name" name="name" required data-error="Please enter your name.">
                                <div class="help-block with-errors text-danger"></div>
                            </div>
                            <div class="form-group wow fadeInUp">
                                <input type="email" class="form-control" placeholder="Your Email *" id="email" name="email" required data-error="Please enter your email address.">
                                <div class="help-block with-errors text-danger"></div>
                            </div>
                            <div class="form-group wow fadeInUp">
                                <textarea class="form-control" placeholder="Your Message *" id="message" name="message" required data-error="Please enter a message."></textarea>
                                <div class="help-block with-errors text-danger"></div>
                            </div>
                        <div class="clearfix"></div>
                        <div class="col-lg-12 wow fadeInUp">
                            <div id="success"></div>
                            <input type="hidden" name="action" value="ajax_contact" />
                            <?php wp_nonce_field( 'contact_nonce', 'contact_nonce' ); ?>
                            <button type="submit" class="btn btn-danger btn-lg">Send Message</button>
                        </div>
                </form>

As you can see on the form i added method to post and action to wordpress ajax url I also added hidden field with value to registered action hook and nonce field.

And in javascript file i changed to this

$('#contactForm').on('submit', function(e) {
    e.preventDefault();
    var $form = $(this);
    $.post( $form.attr('action'), $form.serialize(), 'json')
      .done(function( data ) {
          var response = JSON.parse(data);
          if(response.status == "success") {
            // Success message
            $('#success').html("<div class='alert alert-success'>");
            $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>");
            $('#success > .alert-success').append("<strong>" + response.message + "</strong>");
            $('#success > .alert-success').append('</div>');
            //clear all fields
            $('#contactForm').trigger("reset");
        } else if(response.status == "error") {
            // Error message
            $('#success').html("<div class='alert alert-danger'>");
            $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>");
            $('#success > .alert-danger').append("<strong>" + response.message + "</strong>");
            $('#success > .alert-danger').append('</div>');
            //clear all fields
            $('#contactForm').trigger("reset");
        } else {
            // Fail message
              $('#success').html("<div class='alert alert-danger'>");
              $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>");
              $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
              $('#success > .alert-danger').append('</div>');
              //clear all fields
              $('#contactForm').trigger("reset");
        }
      })
      .fail(function() {
          // Fail message
            $('#success').html("<div class='alert alert-danger'>");
            $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>");
            $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
            $('#success > .alert-danger').append('</div>');
            //clear all fields
            $('#contactForm').trigger("reset");
      });

The most important part was JSON.parse And function and registered hooks in .php file remain unchanged, only thing i added was check for nonce field.

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.