Home / WordPress Ajax request send and receive

WordPress Ajax request send and receive

Send request from HTML form

<form data-action="<?php echo get_site_url().'/wp-admin/admin-ajax.php'; ?>">
    <input type="hidden" name="action" value="ACTION_NAME_HERE">
    <input type="text" name="name">
    <button type="submit">Submit</button>
</form>

Receive request from below code

add_action('wp_ajax_ACTION_NAME_HERE', 'domain_search_results'); // Ajax actions for logged-in users.
add_action('wp_ajax_nopriv_ACTION_NAME_HERE', 'domain_search_results'); // Ajax actions for logged-out users
function domain_search_results(){
	extract($_POST);

	if(!$MsgError){
		$FormData = 'Sample output';
	}

	if ($MsgError) {
		$Return->MsgError = implode(', ', $MsgError);
	}
	if ($MsgSuccess) {
		$Return->MsgSuccess = $MsgSuccess;
	}
	if ($FormData) {
		$Return->FormData = $FormData;
	}
	
	echo ($Return)?json_encode($Return):'';
	die(); exit();
}

all rights reserved