0

drupal_add_js works to pass variables from php to javascript, and there are plenty of examples. But I want the variable to update without a new page request.

I have a page request that kicks off some long-running code in the background (using background_batch and the Batch API), during which a variable is updated occasionally. When it changes, calling drupal_add_js again doesn't do anything. Then I tried to implement this but it doesn't seem to work either. I've use ajax with the Form API, but that is a specific request that returns to an element just once - this is going the other way (php to js ad-hoc).

Summarizing: How to push a php variable to be available in javascript at any point it time, from any Drupal code?

2

You have two options, depending on how responsive you need it to be, and how complex you're willing to get:

1) You can add Javascript to your page that will continually send AJAX requests to the server in the background, essentially asking for the value of that variable. You would achieve this by creating a new menu path with the sole purpose of serving the value of that variable in JSON. The JS that sits on the page could then be set up to ask for that variable every X seconds until it changes (or it could just keep doing it forever if you wanted).

2) You could write a separate Node.js application that runs on your server, which listens for updates to the variable from the background task and then pushes a notification to the JS in your page via websockets. That's obviously a lot more complex. But potentially more performant, and the updates would be instant. See this module for an example of a Node.js chat application: https://www.drupal.org/project/nodejs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.