Woocommerce Variations Radio buttons - javascript

I had the hooks below that's working perfectly to change the Products variations select to radio buttons while creating variations using custom attributes.
I added new products variations using the Global Attributes but it seems that the hook is not compatible with it.
am looking for a way to make it compatible with both since I already have 200 products using the custom attributes and want to start using global attributes for the new products.
function variation_radio_buttons($html, $args)
{
$args = wp_parse_args(apply_filters('woocommerce_dropdown_variation_attribute_options_args', $args) , array(
'options' => false,
'attribute' => false,
'product' => false,
'selected' => false,
'name' => '',
'id' => '',
'class' => '',
'show_option_none' => __('Choose an option', 'woocommerce') ,
));
if (false === $args['selected'] && $args['attribute'] && $args['product'] instanceof WC_Product)
{
$selected_key = 'attribute_' . sanitize_title($args['attribute']);
$args['selected'] = isset($_REQUEST[$selected_key]) ? wc_clean(wp_unslash($_REQUEST[$selected_key])) : $args['product']->get_variation_default_attribute($args['attribute']);
}
$options = $args['options'];
$product = $args['product'];
$attribute = $args['attribute'];
$name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title($attribute);
$id = $args['id'] ? $args['id'] : sanitize_title($attribute);
$class = $args['class'];
$show_option_none = (bool)$args['show_option_none'];
$show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __('Choose an option', 'woocommerce');
$label = wc_attribute_label($args['attribute'], $args['product']);
if (empty($options) && !empty($product) && !empty($attribute))
{
$attributes = $product->get_variation_attributes();
$options = $attributes[$attribute];
}
$html = '<select id="' . esc_attr($id) . '" class="d-none ' . esc_attr($class) . '" name="' . esc_attr($name) . '" data-attribute_name="attribute_' . esc_attr(sanitize_title($attribute)) . '" data-show_option_none="' . ($show_option_none ? 'yes' : 'no') . '">';
$html .= '<option value="">' . esc_html($show_option_none_text) . '</option>';
if (!empty($options))
{
if ($product && taxonomy_exists($attribute))
{
// Get terms if this is a taxonomy - ordered. We need the names too.
$terms = wc_get_product_terms($product->get_id() , $attribute, array(
'fields' => 'all'
));
foreach ($terms as $term)
{
if (in_array($term->slug, $options))
{
$html .= '<option value="' . esc_attr($term->slug) . '" ' . selected(sanitize_title($args['selected']) , $term->slug, false) . '>' . esc_html(apply_filters('woocommerce_variation_option_name', $term->name)) . '</option>';
}
}
}
else
{
foreach ($options as $option)
{
// This handles < 2.4.0 bw compatibility where text attributes were not sanitized.
//$selected = sanitize_title( $args['selected'] ) === $args['selected'] ? selected( $args['selected'], sanitize_title( $option ), false ) : selected( $args['selected'], $option, false );
//if (sanitize_title($option) == $current){
//$selected = 'selected';
//}
$selected = '';
$html .= '<option value="' . esc_attr($option) . '" ' . $selected . '>' . esc_html(apply_filters('woocommerce_variation_option_name', $option)) . '</option>';
}
}
}
$html .= '</select>';
$radios = '<div class="radio-group">';
if (!empty($options))
{
if ($product && taxonomy_exists($attribute))
{
$terms = wc_get_product_terms($product->get_id() , $attribute, array(
'fields' => 'all',
));
foreach ($terms as $term)
{
if (in_array($term->slug, $options, true))
{
$radios .= '<input id="' . strtolower($option) . '" type="radio" name="' . esc_attr($name) . '" value="' . esc_attr($term->slug) . '" onClick="jQuery("#' . esc_attr($name) . '").val(' . esc_attr($term->slug) . ').trigger("change");" ' . checked(sanitize_title($args['selected']) , $term->slug, false) . '><label for="' . esc_attr($term->slug) . '">' . esc_html(apply_filters('woocommerce_variation_option_name', $term->name)) . '</label>';
}
}
}
else
{
foreach ($options as $option)
{
// $checked = sanitize_title($args['selected']) === $args['selected'] ? checked($args['selected'], sanitize_title($option), false) : checked($args['selected'], $option, false);
//if (sanitize_title($option) == $current){
//$checked = 'checked="checked"';
//}
$checked = '';
$radios .= '<input id="' . strtolower(sanitize_title($option)) . '" type="radio" name="' . esc_attr($name) . '" value="' . esc_attr($option) . '" id="' . sanitize_title($option) . '" onClick="changeTrigger(\'#' . strtolower($attribute) . '\',\'' . esc_attr($option) . '\',\'' . esc_attr($label) . '\');" ' . $checked . '><label for="' . sanitize_title($option) . '">' . esc_html(apply_filters('woocommerce_variation_option_name', $option)) . '</label>';
$allAttribute[] = strtolower($attribute);
}
}
}
$radios .= '</div>';
return $html . $radios;
}
add_filter('woocommerce_dropdown_variation_attribute_options_html', 'variation_radio_buttons', 20, 2);
function variation_check($active, $variation)
{
if (!$variation->is_in_stock() && !$variation->backorders_allowed())
{
return false;
}
return $active;
}
add_filter('woocommerce_variation_is_active', 'variation_check', 10, 2);
if (!function_exists('shop_attributes_in_loop'))
{
function shop_attributes_in_loop()
{
global $product;
//Getting product attributes
$product_attributes = $product->get_attributes();
if (!empty($product_attributes))
{
//Getting product attributes slugs
$product_attribute_slugs = array_keys($product_attributes);
?>
<script>
function resetAttr(c,d){
var attr = c;
jQuery('input[name=attribute_'+c+']').attr('disabled',false);
jQuery('input[name=attribute_'+c+']').attr('checked',false);
jQuery('#' + c + '-selected').html('');
jQuery('#' + c + '-section').removeClass('d-none');
jQuery('#' + c + ' option[value=""]').prop('selected', true);
if(d){
jQuery('#' + c).trigger('change');
}
<?php
foreach ($product_attribute_slugs as $product_attribute_slug)
{
$attribute_name = str_replace('pa_', '', $product_attribute_slug); // Removing "pa_" from attribute slug
//echo 'jQuery(\'#'.$attribute_name.'\').trigger(\'change\');';
?>
var allvalues = [];
jQuery('select#<?php echo $attribute_name; ?>').find('option').each(function() {
if(jQuery('select#<?php echo $attribute_name; ?>').val() == ""){
if(jQuery(this).attr('disabled', false)){
var theValue = jQuery(this).val();
allvalues.push(theValue);
}
}
});
jQuery('input[name="attribute_<?php echo $attribute_name; ?>"]').each(function () {
var theRadio = jQuery(this).val();
var check = allvalues.includes(theRadio);
if(check == false){
jQuery(this).attr('disabled', true);
}else{
jQuery(this).attr('disabled', false);
}
});
<?php
}
?>
}
function changeTrigger(a,b,c){
a = a.replace(/\s+/g, "-");
jQuery(a + ' option[value="' + b + '"]').prop('selected', true);
jQuery(a + '-selected').html('<div class="selected-variable"><span>'+c.replace(/#/, "").toUpperCase()+': '+b+' </span><a class="var-del" onClick="resetAttr(\''+a.replace(/#/, "")+'\',true)"><div class="close-x"></div></a></div>');
jQuery(a + '-section').addClass('d-none');
jQuery('input[name=attribute_'+a.replace(/#/, "")+']').attr('disabled',true);
jQuery(a).trigger('change');
<?php
foreach ($product_attribute_slugs as $product_attribute_slug)
{
$attribute_name = str_replace('pa_', '', $product_attribute_slug); // Removing "pa_" from attribute slug
//echo 'jQuery(\'#'.$attribute_name.'\').trigger(\'change\');';
?>
var allvalues = [];
jQuery('select#<?php echo $attribute_name; ?>').find('option').each(function() {
if(jQuery('select#<?php echo $attribute_name; ?>').val() == ""){
resetAttr('<?php echo $attribute_name; ?>',false);
/*jQuery('input[name=attribute_<?php echo $attribute_name; ?>]').attr('checked',false);*/
if(jQuery(this).attr('disabled', false)){
var theValue = jQuery(this).val();
allvalues.push(theValue);
}
}
});
jQuery('input[name="attribute_<?php echo $attribute_name; ?>"]').each(function () {
var theRadio = jQuery(this).val();
var check = allvalues.includes(theRadio);
if(check == false){
jQuery(this).attr('disabled', true);
}else{
//jQuery(this).attr('disabled', false);
}
});
<?php
}
echo "}</script>";
}
}
}
add_action('woocommerce_before_add_to_cart_button', 'shop_attributes_in_loop');

Related

How can I get similar count of data

I want to get set if statement of no. of count of array from database. I already have a if statement checking the count but I am unable to use it in my file.
Help me replicate the count if statement here. I want to wrap pro_type and is_pro in if statement of no. of counts similar in reaferandearn page .
My function where I need if count statement :
users.php file
public function update_valid_refer_point($id){
global $db;
$user_balance = $db->where('id',$id)
->getOne('users',array('balance'));
$_POST['pro_type'] =4;
$_POST['is_pro'] =1;
$bal =$user_balance['balance']+500;
$updated = $db->where('id', $id)
->update('users', array('pro_type' => 4,'is_pro' => 1,'balance' => $bal));
return TRUE;
}
The file where I have similar if count statement but I have no idea how to use it above :
referandearn.php
if(count($data['refferal_data']['data']) > 0){
for($u=0; $u<count($data['refferal_data']['data']);$u++){
$userFirstName = $data['refferal_data']['data'][$u]->first_name;
$userLastName = $data['refferal_data']['data'][$u]->last_name;
$userName = $userFirstName.' '.$userLastName;
$userProfilePhoto = $data['refferal_data']['data'][$u]->avater;
$refferalDate = date('d - M - Y',strtotime($data['refferal_data']['data'][$u]->refferalDate));
$userRefferalCode = $data['refferal_data']['data'][$u]->refferalCode;
?>
<li>
<img src="<?php echo $userProfilePhoto;?>" width="75" height="75" viewBox="0 0 24 24" style="margin-right: 15px; border-radius: 50%;"/>
<?php echo $userName."<br>".$refferalDate;?>
</li>
<?php
}
}else{
?>
<li>
<?php echo 'No reffered user yet';?>
</li>
<?php
}
?>
referandearn controller :
Class Referearn extends Theme {
public static function LoadreffralUsers() {
global $_AJAX, $_CONTROLLERS;
$data = '';
$ajax_class = realpath($_CONTROLLERS . 'aj.php');
$ajax_class_file = realpath($_AJAX . 'loadmore.php');
if (file_exists($ajax_class_file)) {
require_once $ajax_class;
require_once $ajax_class_file;
$_POST['page'] = 1;
$loadmore = new Loadmore();
$refferal_users = $loadmore->refferal_users();
parent::$data['refferal_data'] = $refferal_users;
/*if (isset($refferal_users['html'])) {
$data = $refferal_users['html'];
}*/
}
return $data;
}
}
And loadmore referusers function :
function refferal_users() {
global $db, $_BASEPATH, $_DS,$_excludes;
if (self::ActiveUser() == NULL) {
return array(
'status' => 403,
'message' => __('Forbidden')
);
}
$error = '';
$page = 0;
$perpage = 7;
$html = '';
$html_imgs = '';
$template = '';
if (isset($_POST) && !empty($_POST)) {
if (isset($_POST[ 'page' ]) && (!is_numeric($_POST[ 'page' ]) || empty($_POST[ 'page' ]))) {
$error = '<p>• ' . __('no page number found.') . '</p>';
} else {
$page = (int) Secure($_POST[ 'page' ]) - 1;
}
}
if ($error == '') {
$limit = $perpage;
$offset = $page * $perpage;
//$query = GetRefferalUserQuery(self::ActiveUser()->id, $limit, $offset);
//exit;
//$refferal_users = $db->rawQuery($query);
$sql = 'SELECT U.id,U.online,U.lastseen,U.username,U.avater,U.country,U.first_name,U.last_name,U.location,U.birthday,U.language,U.relationship,U.height,U.body,U.smoke,U.ethnicity,U.pets,U.gender, RU.refferalDate, RU.refferalCode FROM users U INNER JOIN refferalusers RU ON RU.refferalBy = U.id ';
$sql .= ' WHERE RU.refferalTo = '.self::ActiveUser()->id.' AND ( ';
$sql .= ' U.verified = "1" AND U.privacy_show_profile_random_users = "1" ';
// to exclude blocked users
$notin = ' AND U.id NOT IN (SELECT block_userid FROM blocks WHERE user_id = '.self::ActiveUser()->id.') ';
// to exclude liked and disliked users users
$notin .= ' AND U.id NOT IN (SELECT like_userid FROM likes WHERE ( user_id = '.self::ActiveUser()->id.' OR like_userid = '.self::ActiveUser()->id.' ) ) ';
$sql .= ' ) ';
$sql .= ' ORDER BY U.id DESC LIMIT '.$limit.' OFFSET '.$offset.';';
$random_users = $db->objectBuilder()->rawQuery($sql);
$theme_path = $_BASEPATH . 'themes' . $_DS . self::Config()->theme . $_DS;
//$template = $theme_path . 'partails' . $_DS . 'find-matches' . $_DS . 'random_users.php';
//$template1 = $theme_path . 'partails' . $_DS . 'find-matches' . $_DS . 'matches_imgs.php';
if (file_exists($template)) {
foreach ($random_users as $random_user) {
if($random_user->id!=(int)auth()->id){
ob_start();
require($template);
$html .= ob_get_contents();
ob_end_clean();
}
}
}
return array(
'status' => 200,
'page' => $page + 2,
'html' => $html,
'data' => $random_users
);
} else {
return array(
'status' => 400,
'message' => $error
);
}
}

How to call similar variables in php

I want to get set if statement of no. of count of array from database. I already have a if statement checking the count but I am unable to use it in my file.
Help me replicate the count if statement here. I want to wrap pro_type and is_pro in if statement of no. of counts similar in reaferandearn page .
My function where I need if count statement :
users.php file
public function update_valid_refer_point($id){
global $db;
$user_balance = $db->where('id',$id)
->getOne('users',array('balance'));
$_POST['pro_type'] =4;
$_POST['is_pro'] =1;
$bal =$user_balance['balance']+500;
$updated = $db->where('id', $id)
->update('users', array('pro_type' => 4,'is_pro' => 1,'balance' => $bal));
return TRUE;
}
The file where I have similar if count statement but I have no idea how to use it above :
referandearn.php
if(count($data['refferal_data']['data']) > 0){
<?php
}>
referandearn controller :
Class Referearn extends Theme {
public static function LoadreffralUsers() {
global $_AJAX, $_CONTROLLERS;
$data = '';
$ajax_class = realpath($_CONTROLLERS . 'aj.php');
$ajax_class_file = realpath($_AJAX . 'loadmore.php');
if (file_exists($ajax_class_file)) {
require_once $ajax_class;
require_once $ajax_class_file;
$_POST['page'] = 1;
$loadmore = new Loadmore();
$refferal_users = $loadmore->refferal_users();
parent::$data['refferal_data'] = $refferal_users;
/*if (isset($refferal_users['html'])) {
$data = $refferal_users['html'];
}*/
}
return $data;
}
}
And loadmore referusers function :
function refferal_users() {
global $db, $_BASEPATH, $_DS,$_excludes;
if (self::ActiveUser() == NULL) {
return array(
'status' => 403,
'message' => __('Forbidden')
);
}
$error = '';
$page = 0;
$perpage = 7;
$html = '';
$html_imgs = '';
$template = '';
if (isset($_POST) && !empty($_POST)) {
if (isset($_POST[ 'page' ]) && (!is_numeric($_POST[ 'page' ]) || empty($_POST[ 'page' ]))) {
$error = '<p>• ' . __('no page number found.') . '</p>';
} else {
$page = (int) Secure($_POST[ 'page' ]) - 1;
}
}
if ($error == '') {
$limit = $perpage;
$offset = $page * $perpage;
//$query = GetRefferalUserQuery(self::ActiveUser()->id, $limit, $offset);
//exit;
//$refferal_users = $db->rawQuery($query);
$sql = 'SELECT U.id,U.online,U.lastseen,U.username,U.avater,U.country,U.first_name,U.last_name,U.location,U.birthday,U.language,U.relationship,U.height,U.body,U.smoke,U.ethnicity,U.pets,U.gender, RU.refferalDate, RU.refferalCode FROM users U INNER JOIN refferalusers RU ON RU.refferalBy = U.id ';
$sql .= ' WHERE RU.refferalTo = '.self::ActiveUser()->id.' AND ( ';
$sql .= ' U.verified = "1" AND U.privacy_show_profile_random_users = "1" ';
// to exclude blocked users
$notin = ' AND U.id NOT IN (SELECT block_userid FROM blocks WHERE user_id = '.self::ActiveUser()->id.') ';
// to exclude liked and disliked users users
$notin .= ' AND U.id NOT IN (SELECT like_userid FROM likes WHERE ( user_id = '.self::ActiveUser()->id.' OR like_userid = '.self::ActiveUser()->id.' ) ) ';
$sql .= ' ) ';
$sql .= ' ORDER BY U.id DESC LIMIT '.$limit.' OFFSET '.$offset.';';
$random_users = $db->objectBuilder()->rawQuery($sql);
$theme_path = $_BASEPATH . 'themes' . $_DS . self::Config()->theme . $_DS;
//$template = $theme_path . 'partails' . $_DS . 'find-matches' . $_DS . 'random_users.php';
//$template1 = $theme_path . 'partails' . $_DS . 'find-matches' . $_DS . 'matches_imgs.php';
if (file_exists($template)) {
foreach ($random_users as $random_user) {
if($random_user->id!=(int)auth()->id){
ob_start();
require($template);
$html .= ob_get_contents();
ob_end_clean();
}
}
}
return array(
'status' => 200,
'page' => $page + 2,
'html' => $html,
'data' => $random_users
);
} else {
return array(
'status' => 400,
'message' => $error
);
}
}

Value number no appear inside js

I don't understand why the id: ' . $QspecificationName->valueInt('specification_id') . ', does'nt want to take the value of $QspecificationName->valueInt('specification_id');
$QspecificationName->valueInt('specification_id') has value like 2 and 3 but it write always 0.
Any idea ?
Tk
while ($Qspecification->fetch()) {
$specification_name = $this->productsSpecificationAdmin->getSpecificationName($Qspecification->valueInt('specification_id'), $this->lang->getId());
$customers_group_id = $Qspecification->valueInt('customers_group_id');
$QspecificationName = $this->app->db->prepare('select distinct s.specification_id as id,
sd.name as name,
sgd.name as groupName
from :table_specification s
left join :table_specification_group sg ON (s.specification_group_id = sg.specification_group_id )
left join :table_specification_group_description sgd on (sg.specification_group_id = sgd.specification_group_id),
:table_specification_description sd
where s.specification_id = sd.specification_id
and s.specification_id = :specification_id
and sg.specification_group_id = sgd.specification_group_id
and sd.language_id = :language_id
and sgd.language_id = :language_id
');
$QspecificationName->bindInt('specification_id', $Qspecification->valueInt('specification_id'));
$QspecificationName->bindInt(':language_id', $this->lang->getId());
$QspecificationName->execute();
$content .= '<tr id="specification-row' . $t . '">';
$content .= HTML::hiddenField('id', $Qspecification->valueInt('id'));
$content .= ' <td>
<script type="text/javascript">
$(document).ready(function() {
$("#specificationName' . $t . '").tokenInput("' . $products_specification_ajax . '" ,
{
tokenLimit: 1,
resultsLimit: 5,
onResult: function (results) {
$.each(results, function (index, value) {
value.name = value.id + " " + value.groupName + "/" + value.name;
});
return results;
}
});
});
$(document).ready(function() {
$("#specificationName' . $t . '").tokenInput("' . $products_specification_ajax . '", {
prePopulate: [
{
id: ' . $QspecificationName->valueInt('specification_id') . ',
name: "' . $QspecificationName->valueInt('specification_id') . ' ' . $QspecificationName->value('groupName') . '/' . $QspecificationName->value('name') . '"
}
],
tokenLimit: 1
});
});
</script>
}

localstorage data not persisting between pages

I am attempting to build a website to assist with recording times of events during ems calls. I have replicated our protocols and am using localstorage to record when and what event happens. When the incident is over, all the events that have been clicked are displayed on a report page where the information can be sent via email.
Everything seems to work, however, if another page is opened, the localstorage seem to clear and only the buttons clicked on the most recent page appear. I need every button clicked recorded for the report.
This is my JS:
//GO BACK BUTTON
function goBack() {
window.history.back();
}
// DATE FORMATER
function convertDate() {
var d = new Date();
var a = [(d.getMonth() + 1),
(d.getDate()),
(d.getFullYear()),
].join('-');
var b = [(d.getHours()),
(d.getMinutes()),
(d.getSeconds()),
].join(':');
return (b + ' ' + a);
}
///////////////////button////////////////////////
$(document).ready(function () {
var report = {};
var myItem = [];
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.report = JSON.stringify(myItem);
});
});
And this is part of the report page:
<script>
window.onload = function () {
var areport = JSON.stringify(localStorage.report);
console.log(areport);
areport = areport.replace(/\\"/g, "");
areport = areport.replace(/{/g, "");
areport = areport.replace(/}/g, "");
areport = areport.replace(/[\[\]']+/g, "");
areport = areport.replace(/,/g, "");
areport = areport.replace(/"/g, "");
console.log(areport);
document.getElementById('result').innerHTML = areport;
};
</script>
<body>
<div class="container-fluid">
<h1>Report</h1>
<?php
if (isset($_POST["send"])) {
$incident = $_POST['incident'];
$name = $_POST['name'];
$address = $_POST['address'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$reportData = $_POST['reportData'];
if ($incident == '') {
echo $incident = 'No incident number entered.';
echo '<br>';
} else {
echo $incident . '<br>';
}
if ($name == '') {
echo $name = 'No name entered.';
echo '<br>';
} else {
echo $name . '<br>';
}
if ($address == '') {
echo $address = 'No address entered.';
echo '<br>';
} else {
echo $address . '<br>';
}
if ($dob == '') {
echo $dob = 'No birthdate entered.';
echo '<br>';
} else {
echo $dob . '<br>';
}
if ($gender == '') {
echo $gender = 'No gender entered.';
echo '<br>';
} else {
echo $gender . '<br>';
}
if ($reportData == null) {
echo $reportData = 'No report entered.';
echo '<br>';
} else {
echo $reportData . '<br>';
}
//mail
$headers = "From: CCEMP.info <ccemlbaw#server237.web-hosting.com> \r\n";
$reEmail = $_POST['reEmail'];
$reEmail1 = $_POST['reEmail1'];
//$areport = json_decode($_POST['localStorage.report']);
$msg = "Incident: " . $incident . "\n" . "Name: " . $name . "\n" . "Address:
". $address . "\n" . "DOB: " . $dob . "\n" . "Gender: " . $gender . "\n" .
$reportData;
mail($reEmail, 'Incident:' . $incident, $msg, $headers);
mail($reEmail1, 'Incident:' . $incident, $msg, $headers);
}//end of submit
?>
Here is a sample button:
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">General Truama</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" >Continue Assessment</a>
<a class="dropdown-item" href="GATA.php">Go to Truama</a>
</div>
</div>
Thanks.
You are not using localStorage, just setting .report on global localStorage variable. You would see this issue if you used strict mode ("use strict"; at top of the js file).
instead use:
localStorage.setItem("report", JSON.stringify(myItem));
and to get the item
localStorage.getItem("report");
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
This does not set the item to localStorage. In fact, localStorage.report is undefined.
localStorage.report = JSON.stringify(myItem);
This does.
localStorage.setItem('report', JSON.stringify(myItem));
I wasn't adding the localStorage from the previous page to the new one.
var myItem = [];
$(document).ready(function () {
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
var item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.setItem('report', JSON.stringify(myItem));
console.log(myItem);
});
var areport = localStorage.getItem("report");
myItem.push(areport);
});

ReferenceError: Function Not Defined. What am I missing?

Can't seem to figure out why I keep getting this ReferenceError: OnLoad is not defined error.
Since the time of my previous commit, I have changed lines 28-30 and that is all.
How can this cause my javascript to not be loaded properly? I have only changed these three lines. I'm certain these lines shouldn't really be related. The Javascript file is identical to the one in the previous commit.
What am I missing?
UserInterface.php - Current Commit
class UserInterface {
var $ParentAppInstance;
function __construct($AppInstance){
$this->ParentAppInstance = $AppInstance;
$this->DrawPageHTML();
$this->DrawDBSetDropdown();
$this->DrawQueryForm();
}
//Override thjis function to change the HTML and PHP of the UI page.
protected function DrawPageHTML(){
$CurrDB_Obj = $this->ParentAppInstance->CurrentDBObj; //Line 28
$EncodedFields = json_encode($CurrDB_Obj->GetFields()); //Line 29
echo "<body onload='OnLoad($EncodedFields);'>"; // Line 30
echo '
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./CSS/UserInterface.css">
<div id="DebugOutput"></div>
</body>
';
}
protected function DrawDBSetDropdown(){
echo '<div align="right">';
echo '<select onchange="SwitchDatabaseSet();" name="DBSetList" form="DBSetSelector" id="DBSetSelector">';
$i = 0;
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){/* DO NOTHING. IE. IGNORE IT*/}
else if ($DBSet->DBSetName == 'DBSet0'){/* DO NOTHING. IE. IGNORE IT*/}
else{
//Add the DBSet to the dropdown list.
$i++;
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
echo '</select>';
echo '</div>';
}
protected function DrawQueryForm(){
echo '<form action="DatabaseSearch.php" method="post" accept-charset="UTF-8">';
echo '<div id="QFormBody">';
$NumActiveQBoxes = $this->ParentAppInstance->Config['ApplicationSettings']['NumberDefaultQueryOptions'];
for ($i = 1; $i <= $NumActiveQBoxes; $i++){
echo '<div class="QueryBox" name="QBox_' . $i . '">';
echo '<select name=Field_' . $i . '">';
$DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT);
$CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num];
foreach($CurrDBSet_Obj->GetDBSetFields() as $Field){
//echo $Field;
echo '<option>' . $Field . '</option>';
}
echo '</select>';
echo '<input type="text" name="Query_' . $i . '"></input>';
echo '<button class= "RMButton" type="button">-</button>';
echo '</div>';
}
echo '<button type="button" id="add" onclick="AddQueryBox();">+</button>';
echo '<button type="submit" id="submit">SEARCH</button>';
echo '</Form>';
echo '<script src=/GLS_DBSearchProject/JavaScript/UserInterface.js></script>';
}
UserInterface.php - Previous Commit
class UserInterface {
var $ParentAppInstance;
function __construct($AppInstance){
$this->ParentAppInstance = $AppInstance;
$this->DrawPageHTML();
$this->DrawDBSetDropdown();
$this->DrawQueryForm();
}
//Override thjis function to change the HTML and PHP of the UI page.
protected function DrawPageHTML(){
$DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT); //Line 28
$CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num]; //Line 29
$EncodedFields = json_encode($CurrDBSet_Obj->GetDBSetFields()); //Line 30
echo "<body onload='OnLoad($EncodedFields);'>";
echo '
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./CSS/UserInterface.css">
<div id="DebugOutput"></div>
</body>
';
}
protected function DrawDBSetDropdown(){
echo '<div align="right">';
echo '<select onchange="SwitchDatabaseSet();" name="DBSetList" form="DBSetSelector" id="DBSetSelector">';
$i = 0;
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){/* DO NOTHING. IE. IGNORE IT*/}
else if ($DBSet->DBSetName == 'DBSet0'){/* DO NOTHING. IE. IGNORE IT*/}
else{
//Add the DBSet to the dropdown list.
$i++;
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
echo '</select>';
echo '</div>';
}
protected function DrawQueryForm(){
echo '<form action="DatabaseSearch.php" method="post" accept-charset="UTF-8">';
echo '<div id="QFormBody">';
$NumActiveQBoxes = $this->ParentAppInstance->Config['ApplicationSettings']['NumberDefaultQueryOptions'];
for ($i = 1; $i <= $NumActiveQBoxes; $i++){
echo '<div class="QueryBox" name="QBox_' . $i . '">';
echo '<select name=Field_' . $i . '">';
$DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT);
$CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num];
foreach($CurrDBSet_Obj->GetDBSetFields() as $Field){
//echo $Field;
echo '<option>' . $Field . '</option>';
}
echo '</select>';
echo '<input type="text" name="Query_' . $i . '"></input>';
echo '<button class= "RMButton" type="button">-</button>';
echo '</div>';
}
echo '<button type="button" id="add" onclick="AddQueryBox();">+</button>';
echo '<button type="submit" id="submit">SEARCH</button>';
echo '</Form>';
echo '<script src=/GLS_DBSearchProject/JavaScript/UserInterface.js></script>';
}
UserInterface.js
var DBSetFields = [];
var NumQBoxes = 3;
//window.onload = OnLoad();
function OnLoad(Fields){
console.log("OnLoad called");
CloneDBSetFields(Fields);
var RMNodeList = document.getElementsByClassName('RMButton');
for (var i = 0; i < RMNodeList.length; ++i) {
console.log(RMNodeList[i]);
RMNodeList[i].onclick = RemoveQBox; // Calling myNodeList.item(i) isn't necessary in JavaScript
}
}
function JSTEST(){
window.alert("JS Called Successfully!!");
}
function CloneDBSetFields(Fields){
console.log("CloneDBSetFields");
DBSetFields = Fields;
}
function SwitchDatabaseSet(MainPageDoc){
document.getElementById("DebugOutput").innerHTML = "Test";
window.location.replace('/GLS_DBSearchProject/index.php?DBSet=' + document.getElementById("DBSetSelector").value);
console.log(document.getElementById("DBSetSelector").value);
//console.log(document.)
}
function Fields_FOREACH(ELEMENT, INDEX, ARRAY){
console.log("TEST");
var FieldOption = document.createElement('option');
FieldOption.setAttribute('value', ARRAY[INDEX]);
FieldOption.innerHTML = ARRAY[INDEX];
this.appendChild(FieldOption);
}
function AddQueryBox(){
NumQBoxes += 1;
var NewQBox = document.createElement('div');
NewQBox.setAttribute('class', 'QueryBox');
//Create and fill Field Selector dropdown "select" element
var FieldSelector = document.createElement('select');
FieldSelector.setAttribute('name', 'Field_' + NumQBoxes);
//foreach element in Fields
console.log(DBSetFields);
DBSetFields.forEach(Fields_FOREACH, FieldSelector);
//Create and fill
var QueryText = document.createElement('input');
QueryText.setAttribute('type', 'text');
QueryText.setAttribute('name', 'Query_' + NumQBoxes);
//Create "-" Remove button for removing query lines.
var RemoveButton = document.createElement('button');
RemoveButton.innerHTML = "-";
RemoveButton.setAttribute('type', 'button');
RemoveButton.setAttribute('class', 'RMButton');
RemoveButton.addEventListener("click", RemoveQBox);
//Combine the individual elements into a new query box and insert the new query box into the HTML Document
NewQBox.appendChild(FieldSelector);
NewQBox.appendChild(QueryText);
NewQBox.appendChild(RemoveButton);
document.getElementById("QFormBody").insertBefore(NewQBox, document.getElementById("add"));
}
function RemoveQBox(e){
console.log("Remove");
var RemoveButton = this; //this == e.currentTarget
console.log(RemoveButton);
var QBox = RemoveButton.parentNode;
QBox.remove();
NumQBoxes -= 1;
}
EDIT: My Javascript file is not being loaded on the client side (ie. it doesn't show up under "Sources", so I'm not really not sure: Why wouldn't my javascript be loading on the client side?

Categories

Resources