Home » Php » php – Update Data parameter of a localized script in WordPress

php – Update Data parameter of a localized script in WordPress

Posted by: admin July 12, 2020 Leave a comment

Questions:

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));  
How to&Answers:

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;
   }
});

Answer:

create an array with IDs.

$ids = array( 5, 8 );
foreach ( $ids as $id ) {
    wp_localize_script('my_js', 'ajaxload', array('post_id' => $id));
}