0

So I am having a hard time trying to set my contact form working on a theme I am building.

It uses JqBootstrapValidation plugin.

Someone told me that the reason this is not working is because WP is not being loaded when js is calling via AJAX the contact-me.php file. So, if someone could implement the WP AJAX API on this, I would be very grateful, cause I don´t have a clue.

BTW, the JS file is working great. Fields are being validated and I am getting a succes message on sending form.

Here is the Js code:

(function($) {

$("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 theme path
    var stylesheet_directory_uri = ContactMe_uri.templateUrl;
    // get values from FORM
    var name = $("input#name").val();
    var email = $("input#email").val();
    var subject = $("input#subject").val();
    var message = $("textarea#message").val();
    var firstName = name; // For Success/Failure Message
    // Check for white space in name for Success/Fail message
    if (firstName.indexOf(' ') >= 0) {
        firstName = name.split(' ').slice(0, -1).join(' ');
    }
    $.ajax({
        url: stylesheet_directory_uri+"/inc/contact-me.php",
        type: "POST",
        data: {
            name: name,
            subject: subject,
            email: email,
            message: message
        },
        cache: false,
        success: function() {
            // 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>Your message has been sent. </strong>");
            $('#success > .alert-success')
                .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 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");
},
});

$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});  
}(jQuery)); 
/*When clicking on Full hide fail/success boxes */
jQuery('#name').focus(function() {
jQuery('#success').html('');
}); 
  • Is this frontend or backend? – David Gard Feb 20 '15 at 15:10
1

Currently I'm assuming that is is backend (front end is slightly different), but it's very easy to implement on the frontend if required.

You are correct in thinking that because you haven't used the WordPress admin-ajax.php file, all the goodness of WordPress is missing. Fortunately this is easily fixed.

Before continuing I recommend that you take a look at the following -

And just in case you are wondering why I have reloaed .error with .fail, please not this from the docs for the jQuery.post() function -

Deprecation Notice - The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.


JS

You'll notice that WP users jQuery.post() as opposed to jQuery.ajax(). Because of that, you don't have to explicitly declare a success function, as the 3rd parameter replicates that function.

You'll also notice that there is no explicit path to your PHP declared. Instead we add the action key to the data object. You'll see below in the PHP how this works.

var data = {
    action:  'my_ajax_action',
    name:    name,
    subject: subject,
    email:   email,
    message: message
}

var jqxhr = $.post(ajaxurl, data, function(response) { // This is the 'success' function

    // 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>Your message has been sent. </strong>");
    $('#success > .alert-success')
        .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 mail server is not responding. Please try again later!");
    $('#success > .alert-danger').append('</div>');
    //clear all fields
    $('#contactForm').trigger("reset");

});

PHP

Your PHP now has to be slighty different as well. You can place this in either functions.php, or any independant PHP file that is included by functions.php.

Basically you add an action to execute your code inside a function as below.

add_action('wp_ajax_my_ajax_action', 'my_ajax_action_callback');
function my_ajax_action_callback() {

    echo 'It works!';
    wp_die();   // This is required for a proper result

}
  • David, first thanks for being helpful. I could not understand your question abour frontend or backend. The form is here: vcvivo.com.br/bootfreela . 1) Should I substitute all my js code for yours? 2) should I tranport all code inside current inc/contact-me.php file to the my_ajax_action_callbackfunction you provide? 3) is the wp_die() just for testing purposes? Sorry, but I am very newbie on this. – Luis Rock Feb 20 '15 at 16:17
  • And by the way, if you need to see my entire code, check this question I posted before: wordpress.stackexchange.com/questions/178792/… – Luis Rock Feb 20 '15 at 16:21
  • @LuisRock - Frontend - Your website, the bit all visitors are able to see. Backend - the admin area. 1) JS - the code posted replaces your $.ajax() function. 2) PHP - from the looks of it, yes (but I can't be 100% sure). 3) wp_die() - this is always required at the end of a WP AJAX function. Hope that helps. – David Gard Feb 21 '15 at 18:42
  • Well, we are talking about a contact form that will show to all visitors. You said your code was related to backend. So what is the version to the frontend? – Luis Rock Feb 22 '15 at 12:23

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.