ajax is working

This commit is contained in:
asus
2024-02-10 12:05:50 +01:00
parent 4e18b21406
commit 0b2e6352e1
2 changed files with 30 additions and 9 deletions

View File

@@ -6,13 +6,23 @@ sendButton.addEventListener('click', () => {
const myurl = php_data.ajax_url;
console.log(myurl);
const data = new FormData();
data.append('action', 'get_data',);
data.append('_ajax_nonce', php_data.nonce);
data.append('data', inputValue);
fetch(myurl, {
method: 'POST',
credentials: 'same-origin',
body: JSON.stringify({
action: 'get_data',
_ajax_nonce: php_data.nonce,
data: inputValue,
})
body: data
})
.then((response) => response.json())
.then((data) => {
console.log("data: ");
console.log(data);
})
.catch((error) => {
console.log("error: ");
console.log(error);
});
});

View File

@@ -80,7 +80,6 @@ add_shortcode('wp_model_plugin', 'main_shortcode');
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
menu plugin
ajax : https://stackoverflow.com/questions/43557755/how-to-call-ajax-in-wordpress
*/
function plugin_menu() {
add_menu_page(
@@ -93,10 +92,22 @@ function plugin_menu() {
}
add_action('admin_menu', 'plugin_menu');
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
ajax
- https://stackoverflow.com/questions/43557755/how-to-call-ajax-in-wordpress
- in `add_action( 'wp_ajax_get_data', 'my_ajax_handler' );`
the 'wp_ajax_get_data' is a hooks formated as 'wp_ajax_{$action}'
the `$action` param is passed in the data object of the ajax call
- to access the content of the data object properties of the ajax call :
use $_POST['property_name']
*/
function my_ajax_handler() {
console_log("in my_ajax_handler");
console_log("data: ");
console_log($data);
error_log("test");
error_log($_POST['data']);
wp_send_json_success( 'It works' );
}
add_action( 'wp_ajax_get_data', 'my_ajax_handler' );