I’m working on a child theme, In my-page-template.php
I have :
$id_curr= 5; //calculated value through code
wp_localize_script('my_js', 'ajaxload', array('post_id' => $id_curr));
In my_js.js
I have an AJAX call :
$.ajax({
//...
type: 'post',
data: {
action: 'ajax_load',
post_id: ajaxload.post_id
}
})
Now in functions.php
, I want to edit/update ajaxload.post_id
according to a new result. Is there a way to do that? If I try re-calling wp_localize_script()
with the same $name
as shown below, will this work?
$id_new= 8; //new calculated value
wp_localize_script('my_js', 'ajaxload', array('post_id' => $id_new));
After deep research, I venture to answer my question.
WordPress have the function
wp_send_json()
that allows to send a response back to an AJAX request. This function can updateajaxload.post_id
.In
functions.php
:In
my_js.js
:create an array with IDs.