Categories
Web Development WordPress

WordPress: How to send an AJAX call with js to execute PHP

Several of the webpages and plugins that I have made with WordPress needed to update the database in some way or reference PHP on a button click. Since PHP and access to the database are run before page load, that seems impossible. This need to run PHP on as a response to user input when a button is pressed is exactly the case that an asynchronous AJAX call like the one I am about to show you comes in handy. Making this asynchronous call work is a multi-step process, but when it works it will do exactly what you want it to do.

First, in functions.php file, enqueue the script as normally but localize the script with a nonce which we will use for security purposes later:

wp_register_script( 'script', plugin_dir_url( __FILE__ ) . '/library/js/script.js', [ 'jquery' ], 'all', true );
wp_localize_script( 'script', 'cp_script', [
	'ajaxurl' => admin_url( 'admin-ajax.php' ),
] );
wp_enqueue_script( 'script' );

Then in the JQuery file, use create a handler for a user clicking a button and in the response include a $.ajax call, which is the asynchronous part. Also in the JQuery we are sending the AJAX to the ajax_url that we localized into the script and we also pass the nonce for use in the PHP for security purposes:

$( 'body' ).on( 'click', '.button_input', function() {	
	var data = {
		index: index,
		author: author,
		message: message,
		style: style,
	};
	
	
	$.ajax({
		type: 'POST',   // Adding Post method
		url: cp_script.ajaxurl, // Including ajax file
		data: {
		"action": "the_function",
		"data"   : data,
		"nonce": cp_script.nonce
	},
	success: function( response ) { // Show returned data using the function.
		console.log( response.data.message );
	
	}
	
        });
	
	
});

And finally in the PHP file, add both actions listed below with the prefixes wp_ajax_ and wp_ajax_nopriv for users of different types, define the function using the same name used in the JQuery and get any data sent from the JQuery from post variables. One of those bits of data is the nonce, it is used to verify that your code sent the command and not some malicious actor. From here you can update the WordPress database and then optionally send results of the update back to the JQuery:

add_action( 'wp_ajax_the_function', 'the_function' );
add_action( 'wp_ajax_noprivs_the_function', 'the_function' );
function the_function() {
// check the nonce to make sure the request came from a user of your code
check_ajax_referer( 'the_function', 'nonce')
// do whatever you want to update the database with PHP
$message = wp_unslash( sanitize_text_field( $_POST['data']) );
update_option( 'latest_message', data );
// optionally send data back to the JQuery that you got from the PHP
wp_send_json_success{ [
   'message'  => 'succeeded'
] );
}

Leave a Reply