Passing Variables from Javascript to Drupal/PHP
jazzdrive3 - July 26, 2009 - 07:13
What the best way to do this? I'm using a custom form to calculate a number with Jquery, and I need to pass this number for use in a Drupal module. Would a session variable do it?
Context: It's a custom price calculator for Ubercart. They enter weight and height, and they get the price, updated in real time on the page. But I need to do a module that hooks into the add_to_cart process that uses this custom price.
I am at a complete loss here.
Thanks!

I am not sure if there is
I am not sure if there is some standard way to do it. There are two ways that I can think to accomplish this (I have used both).
I thought about the form
I thought about the form idea. Do I just append or prepend the hidden input value html to the form element?
Would I then have access to that on hook functions for a module?
You just put the values that
You just put the values that you need into the hidden field. If you aren't sure how to use the Drupal form api, then you can look into it: http://api.drupal.org/api/file/developer/topics/forms_api.html. Just use the hidden field type. I don't know how any of your stuff is layed out to really help you much more than that.
Ok, but back to the orginal
Ok, but back to the orginal question. How do I get the Javascript variable passed to the form_alter function to add the hidden field to the form?
I can easily add a hidden field wth hook_form_alter. But to give it the value I want, what do I do? Is it ok to directly edit the HTML. That doesn't seem like a good solution to me.
I imagine I need to do something similar to what the uc_aac module is doing, but that code is doing so much more and it's hard to find the relevant areas.
Any help is appreciated.
Thanks!
Not quite clear on your
Not quite clear on your confusion.
In your form_alter function, add the additional hidden field to the form as well as an additional submit function that will get called when the form is submitted. Then your javascript will put the fields you need into the hidden field:
$('#edit-my-hidden-field').val('the-values-that-I-need');. Here is the general idea for the php code:<?php
/**
* Implementation of hook_form_alter()
**/
function example_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'form_id_searching_for') {
$form['my-hidden-field'] = array(
'#type' => 'hidden',
);
//Add the additional submit function in order to handle the added hidden field
$form['#submit'][] = 'example_my_hidden_field_submit';
}
}
/**
* Submit handler to store my-hidden-field
**/
function example_my_hidden_field_submit($form, &$form_state) {
//Probably your best bet is to put your values into the session
$_SESSION['my-values'] = $form_state['values']['my-hidden-field'];
}
?>
I am not sure if that is what you are looking for, but that is the basic idea of what you want to do I think.
Ok, that works. Thanks!
Ok, that works. Thanks!