Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Data parameter of a localized script in Wordpress

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));  
like image 318
Naourass Derouichi Avatar asked Oct 20 '15 23:10

Naourass Derouichi


1 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;
   }
});
like image 69
Naourass Derouichi Avatar answered Nov 19 '22 08:11

Naourass Derouichi