nervewax
6/26/2018 - 1:04 PM

WP Admin AJAX

WP Admin AJAX

<?php
function ajax_example() {

  check nonce

  if nonce is wrong {
    json error
    die
  }

  do function {
    response
  }

  if response is empty {
    json error
  }

  json send back response

  die();
}
add_action( 'wp_ajax_admin_ajax_example', 'admin_ajax_example' );
add_action( 'wp_ajax_admin_ajax_example', 'admin_ajax_example' );

function enqueues() {
  ajax_url
  ajax_nonce

  localize both
}
?>
$.ajax ({
	type: post,
	url: ajax_url,
	data: {
		action: 'ajax_example',
		nonce: ajax_nonce,
		other: 'other things'
	},

	success: function (result) {

	},

	error: function (error) {

	}
});
<div id="ajax-example">
</div>