2

I am trying to send a value in JavaScript variable to Drupal. I am calling an external js file in hook_nodeapi(). I want to send a value from this external js file to Drupal, and want to use this value in Drupal in hook_block.
For example

hook_nodeapi() {
  // call(external.js)
}
external.js
var sendData =10;

hook_block
{
  case view:
  // need to access sendData value
}

I tried this using cookies, but I think that is not the best way. How can this be done?

1

2 Answers 2

1

Let's look at what the client can do as an alternative to setting a cookie:

  1. Make an AJAX request that lets the server store the variable.
  2. Add the variable name and value to the query string of every internal link and to every form submission (not just the next one).

I do not see any benefits of Solution 1, that justifies the extra HTTP request. Especially, you cannot circumvent the necessity for the user to have Cookies enabled, because the value must be stored close to the user and Drupal uses Cookies exclusively to determine the session (and thus the user).

Solution 2 allows for different values within the same session. If this is not one of your requirements, I consider this solution too much of a hassle.

3
  • 1
    Nice analysis. But your conclusion is flawed: Adding a query parameter to all links and form-submissions is a lot more complex: What about other AJAX-requests? What about the time it takes the browser to walk through all links? … All in all the first option seems to be less complex, more reliable. The JavaScript wants to tell the server something so it should do it right away. Jul 28, 2012 at 13:43
  • 1
    I know solution 2 is complicated. That's why I did not endorse it. When I say "benefits of solution 1", I mean benefits compared to settings a cookie.
    – Oswald
    Jul 28, 2012 at 15:10
  • Ok sorry for the misunderstanding. Jul 29, 2012 at 12:17
0

You can check below code to get base path value from js variable.

$settings = drupal_add_js(null, null);

$base_path = $settings['settings']['data'][0]['basePath'];

drupal_add_js() function will return the array of the JavaScript variable. You can trace the array in PHP and can get the value of required variable.

1
  • 1
    The settings array won't contain variables that are set in external JS files, so this won't solve the problem.
    – Jesse
    May 21, 2014 at 8:32

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