WP AJAX API with JS file

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
    
}