My WP Trek

Playing with WordPress

Quick Way of using AJAX in WordPress

This is a quick template that I repeatedly use while working with AJAX in WordPress.

 

In .js

$('body').on('click', '.some_element_class', function (e) {
    e.preventDefault(); 
    var ajaxdata = {}; 
    //Data that you're sending 
    ajaxdata.somedata = 'somedata'; 
    ajaxdata.action = 'your_action_name'; 
    $.ajax({ 
        beforeSend: function () { 
            //some work before sending data 
        }, 
        type: 'POST', 
        dataType: 'json', 
        url: ajaxscript.ajax_url, //ajax url 
        data: ajaxdata, 
        success: function (data) { 
        // some work after ajax success 
        }, 
        complete: function () { 
            // some work after ajax complete 
        } 
    }); 
});

 

In .php

$ajax_events = array( 
    'your_action_name' => 'your_function_to_call', 
); 
foreach ( $ajax_events as $ajax_event => $function ) { 
    add_action( 'wp_ajax_' . $ajax_event, $function ); 
    add_action( 'wp_ajax_nopriv_' . $ajax_event, $function ); 
} 
// Function ajax calls 
function your_function_call() { 
    if ( isset( $_POST['action'] ) && 'your_action_name' !== $_POST['action'] ) { 
        return; 
    } 
    // Do what you want to do 
    
    // return back with json data 
    echo wp_json_encode( 
        array( 
            'status' => 'good', 
            'msg' => __( 'Working Fine.', 'your_work_space' ),
         ) 
    ); 
    exit; 
}

 

 

Quick Way of using AJAX in WordPress

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top