Skip to content

Instantly share code, notes, and snippets.

@hasanTheBest
Last active October 30, 2019 05:56
Show Gist options
  • Save hasanTheBest/5f8304c1e550691874653dc204df6b8a to your computer and use it in GitHub Desktop.
Save hasanTheBest/5f8304c1e550691874653dc204df6b8a to your computer and use it in GitHub Desktop.
1. In functions.php file
=========================
if(condition){
wp_enqueue_script( 'handler', 'path', array(), 'version', boolean );
$ajax_url = admin_url('admin-ajax.php');
wp_localize_script('handler', 'object_name', array('data_1', => 'value_1') );
}
3. Hook data to built ajax.php
==============================
function callback_fucntion() {
if ( check_ajax_referer( 'action_name', 'nonce_value' ) ) {
$info = $_POST['info'];
echo strtoupper( $info );
die(); // Important
}
}
add_action( 'wp_ajax_{action_name}', 'callback_fucntion' ); // loged in user
add_action( 'wp_ajax_nopriv_{action_name}', 'callback_fucntion' ); // non loged in user ( We can define another function for the non logged in users )
2. In html file
====================
wp_nonce_field('ajaxtest');
3. In ajax.js file
====================
console.log(object_name.data_1); // retrieve ajax url
var info = $("#info").val();
var nonce = $("#_wpnonce").val();
$.post(object_name.data_1, {
action: "action_name", // important to keep in mind
info: info,
nonce_value:nonce
}, function (data) {
console.log(data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment