/    Sign up×
Community /Pin to ProfileBookmark

Passing javascript var to php?

Hi Guys.
Im using a joomla plugin for my forms and another plugin to update a column in sql once a button is pressed.
When a row is slected a button is pressed the user is given a prompt ‘enter a reason’.
I need to pass this reason to php so that it can be stored in a table.

The javascript works fine but i need to get the users reason (var y) accross to the update_col.php script.

THE JAVASCRIPT:

[CODE]var fbTableUpdateCol = FbTablePlugin.extend({

initialize: function(tableform, options, lang) {

this.setOptions(tableform, options);

this.lang = Object.extend({‘selectrow’:’Please select a row!’}, lang || {});

window.addEvent(‘domready’, function() {

this.tableid = this.tableform.getElement(‘input[name=tableid]’).value;

this.watchButton();

}.bind(this));

},

watchButton:function() {

var button = this.tableform.getElement(‘input[name=’+this.options.name+’]’);

if(!button) {

return;

}

button.addEvent(‘click’, function(event) {

var e = new Event(event);

e.stop();

var ok = false;

this.tableform.getElements(‘input[name^=ids]’).each(function(c) {

if(c.checked) {
var y=window.prompt(“please enter a reason”)
if (y!=null && y!=””) {
ok = true;
} else {
ok = ‘noreason’;
return;
}
}
});

if(ok == false) {

alert(this.lang.selectrow);

return;

} else if(ok == ‘noreason’) {

return;
}

this.tableform.getElement(‘input[name=fabrik_tableplugin_name]’).value = ‘update_col’;

this.tableform.getElement(‘input[name=fabrik_tableplugin_renderOrder]’).value = button.name.split(‘-‘).getLast();

oPackage.submitfabrikTable(this.tableid, ‘doPlugin’);

}.bind(this));

}

});[/CODE]

to post a comment
JavaScript

12 Comments(s)

Copy linkTweet thisAlerts:
@adamckauthorFeb 15.2011 — UPDATE_COL.PHP
[CODE]<?php

/**
* Add an action button to the table to copy rows
* @package Joomla
* @subpackage Fabrik
* @author Rob Clayburn
* @copyright (C) Rob Clayburn
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

//require the abstract plugin class
require_once(COM_FABRIK_FRONTEND.DS.'models'.DS.'plugin-table.php');
require_once(COM_FABRIK_FRONTEND.DS.'helpers'.DS.'html.php');
require_once(COM_FABRIK_FRONTEND.DS.'helpers'.DS.'parent.php');

class FabrikModelUpdate_col extends FabrikModelTablePlugin {

var $_counter = null;

var $_buttonPrefix = 'update_col';

var $_sent = 0;

var $_notsent = 0;

var $_row_count = 0;

/**
* Constructor
*/

function __construct()
{
parent::__construct();
}

function button()
{
return "update records";
}

function button_result($c )
{
$params =& $this->getParams();
if ($this->canUse()) {
$name = $this->_getButtonName();
return "<input type="button" name="$name" value="". $params->get('button_label', 'update') . "" id="$id" class="button tableplugin"/>";
}
}

/**
* (non-PHPdoc)
* @see FabrikModelTablePlugin::getAclParam()
*/

function getAclParam()
{
return 'updatecol_access';
}

/**
* determine if the table plugin is a button and can be activated only when rows are selected
*
* @return bol
*/

function canSelectRows()
{
$params =& $this->getParams();
$access = $params->get('updatecol_access');
$name = $this->_getButtonName();
$canuse = FabrikWorker::getACL($access, $name);
return $canuse;
}

/**
* do the plugin action
* @param object parameters
* @param object table model
*/

function process(&$params, &$model, $opts = array())
{
$db =& $model->getDb();
$user =& JFactory::getUser();
$updateTo = $params->get('update_value');
$updateCol = $params->get('coltoupdate');
// $$$ rob moved here from bottom of func see http://fabrikar.com/forums/showthread.php?t=15920&page=7
$tbl = array_shift(explode('.', $updateCol));
$dateCol = $params->get('update_date_element');
$userCol = $params->get('update_user_element');

$db->setQuery("SELECT * FROM #__fabrik_joins WHERE table_id = " . (int)$model->_id);
$joins = (array)$db->loadObjectList();

$table =& $model->getTable();
// array_unique for left joined table data
$ids = array_unique(JRequest::getVar('ids', array(), 'method', 'array'));
$this->_row_count = count($ids);
$ids = implode(',',$ids);
$model->_pluginQueryWhere[] = $table->db_primary_key . ' IN ( '.$ids.')';
$data =& $model->getData();

//$$$servantek reordered the update process in case the email routine wants to kill the updates
$emailColID = $params->get('update_email_element', '');
if (!empty($emailColID)) {
$w = new FabrikWorker();
jimport('joomla.mail.helper');
$message = $params->get('update_email_msg');
$subject = $params->get('update_email_subject');
$eval = $params->get('eval', 0);
$config =& JFactory::getConfig();
$from = $config->getValue('mailfrom');
$fromname = $config->getValue('fromname');
$elementModel =& JModel::getInstance('element', 'FabrikModel');
$elementModel->setId($emailColID);
$emailElement =& $elementModel->getElement(true);
$emailField = $elementModel->getFullName(false, true, false);
$emailColumn = $elementModel->getFullName(false, false, false);
$emailFieldRaw = $emailField . '_raw';
$emailWhich = $emailElement->plugin == 'fabrikuser' ? 'user' : 'field';
$db =& JFactory::getDBO();
$aids = explode(',', $ids);
// if using a user element, build a lookup list of emails from jos_users,
// so we're only doing one query to grab all involved emails.
if ($emailWhich == 'user') {
$userids_emails = array();
$query = 'SELECT #__users.id AS id, #__users.email AS email FROM #__users LEFT JOIN ' . $tbl . ' ON #__users.id = ' . $emailColumn . ' WHERE ' . $table->db_primary_key . ' IN ('.$ids.')';
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ($results as $result) {
$userids_emails[(int)$result->id] = $result->email;
}
}
foreach ($aids as $id) {
$row = $model->getRow($id);
if ($emailWhich == 'user') {
$userid = (int)$row->$emailFieldRaw;
$to = $userids_emails[$userid];
}
else {
$to = $row->$emailField;
}

if (JMailHelper::cleanAddress($to) && JMailHelper::isEmailAddress($to)) {
//$tofull = '"' . JMailHelper::cleanLine($toname) . '" <' . $to . '>';
//$$$servantek added an eval option and rearranged placeholder call
$thissubject = $w->parseMessageForPlaceholder($subject, $row);
$thismessage = $w->parseMessageForPlaceholder($message, $row);
if ($eval) {
$thismessage = JDEBUG ? eval($thismessage) : @eval($thismessage);
}
$res = JUtility::sendMail( $from, $fromname, $to, $thissubject, $thismessage, true);
if ($res) {
$this->_sent ++;
} else {
$$this->_notsent ++;
}
} else {
$this->_notsent ++;
}
}
}
//$$$servantek reordered the update process in case the email routine wants to kill the updates
if (!empty($dateCol)) {
$datetbl = array_shift(explode('.', $dateCol));
$this->_process($datetbl, $model, $joins, " $dateCol = NOW() ");
}

if (!empty($userCol)) {
$usertbl = array_shift(explode('.', $userCol));
$this->_process($usertbl, $model, $joins, " $userCol = ". (int)$user->get('id'));
}
$this->_process($tbl, $model, $joins, "$updateCol = ".$db->Quote($updateTo));

return true;
}

function process_result($c)
{
$params =& $this->getParams();
$msg = $params->get('update_message', '');

if (empty($msg)) {
$msg = JText::sprintf('&#37;d ROWS UPDATED, %d EMAILS SENT', $this->_row_count, $this->_sent);
}
else {
$msg = JText::sprintf($msg, $this->_row_count, $this->_sent);
}
// $$$ rob moved msg processing to process() as for some reason we
//have incorrect plugin object here (where as php table plugin's process_result()
//has correct params object - not sure why that is :(
return $msg;
}

/**
*
* @param string table name to update
* @param object $model table
* @param array $joins objects
* @param string $update sql statement (x=y)
*/

private function _process($tbl, &$model, &$joins, $update)
{
$db =& $model->getDb();
$nav =& $model->getPagination(1, 0, 1);

$data = $model->getData();
// $$$ rob dont unshift as this messes up for grouped data
//$data = array_shift($data);
$table =& $model->getTable();

$ids = JRequest::getVar('ids', array(), 'method', 'array');
JArrayHelper::toInteger($ids);
$ids = implode(',', $ids);
$dbk = $k = $table->db_primary_key;
$db_table_name = $table->db_table_name;
$db->setQuery("UPDATE $db_table_name SET $update WHERE $dbk IN ($ids)");
$db->query();

// if the update element is in a join replace the key and table name with the
// join table's name and key
foreach ($joins as $join) {
if ($join->table_join == $tbl) {
$db->setQuery('DESCRIBE '.$tbl);
$fields = $db->loadObjectList('Key');
$k = $tbl.'___'.$fields['PRI']->Field;
$dbk = $tbl.'.'.$fields['PRI']->Field;
$db_table_name = $tbl;
$ids = array();
foreach ($data as $groupdata) {
foreach ($groupdata as $d) {
$v = $d->{$k.'_raw'};
if ($v != '') {
$ids[] = $v;
}
}
}
if (!empty($ids)) {
$ids = implode(',', $ids);
$db->setQuery("UPDATE $db_table_name SET $update WHERE $dbk IN ($ids)");
$db->query();
}
}
}

//$db->setQuery("UPDATE $db_table_name SET $update WHERE $dbk IN ($ids)");
//$db->query();
}

/**
* load the javascript class that manages interaction with the form element
* should only be called once
* @return string javascript class file
*/

function loadJavascriptClass()
{
FabrikHelperHTML::script('javascript.js', 'components/com_fabrik/plugins/table/update_col/', false);
}

/**
* return the javascript to create an instance of the class defined in formJavascriptClass
* @param object parameters
* @param object table model
* @param array [0] => string table's form id to contain plugin
* @return bool
*/

function loadJavascriptInstance($params, $model, $args )
{
$form_id = $args[0];
$opts = new stdClass();
$opts->name = $this->_getButtonName();
$opts = FastJSON::encode($opts);
$lang = $this->_getLang();
$lang = FastJSON::encode($lang);
$this->jsInstance = "new fbTableUpdateCol('$form_id', $opts, $lang)";
return true;
}

/* function _getColName()
{
$params = $this->getParams();
$col = $params->get('coltoupdate');
return $col.'-'.$this->renderOrder;
}*/

/* function _getButtonName()
{
//$$$ hugh - for some reason, _getColName() screws up because getParams() returns the wrong params.
// and as we don't seem to use the col name from the button name, lets skip it ...
//return $this->_buttonPrefix ."-" . $this->_getColName();
return parent::_getButtonName();
}*/

/**
* show a new for entering the form actions options
*/

function renderAdminSettings( $elementId, &$row, &$params, $lists, $c )
{
$params->_counter_override = $this->_counter;
$display = ($this->_adminVisible) ? "display:block" : "display:none";
$return = '<div class="page-' . $elementId . ' elementSettings" style="' . $display . '">
' . $params->render('params', '_default', false, $c) .
'</div>
';
$return = str_replace("r", "", $return);
return $return;
}

}
?>
[/CODE]
Copy linkTweet thisAlerts:
@KorFeb 15.2011 — You can not "pass a JavaScript variable to PHP" just like that. You need to [I]submit[/I] that variable to a page which contains a PHP code which will retrieve it as a POST variable. Or use AJAX, to avoid the changing of the session, which, in fact, means a submit query process as well.
Copy linkTweet thisAlerts:
@adamckauthorFeb 15.2011 — This already does that.

Upon clicking the button the javascript runs, if i enter a reason and continue, the php does run and the sql update does happen.

Im guessing the lines:

[B]this.tableform.getElement('input[name=fabrik_tableplugin_name]').value = 'update_col';[/B]

[B]oPackage.submitfabrikTable(this.tableid, 'doPlugin');[/B]

Gets the php file and runs it?

The php file is called[B] update_col[/B].php

So if i can set the value of something, then retrieve it in the php script then my problem is gone.

But the javascript definately runs the php script on success.

Adam.
Copy linkTweet thisAlerts:
@KorFeb 15.2011 — hard to say, as long as your code there is not written in native JavaScript, but probably are custom methods of a JavaScript Framework which you omitted to specify. Is it JQuery? If so, it might be a JQuery problem.
Copy linkTweet thisAlerts:
@adamckauthorFeb 15.2011 — Ok so ive managed to pass something accross to the php and run the sql update.

But... having issue with changing an hidden inputs value to my variable?

[CODE] this.tableform.getElements('input[name^=ids]').each(function(c) {

if(c.checked) {
var reason=window.prompt("please enter a reason")
if (reason!=null && reason!="") {
ok = true;
} else {
ok = 'noreason';
return;
}
}
});


if(ok == false) {

alert(this.lang.selectrow);

return;

} else if(ok == 'noreason') {

return;
}

this.tableform.getElement('input[name=fabrik_tableplugin_Reason]').value = reason;[/CODE]


When i set this:
[CODE]this.tableform.getElement('input[name=fabrik_tableplugin_Reason]').value = reason;[/CODE]

It fails...

When i set this (to test it)
[CODE]this.tableform.getElement('input[name=fabrik_tableplugin_Reason]').value = 'reason';[/CODE]

It works but it enter the word 'reason' into the table not the reason variable from the prompt box.

How do i get around this?

Ive tried:

.value = '' + reason;

.value = '' + reason + '';

.value = reason;

.value =reason;

Any help?
Copy linkTweet thisAlerts:
@KorFeb 15.2011 — What that getElement() custom method supposes to do? Once again, are you conscious that method is a custom one, not part of the native JavaScript syntax? Unless you tell us what you are using (JQuery, MooTools, Prototype, other?) we can not help you. It should be a matter of that framework's syntax.
Copy linkTweet thisAlerts:
@adamckauthorFeb 15.2011 — Hi,

Sorry its hard to explain it as i didnt write it either and its not easy getting help from the creators.

I now seem to have the script working fine, but ive met an annoying bug in IE which is ignoring the return; and just continuing with the code.

[CODE]this.tableform.getElements('input[name^=ids]').each(function(c) {

if(c.checked) {
name = prompt("Enter a reason", "");
if (name!=null && name!="") {
ok = true;
} else {
return;
}
}
});[/CODE]


Any ideas why?

Works fine in FF, when i try it in IE it pops up asking for the input, i click cancel and it continues with the code that is after this script hence ignoring my [B][I]return;[/I][/B]

Thanks in advance!
Copy linkTweet thisAlerts:
@KorFeb 15.2011 — Hi,

Sorry its hard to explain it as i didnt write it either and its not easy getting help from the creators.[/QUOTE]

Without knowing what is beneath those codes it is impossible to understand what happens.
Copy linkTweet thisAlerts:
@adamckauthorFeb 15.2011 — As above... i have now managed to pass the variable and it all works perfectly in FF & IE except for IE not stopping the code running when it should.

The full javascript is only...

[CODE]var fbTableUpdateCol = FbTablePlugin.extend({

initialize: function(tableform, options, lang) {

this.setOptions(tableform, options);

this.lang = Object.extend({'selectrow':'Please select a row!'}, lang || {});

window.addEvent('domready', function() {

this.tableid = this.tableform.getElement('input[name=tableid]').value;

this.watchButton();

}.bind(this));

},



watchButton:function() {

var button = this.tableform.getElement('input[name='+this.options.name+']');

if(!button) {

return;

}

button.addEvent('click', function(event) {

var e = new Event(event);

e.stop();

var ok = false;

this.tableform.getElements('input[name^=ids]').each(function(c) {

if(c.checked) {
name = prompt("Enter a reason", "");
if (name != null && name != "") {
ok = true;
} else {
ok = 'noreason';
return;
}
}
});


if(ok == false) {

alert(this.lang.selectrow);

return;

} else if(ok == 'noreason') {

return;
}

this.tableform.getElement('input[name=fabrik_tableplugin_Reason]').value = name;
this.tableform.getElement('input[name=fabrik_tableplugin_name]').value = 'update_col';

this.tableform.getElement('input[name=fabrik_tableplugin_renderOrder]').value = button.name.split('-').getLast();



oPackage.submitfabrikTable(this.tableid, 'doPlugin');

}.bind(this));

}

});[/CODE]


And its only this part that doesnt stop running (upon promp box cancel i want it to stop everything)

[CODE]this.tableform.getElements('input[name^=ids]').each(function(c) {

if(c.checked) {
name = prompt("Enter a reason", "");
if (name != null && name != "") {
ok = true;
} else {
ok = 'noreason';
return;
}
}
});[/CODE]
Copy linkTweet thisAlerts:
@adamckauthorFeb 15.2011 — Just tried this tutorial code in FF and IE and IE performs the same ignoring the If and else and just runs even when the prompt variable is null.

http://www.globalguideline.com/JavaScript_Guide/JavaScript_Examples.php?JScript=JavaScript_Prompt_Box

Try running that page in IE and FF and you will see the promp say guest when you cancel in FF and say Null when you cancel in IE!
Copy linkTweet thisAlerts:
@KorFeb 15.2011 — change the variable [B]name[/B] into, say, [B]var n[/B]
Copy linkTweet thisAlerts:
@adamckauthorFeb 15.2011 — I tried that before and when i did it worked ok but it wouldnt allow me to change the value of the fabrik_tableplugin_reason to n;

So i have added

var name = null;

before the prompt and this seems to have fixed it ?

Thanks for your help ?
×

Success!

Help @adamck spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...