Skip to content

Instantly share code, notes, and snippets.

@HDDen
Last active February 20, 2024 19:50
Show Gist options
  • Save HDDen/e57dbe01789b1aac29df18748328eee3 to your computer and use it in GitHub Desktop.
Save HDDen/e57dbe01789b1aac29df18748328eee3 to your computer and use it in GitHub Desktop.
js post wordpress ajax data
/**
* Cюда поместим отправляемые параметры
*/
var query = {
'action': 'loadMore',
'hdden_data': {
'posttype': 'news',
}
};
query.hdden_data.foo = 'bar';
/**
* Конверсия данных к отправке, action=loadMore&hdden_data[posttype]=news
*/
var xhr_query = [];
Object.keys(query.hdden_data).forEach(function(element){
xhr_query.push(
'hdden_data['+encodeURIComponent(element) + "]=" + encodeURIComponent(query.hdden_data[element])
)
});
var xhr_body = xhr_query.join("&");
// добавляем action
xhr_body = 'action='+query.action+'&'+xhr_body;
/**
* Отправка
*/
var xhr = new XMLHttpRequest();
// коллбэк
xhr.onload = function (){
var data = JSON.parse(this.responseText);
debug ? console.log('получен ответ ajax', data) : '';
}
xhr.onerror = function (){
}
// xhr.onreadystatechange = function () {
// if (this.readyState != 4) return;
// if (this.status == 200) {
// var data = JSON.parse(this.responseText);
// debug ? console.log('получен ответ ajax', data) : '';
// }
// };
xhr.open("POST", "url", true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(xhr_body);
<?php
add_action('wp_ajax_loadMore', 'hdden_loadMore');
add_action('wp_ajax_nopriv_loadMore', 'hdden_loadMore');
function hdden_loadMore(){
global $post;
// изымаем query
$hdden_data = [];
if (isset($_POST['hdden_data'])){
$hdden_data = $_POST['hdden_data'];
}
// отдаём ответ
$out = json_encode([
'foo' => 'aaa',
'bar' => 'bbb',
]);
echo $out;
wp_die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment