Skip to content

Instantly share code, notes, and snippets.

@guytzhak
Created September 3, 2017 15:42
Show Gist options
  • Save guytzhak/1fd21424e8a3751bb327444842208faf to your computer and use it in GitHub Desktop.
Save guytzhak/1fd21424e8a3751bb327444842208faf to your computer and use it in GitHub Desktop.
$( 'body' ).on( 'click', '.my_ajax_btn', function(e){
e.preventDefault();
var first_name = 'Guy';
var last_name = 'Ytzhak';
var role = 'CEO';
jQuery.ajax({
url: sp_ajaxify.ajax_url,
type: 'post',
data: {
action: 'my_custom_name_function', // function name from php
first_name: first_name, // variable that send with your request
last_name: last_name, // כנל
role: role, // כנל
},
beforeSend: function () {
console.log('this run before send data to server');
},
success: function (response) {
var data = jQuery.parseJSON( response );
// המשתנה DATA
// מכיל בעצם את מה שחוזר מהשרת בפורמט ג'ייסון אחרי שהוא עבר המרה למערך ג'אווה סקריפט
console.log(data);
},
error: function (errorThrown) {
alert(errorThrown);
}
});
});
// הגדרת הנתיב לקובץ JS
// בנוסף גם יצירה של משתנה עבור הכתובת לפעולה של האג'קס
wp_enqueue_script( 'theme-ajax-js', get_stylesheet_directory_uri() .'/js/ajax_sample.js', array('jquery'), '1.0', true );
wp_localize_script( 'theme-ajax-js', 'sp_ajaxify', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
));
// הגדרת הפונקציה בוורדפרס לגישה דרך אג'קס
add_action( 'wp_ajax_my_custom_name_function', 'my_custom_name_function' );
add_action( 'wp_ajax_nopriv_my_custom_name_function', 'my_custom_name_function' );
function my_custom_name_function() {
// for example
if( isset( $_POST['first_name'] ) && !empty( $_POST['first_name'] ) ) {
$first_name = sanitize_text_field( $_POST['first_name'] );
} else {
$first_name = '';
}
if( isset( $_POST['last_name'] ) && !empty( $_POST['last_name'] ) ) {
$last_name = sanitize_text_field( $_POST['last_name'] );
} else {
$last_name = '';
}
if( isset( $_POST['role'] ) && !empty( $_POST['role'] ) ) {
$role = sanitize_text_field( $_POST['role'] );
} else {
$role = '';
}
$var = array (
'first_name' => $first_name,
'last_name' => $last_name,
'role' => $role,
);
$response = $var;
echo json_encode($response);
wp_die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment