Skip to content

Instantly share code, notes, and snippets.

@josanua
Last active November 10, 2024 22:15
Show Gist options
  • Select an option

  • Save josanua/a1510d0acdc0487ba70f591f9d14b5eb to your computer and use it in GitHub Desktop.

Select an option

Save josanua/a1510d0acdc0487ba70f591f9d14b5eb to your computer and use it in GitHub Desktop.
wp ajax
<?php
https://wp-kama.ru/id_2018/ajax-v-wordpress.html
https://codex.wordpress.org/AJAX_in_Plugins
// Additional good resources
https://premium.wpmudev.org/blog/load-posts-ajax/
ajaxurl // variabila care este declarata global pe toate paginile de administrator,
// deobicei are valoare /wp-admin/admin-ajax.php
// aceasta variabila nu este declarata in template (thema) site-ului
// Enable error display in AJAX requests
if( WP_DEBUG && WP_DEBUG_DISPLAY && (defined('DOING_AJAX') && DOING_AJAX) ){
@ ini_set( 'display_errors', 1 );
}
// Error Return Values
1 - ошибка при проверке запроса. См. функцию check_ajax_referer()
0 - обработка запроса вернула пустой результат
0 - также возвращается по умолчанию во всех остальных случаях.
// Error Function Always Returns 0
If you’re getting a “0” as the response from an AJAX call in the admin, it’s most likely one of three things:
// WordPress can’t find the function you’ve hooked.
// You don’t have a wp_die() at the end of the PHP function.
// The action isn’t in the data you’re sending to the PHP function.
// Hook-urile necesare
// wp_ajax_(action_name) - use for JS script data send
add_action('wp_ajax_(action_name)', 'my_action_callback'); // Execute only for registered admin
add_action('wp_ajax_nopriv_(action_name)', 'my_action_callback'); // For front-end no-register execution
// Recomandat pentru ca sa se execute doar la cerere
if( wp_doing_ajax() ){
add_action('wp_ajax_myaction', 'ajax_handler');
add_action('wp_ajax_nopriv_myaction', 'ajax_handler');
function ajax_handler(){
wp_die(); // iesirea este necesara pentru ca functia sa returneze doar rezultat si nimic in plus, deobicei returneaza 0 sau 1
// In masura posibilitatii mereu sa utilizam wp_die() in loc de die() sau exit(),
// in functiile de prelucrarea cererilor AJAX, asa se obtine o integrare mai buna cu WP si in cazul erorilor
// v-om obtine date mai detaliate despre ele.
}
}
// --- Pasii necesari --- //
// Pentru Admin side
// 1. Intii adaugam pe pagina de admin JS Code care face cerere AJAX
add_action('admin_print_footer_scripts', 'my_action_javascript', 99);
function my_action_javascript() { ?>
<script>
// this script
jQuery(document).ready(function($) {
// console.log("Clicked form: " + formdata);
var data = {
action: 'my_action', // from wp_ajax_myaction
whatever: 1234
};
// с версии 2.8 'ajaxurl' всегда определен в админке
jQuery.post( ajaxurl, data, function(response) {
console.log('Server Response: ' + response);
});
console.log('Este script');
});
</script>
<?php
}
// Apoi cream functia care v-a prelucra cererea AJAX
add_action( 'wp_ajax_my_action', 'my_action_callback' ); // wp_ajax_my_action
function my_action_callback() {
$whatever = intval( $_POST['whatever'] );
// $whatever += 10;
echo $whatever;
wp_die(); // iesirea este necesara pentru ca functia sa returneze doar rezultat si nimic in plus
}
// --- AJAX in Front side --- //
// Create object for Front AJAX work's
// Declare variable for AJAX needs
add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data(){
// Первый параметр 'twentyfifteen-script' означает, что код будет прикреплен к скрипту с ID 'twentyfifteen-script'
// 'twentyfifteen-script' должен быть добавлен в очередь на вывод, иначе WP не поймет куда вставлять код локализации
// Заметка: обычно этот код нужно добавлять в functions.php в том месте где подключаются скрипты, после указанного скрипта
wp_localize_script( 'twentyfifteen-script', 'myajax',
array(
'url' => admin_url('admin-ajax.php')
)
);
}
// or my example (include in enqueue_scripts theme)
wp_localize_script('bootstrap-js', 'front_ajax',
array(
'url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('myajax-nonce')
)
);
// se poate de inclus in plugin
add_action( 'wp_enqueue_scripts', 'theme_scripts', 99 );
function theme_scripts(){
wp_localize_script( 'jquery', 'front_ajax_url', // jquery - script ID, front_ajax_url - object: front_ajax_url = {"url":"http://wptest.ru/wp-admin/admin-ajax.php"}
array(
'admin_ajax_url' => admin_url('admin-ajax.php')
)
);
}
// exemplu cu $.ajax pentru expediarea datelor
jQuery(document).ready( function(){
jQuery('#content').on('click', 'a.rml_bttn', function(e) {
e.preventDefault();
var rml_post_id = jQuery(this).data( 'id' );
jQuery.ajax({
url : readmelater_ajax.ajax_url,
type : 'post', // indica metoda de expediere GET sau POST
data : {
action : 'read_me_later',
post_id : rml_post_id
},
success : function( response ) {
jQuery('.rml_contents').html(response);
}
});
jQuery(this).hide();
});
});
// quick test, quick implementation, quick job, start in js
jQuery(document).ready(function($) {
$.ajax({
url: ajaxurl, // Provided by wp_localize_script
type: 'POST',
data: {
action: 'my_custom_action',
my_data: 'some_value'
},
success: function(response) {
console.log('Success:', response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('AJAX request failed:', textStatus, errorThrown);
console.error('Response Text:', jqXHR.responseText);
}
});
});
// PHP File:
// In your theme’s functions.php or a custom plugin, ensure you handle the AJAX request properly:
add_action('wp_ajax_my_custom_action', 'my_custom_action_callback');
add_action('wp_ajax_nopriv_my_custom_action', 'my_custom_action_callback');
function my_custom_action_callback() {
// Security check
check_ajax_referer('my_nonce_action', 'security');
// Handle the request and output result
$result = array("message" => "Hello, this is the response from server!");
wp_send_json_success($result); // correctly formatted JSON response
}
// Enqueue the Script:
function my_enqueue_scripts() {
wp_enqueue_script('my_custom_script', get_template_directory_uri() . '/js/my-custom-script.js', array('jquery'), null, true);
wp_localize_script('my_custom_script', 'ajax_object', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'security' => wp_create_nonce('my_nonce_action')
));
}
add_action('wp_enqueue_scripts', 'my_enqueue_scripts');
// Real example of custom plugin
/*
Plugin Name: Unsubscribe Newsletter
Version: 1.0
Author: Simpals Dev.
License: A "Slug" license name e.g. GPL2
*/
// Security reason of acces direct a file
defined('ABSPATH') or die('No script kiddies please!');
// Enable error display in AJAX requests
if (WP_DEBUG && WP_DEBUG_DISPLAY && (defined('DOING_AJAX') && DOING_AJAX)) {
@ ini_set('display_errors', 1);
}
// Create object for Front AJAX work's
add_action('wp_enqueue_scripts', 'theme_scripts', 99);
function theme_scripts() {
wp_localize_script('main-js', 'front_ajax',
array(
'url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('myajax-nonce')
)
);
}
// Initiate AJAX acctions on doing_ajax
if (wp_doing_ajax()) {
// Actions
add_action('wp_ajax_unsubscribe_user', 'callback_ajax_worker');
add_action('wp_ajax_nopriv_unsubscribe_user', 'callback_ajax_worker');
// AJAX Callback functions
function callback_ajax_worker()
{
if (!wp_verify_nonce($_POST['nonce_code'], 'myajax-nonce')) die( 'Stop executing code because of nonce value!' );
$personType = $_POST['personType'];
$personName = $_POST['personName'];
$personEmail = $_POST['personEmail'];
$organisationName = $_POST['organisationName'];
if( $organisationName != '') {
$showOrganisationName = " Organisation name: " . $organisationName;
} else {
$showOrganisationName = " ";
}
$personReason = $_POST['reason'];
if ( !$personEmail ) { die ( "Don't have a person email value" ); }
else {
$message = "Person Type: " . $personType . ", " . $showOrganisationName . ", Person Name:" . $personName . ", Email:" . $personEmail . ", Unsubscribe Reason: " . $personReason;
// $mail_sender_result = wp_mail( 'designwebmoldova@gmail.com', 'User Unsubscribe Notification ', $message );
}
ob_clean(); // trebuie de curatat buferul pentru a vedea erorile
echo $message;
wp_die();
}
}
// hui ego znaet daca-mi trebuie acest exemplu
// JS code in footer front page
add_action('wp_footer', 'footer_ajax_javascript', 99); // для фронта
function footer_ajax_javascript()
{ ?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
// Check selected fields
jQuery( "#person_type" ).change(function() {
// If organisation selected
if ( jQuery( '#person_type option:selected' ).val() == 'organisation' ){
jQuery('#organisation_name_field').css( 'display', 'block' );
jQuery('#subs_org_name').prop( 'required', true );
// $this.prop( "disabled", true );
}
// If person selected
if ( jQuery( '#person_type option:selected' ).val() == 'person' ) {
jQuery('#organisation_name_field').css('display', 'none');
jQuery('#subs_org_name').prop( 'required', false ).prop( 'disabled', true );
}
});
jQuery('#unsubscribe-form-button').on('click', function(e) {
let $this = jQuery(e.currentTarget);
e.preventDefault();
let personType = jQuery( '#person_type option:selected' ).val();
let personName = jQuery( '#subs_name' ).val();
let organisationName = '';
if ( jQuery('#subs_org_name').val()){
organisationName = jQuery('#subs_org_name').val();
}
let personEmail = jQuery( '#subs_email' ).val();
let reason = jQuery( '#subs_reason option:selected' ).val();
// console.log(personType + personName + personEmail + reason);
console.log("Forma s-a citit");
jQuery.ajax({
url: front_ajax.url,
type: 'post',
data: {
action: 'unsubscribe_user',
personType: personType,
personName: personName,
organisationName: organisationName,
personEmail: personEmail,
reason: reason,
nonce_code: front_ajax.nonce
},
complete: function (xhr) {
console.log('Response: ' + xhr.responseText);
},
success: function() {
$this.prop( "disabled", true );
jQuery('#unsubscribe-success-message').css("display", "block");
}
});
});
});
</script>
<?php
}
// clear from duplicates and reset counter, clear duplicates
$cleared_array = array_values(array_unique($all_tax_terms));
echo json_encode($cleared_array);
wp_die(); // this is required to terminate immediately and return a proper response
// --- AJAX in Front side, js scripts --- //
// with fetch API
// small example
fetch(ajaxurl, {
method: "post",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: "action=get_ids_count"
})
.then(res => res.json())
.then(data => console.log(data))
.catch(error => console.log(error));
// bigger example, fetch api example
fetch(ajaxurl +"?action=get_ids_count", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: "get_ids_count"
})
})
.then(function (response) {
fetch_status = response.status;
console.log('Response status');
console.log(fetch_status);
//return response.json();
})
.then(function (json) {
// Check if the response were success
if (fetch_status == 200) {
// Use the converted JSON
console.log(json);
}
})
.catch(function (error) {
// Catch errors
console.log('Error: ' + error);
});
// test AJAX in console
jQuery.ajax({
type: "GET",
// dataType: "json",
url: ajaxurl,
data: { action: "testRabbit" },
success: function (response) {
console.log("AJAX query executed");
console.log(response);
},
error: function(xhr, status, error) {
console.error("AJAX request failed:", status, error);
}
});
// js helper, debug, js debug helper, ajax front-implementation
jQuery.ajax({
url: ajaxurl,
type: 'GET',
data: {
action: 'recipe_plugin_dismiss_bf_banner',
},
// data: Your Data Here,
success: function(response) {
console.log('Success:', response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error:', textStatus, errorThrown);
console.log('Response Text:', jqXHR.responseText);
}
});
// helper function, list_all_ajax_hooks, list all ajax hooks, list ajax hooks
function list_all_ajax_hooks() {
global $wp_filter;
// Create an array to hold the AJAX hooks
$ajax_hooks = [];
// Loop through all hooks in $wp_filter
foreach ( $wp_filter as $hook => $value ) {
// Check for hooks that start with 'wp_ajax_' (for logged-in users)
if ( strpos( $hook, 'wp_ajax_' ) === 0 ) {
$ajax_hooks[] = $hook;
}
// Check for hooks that start with 'wp_ajax_nopriv_' (for non-logged-in users)
if ( strpos( $hook, 'wp_ajax_nopriv_' ) === 0 ) {
$ajax_hooks[] = $hook;
}
}
// Output the registered AJAX hooks
if ( ! empty( $ajax_hooks ) ) {
echo '<pre>';
print_r( $ajax_hooks );
echo '</pre>';
} else {
echo 'No AJAX hooks found.';
}
}
// Use this function to display the list in the admin dashboard or a template
add_action( 'admin_footer', 'list_all_ajax_hooks' );
// code example in case of click function, click btn
// php
add_action('wp_ajax_recipe_plugin_dismiss_bf_banner', 'dismiss_black_friday_banner');
function dismiss_black_friday_banner() {
update_user_meta( get_current_user_id(), 'inspiro_dismiss_black_friday_banner', true );
wp_send_json_success();
}
// js
jQuery(document).ready(function () {
jQuery(document).on('click', '#wpzoom-bf-banner-container button.notice-dismiss', function (e) {
console.log('clicked: ' + e.target);
jQuery.ajax({
url: ajaxurl,
type: 'GET',
data: {
action: 'recipe_plugin_dismiss_bf_banner',
},
// data: Your Data Here,
success: function(response) {
console.log('Success:', response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error:', textStatus, errorThrown);
console.log('Response Text:', jqXHR.responseText);
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment