Using AJAX in WordPress

In the constructor of your PHP class add the following


In your enqueue function add the localize script function so you have a variable to use in the js file to call admin-ajax.php

		wp_enqueue_script('traffic-report', '/js/myjsfile.js', array('jquery'), '3.0');
		wp_localize_script('traffic-report', 'script_vars',array( 'AJAXurl' => admin_url( 'admin-ajax.php' ) ) );

Then add the callback functions to the same class

function send_email_test()
	//here do whatever you need to do with the data posted from the ajax call
	echo "ok";//anything that gets echo'd will resturn as the result in the javascript ajax function

Then in your js file add the following, assuming you have an element with an ID of #send_mail_test which you click on to call the AJAX request.

			url: script_vars.AJAXurl,
			method: "POST",
			data: {
				'action': 'send_email_test',//PHP function name to call
				'device': iDevice //Data to send to ajax function
			success: function (result)
				if (result)
					console.log("result is empty");