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 update ajaxload.post_id
.
In functions.php
:
$return = array('post_id' => $id_new);
wp_send_json($return);
In my_js.js
:
$.ajax({
type: 'post',
data: {
action: 'ajax_load',
post_id: ajaxload.post_id
},
success:function(data) {
var result = $.parseJSON(data);
ajaxload.post_id = result.post_id;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With