using wp_localize instead of wp_add_line for ajax
This commit is contained in:
@@ -1,17 +1,15 @@
|
||||
/*
|
||||
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
|
||||
function that create an ajax post action
|
||||
it can be "overloaded" with a callback_response and _error
|
||||
*/
|
||||
function ajax_post(ajax_data, action, callback_response, callback_error) {
|
||||
console.log("in ajac_post, ajax_data :");
|
||||
console.log(ajax_data);
|
||||
const data = new FormData();
|
||||
data.append('action', action);
|
||||
data.append('_ajax_nonce', nonce);
|
||||
data.append('_ajax_nonce', wp_ajax._nonce);
|
||||
data.append('data', ajax_data);
|
||||
console.log("data: ");
|
||||
console.log(data);
|
||||
|
||||
fetch(ajax_url, {
|
||||
fetch(wp_ajax._url, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
body: data
|
||||
|
||||
@@ -5,11 +5,15 @@
|
||||
/*
|
||||
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
|
||||
function that add the ajax script to front
|
||||
needs to check if already included :
|
||||
no real needs to check if already included :
|
||||
- $handle is uniq so it will not be re-enqueued
|
||||
the first enqueued version would be kept
|
||||
- but the vars add to front would be added twice
|
||||
- if we used add_var_to_front() (which use wp_add_inline_script())
|
||||
the vars would be added twice
|
||||
leading to js syntaxe error (redeclaraiton of 'let' or 'const')
|
||||
- but we use wp_localize_script() so the object will be overwritten
|
||||
it's not a real pbm
|
||||
(what is more efficient, check for double or overwritte object ?)
|
||||
*/
|
||||
function add_ajax_post() {
|
||||
global $first_script;
|
||||
@@ -17,22 +21,22 @@ function add_ajax_post() {
|
||||
|
||||
$file = init_file($ajax_file);
|
||||
|
||||
// check if ajax script was already enqueued
|
||||
global $wp_scripts;
|
||||
$already_enqueued = array_search($file->handle, $wp_scripts->queue);
|
||||
if ($already_enqueued !== false)
|
||||
return ;
|
||||
// // check if ajax script was already enqueued
|
||||
// global $wp_scripts;
|
||||
// $already_enqueued = array_search($file->handle, $wp_scripts->queue);
|
||||
// if ($already_enqueued !== false)
|
||||
// return ;
|
||||
|
||||
$first_script = $file->handle;
|
||||
wp_enqueue_script( $file->handle, $file->url, $previous_js_basename, $file->version, true);
|
||||
$ajax_url = admin_url( 'admin-ajax.php' );
|
||||
$nonce = wp_create_nonce( 'wp-pageviews-nonce' );
|
||||
add_var_to_front(
|
||||
compact(
|
||||
"ajax_url",
|
||||
"nonce",
|
||||
)
|
||||
);
|
||||
|
||||
$_url = admin_url( 'admin-ajax.php' );
|
||||
$_nonce = wp_create_nonce( 'wp-pageviews-nonce' );
|
||||
$vars = compact("_url","_nonce",);
|
||||
// add_var_to_front($vars);
|
||||
$object_name = "wp_ajax";
|
||||
wp_localize_script($file->handle, $object_name, $vars);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user