WordPress AJAX: a simple example without plugins

Written by 06.02.2019

Simple Wordpress AJAX call

Here is a quick and simple example of how you can use AJAX call in WordPress without a plugin. This can really help if you are stacked in a mess of big AJAX tutorials around WordPress.

AJAX call from your Java Script:

	jQuery(document).ready(function($){	
		$.post("<?php echo admin_url( 'admin-ajax.php' ); ?>",
			{	_ajax_nonce: "<?php echo wp_create_nonce( 'your_nonce' ); ?>",
				action: 'your_action',
				test: 'test text'
			}, 
			processData);
						
		function processData(data) {
			console.log( data );
		}
	});

PHP-part, placed in functions.php:

function test_ajax_script(){
	check_ajax_referer( 'your_nonce' );	
	if( $_POST['test'] == 'test text' ){
		echo 'AJAX works! Test text received!';
	}
	else {
		echo 'AJAX works! Test text was not received!';
	}
	wp_die();
}
add_action( 'wp_ajax_nopriv_your_action', 'test_ajax_script' );
add_action( 'wp_ajax_your_action', 'test_ajax_script' );

That’s it!

Cheers!

Leave a Reply

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