How to send data via AJAX from frontend to backend in WordPress Plugin?

How to send data via AJAX from frontend to backend in WordPress Plugin?

Recently, i went into a problem where i had to create a form from the backend plugin without touching the theme and then pass that form data back to the plugin further processing. Here is how this can be achieved:

/* Firstly Add this code to your plugin and load the script file together with the AJAX URL */

function ajax_load_scripts() {
wp_enqueue_script( “ajax-test”, plugin_dir_url( __FILE__ ).’js/script.js’, array( ‘jquery’ ) );
wp_localize_script( ‘ajax-test’, ‘the_ajax_script’, array(‘ajaxurl’ => admin_url( ‘admin-ajax.php’ ) ) );
}
add_action(‘wp_ajax_test_response’, ‘ajax_load_scripts’);

Now open the script file and add the follow code:

function sendData() {
var data = {
action: ‘test_response’,
post_var: ‘response code to return’
};
jQuery.post(the_ajax_script.ajaxurl, data, function(response) {
alert(response);
});
}

In the plugin, add the following code to handle the response:

function ajax_process_request() {
if ( isset( $_POST[“post_var”] ) ) {
echo $_POST[“post_var”];
die();
}
}
add_action(‘wp_ajax_test_response’, ‘ajax_process_request’);

At the front end, you can have a form where you should send the data via jQuery using AJAX with the code mentioned above i.e sendData().

Hope this piece of snippet will help you handle the AJAX request over WordPress Plugin.