How to pass jquery variable to drupal (ajax)

14,808

Solution 1

Passing the variable data from JavaScript to Drupal/PHP is one thing. Passing the information from Drupal/PHP to JavaScript is another separate thing. I think that you meant the first one in your question. So I'll go ahead and answer that.

Passing variables from JavaScript to Drupal/PHP

1) Implement a menu hook. You can do that on an existing contributed or new custom module, it depends what you are doing. It's pretty easy and straight forward, it is also well documented on the Drupal site.

  $items = array();

  $items['my_custom_callback/%'] = array(
    'title' => 'My Custom Callback', 
    'description' => 'Listing of blogs.', 
    'page callback' => 'my_custom_php_function', 
    'page arguments' => array(1),
    'access arguments' => array('access content'), 
    'type' => MENU_CALLBACK,
  );

Let's break down the example above.

$items['my_custom_callback/%']

$items is just an array, and it can be named anything you like. If the URL of my website is www.alexanderallen.name, then http://www.alexanderallen.name/my_custom_callback would be the resource that I would call from my JavaScript application.

In the array's key, the percentage symbol after the word my_custom_callback is a placeholder. This is where you will pass your data from JS to PHP. So if the value of variable x is 10, the call from your JQuery will look like this:

http://www.alexanderallen.name/my_custom_callback/10

When you load that URL, Drupal will find your menu hook, and it will call the function you defined in the 'page callback' array key. In this case that would be:

<?php
/**
* Function that gets called from JQuery asynchronously. 
*/
function my_custom_php_function($argument) {
  // Do something with $argument...
  echo $argument;
}
?>

There you can do anything you want with the value of variable x, like storing it in the database.

If you were to put the menu hook on a custom module, and the name of your module were example_module, the menu hook and custom PHP callback would look like this:

<?php
/**
* @file example_module.module Handles fancy AJAX functionality.
* 
*/

/**
* Implementation of hook_menu
*
* @see http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_menu/6
*/
function example_module_menu() {
  $items = array();

  $items['my_custom_callback/%'] = array(
    'title' => 'My Custom Callback', 
    'description' => 'Listing of blogs.', 
    'page callback' => 'my_custom_php_function', 
    'page arguments' => array(1),
    'access arguments' => array('access content'), 
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
* Function that gets called from JQuery asynchronously. 
*/
function my_custom_php_function($argument) {
  // Do something with $argument...
  echo $argument;
}

?>

If you wanted to pass multiple variables from JQuery to Drupal/PHP, you could consider JSONifying them in JavaScript, before passing it to PHP. Remember that if the payload is very large you should consider JQuery .post() instead of .get(). The PHP functions for decoding JSON are here on php.net.

Don't forget to return $items at the end of the example_module_menu() function. If you wanted to pass two or more arguments from JavaScript to PHP then the menu item would look similar to this:

function example_module_menu() {
  $items = array();

  $items['my_custom_callback/%/%/%'] = array(
    'title' => 'My Custom Callback', 
    'description' => 'Listing of blogs.', 
    'page callback' => 'my_custom_php_function', 
    'page arguments' => array(1, 2, 3),
    'access arguments' => array('access content'), 
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function my_custom_php_function($arg1, $arg2, $arg3) {
  // Do something ...
  $sum = $arg2 + $arg3;

  echo "Hi". $arg1 .", X + Z = ". $sum;
}

?>

In this case I am passing three arguments to PHP. 'page arguments' specifies the part of the URL that you want to pass to PHP. If you were to write 'page arguments' => array(0),, then the argument to your PHP function would be the string my_custom_callback.


2) Call the menu hook from your JS code using JQuery. JQuery provides various AJAX methods. Which one you use will depend on the format of the data your dealing with and it's size, amongst other things.

Most likely you will use one of two JQuery methods. .post() or .get(), bearing in mind that that post requests will allow for a bigger data payload than get requests. So if the size of variable x = 10, you might want to stick with .get(). Both .post() and .get() methods are an extension of, or rely on the .ajax() method. The .ajax() method is more flexible because it provides you with more options, like the ability to specify the format of the data (JSON or plain-text), send a username/password along with your request, choose between synchronous or asynchronous requests, and whether the browser should cache or not the request.

This is the method signature for the JQuery .get() method:

jQuery.get( url, [ data ], [ callback(data, textStatus, XMLHttpRequest) ], [ dataType ] )

If you were going to send your data using GET to Drupal/PHP, using the example above you could do something like this:

    <script type='text/javascript'>
    var name = 'alexander';  
    var x = 10;
    var z = 20;

    $.get( 
      // Callback URL.
      "http://www.alexanderallen.name/my_custom_callback/"+ name +"/"+ x +"/"+ z
    );

    </script>

Note that the usage of the data argument on the .get() method is optional, and in my example I omitted it, but achieved the same effect by concatenating the data to pass to Drupal/PHP with the rest of the URL.

If I were to run that, the HTTP GET request would look like:

http://www.alexanderallen.name/my_custom_callback/alexander/10/20

and the response would look like:

Hi Alexander, X + Z = 30

Passing data from Drupal to JavaScript

For that then you would use Behaviors, I am not entering into details since I think that wasn't your question, but you can go to the official documentation for Drupal 6 behaviors here.

Solution 2

You need to know:

The menu API:
http://api.drupal.org/api/drupal/includes--menu.inc/group/menu/7
Some Drupal JSON functions (maybe)
http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_json_encode/7
variable_set()
http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/variable_set/7
And jQuery ajax API:
http://api.jquery.com/category/ajax/

Essentially, you need to create a menu item that delegates to a callback (be careful with your permissions) and then call it with $.ajax(). If you need to do something with the response, see the json_encode functionality.

You might want to take a look here for some menu examples:
http://drupal.org/project/examples

I think there is a Drupal interface to the jQuery ajax API. Perhaps someone can comment if they know a better way.

Share:
14,808

Related videos on Youtube

Drupal_newbie
Author by

Drupal_newbie

Updated on June 04, 2022

Comments

  • Drupal_newbie
    Drupal_newbie almost 2 years

    I want to pass

    var x = 10; to drupal/php variable $x without page refresh.

    Can anyone suggest?


    Thank you so much for reply. Actually I am developing custom module for E commerce site(Drupal 6). On product page, I have 4 attributes as text field (Width inch, width foot, height inch, height foot) By doing some calculation I got new price for that product. I did that calculation in j query. Now I alter "uc_add_to_cart_form" and add 1 hidden field and get jquery new price into that hidden field using $_SESSION. Upto this point everything is working fine.

    I want to save this new price to product node. I am not able set this new price to $node->price. I am using uc_ajax_cart for "Add to cart" button.

    Can anyone please suggest me how can I proceed?

    • Berdir
      Berdir about 13 years
      The question doesn't make much sense. Please extend the question and explain what you are trying to do. In short, there is no point assigning a value to a $var unless you are doing something with that $var. The variable and everything else will be gone after the request is finished.

Related