ReferenceError: Function Not Defined. What am I missing? - javascript

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?

Related

Woocommerce Variations Radio buttons

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');

JS function not found when calling PHP function on server but works on local server

As stated in the title my code works in local but not on server.
More precisely, when i call whatever PHP function it doesn't find my JS function.
To sum it up : The goal here is to generate an excel (.XLS) file from an HTML table which is created by retrieving data from a database. Everything works flawlessly in local with my Wamp server but when I move it to server I get this error when calling the JS function getDashboardResumeJ ():
DashboardResume.php:124 Uncaught ReferenceError: getDashboardResumeJ is not defined
If I remove all the PHP in the main file everything works when on server.
PHP in main file :
<button id="buttonXLS" href="#" onclick="exportTableToExcel('tableRecap', 'Rapport Mensuel <?php echo $year . '/' . $month?>')">Export to Excel</button>
<table style="display:none" id="tableRecap" >
<tr>
<td style="font-weight: bold">Nom et prénom</td>
<?php $arrayId = array(selectTableEmploye('nom', 'prenom')); ?>
</tr>
<tr>
<td style="font-weight: bold">Date d'entrée</td>
<?php selectTableEmploye('date_embauche'); ?>
</tr>
<tr>
<td style="font-weight: bold">Date de sortie</td>
<?php selectTableEmploye('date_depart'); ?>
</tr>
<tr>
<td style="font-weight: bold">Remarque 1</td>
<?php selectTableTimesheet('commentaire1',$arrayId,$month,$year); ?>
</tr>
<tr>
<td style="font-weight: bold">Remarque 2</td>
<?php selectTableTimesheet('commentaire2',$arrayId,$month,$year); ?>
</tr>
<tr>
<td style="font-weight: bold">Remarque 3</td>
<?php selectTableTimesheet('commentaire3',$arrayId,$month,$year); ?>
</tr>
<tr>
<td style="font-weight: bold">Remarque 4</td>
<?php selectTableTimesheet('commentaire4',$arrayId,$month,$year); ?>
</tr>
<?php
generateDays($dateMonth, $dateYear);
?>
</table>
JS in main file :
<script>
function exportTableToExcel(tableID, filename = ''){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
$(document).ready(function(){
$('.month_dropdown').on('change',function(){
getDashboardResumeJ('dashboard_div', $('.year_dropdown').val(), $('.month_dropdown').val());
});
$('.year_dropdown').on('change',function(){
getDashboardResumeJ('dashboard_div', $('.year_dropdown').val(), $('.month_dropdown').val());
});
getCommJ();
});
function getDashboardResumeJ(target_div, year, month){
$.ajax({
type:'POST',
url:'functionsDashboardResume.php',
data:'func=getDashboardResumeP&year='+year+'&month='+month,
success:function(html){
$('#'+target_div).html(html);
}
});
}
PHP functions called by main file PHP :
<?php
function selectTableEmploye($attribute, $optAttribute = '')
{
include "dbConfig.php";
$query = 'SELECT * FROM employe ORDER BY id_employe ASC';
if ($stmt = $db->prepare($query)) {
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
$arrayId = [];
if ($optAttribute != '') {
while ($row = $result->fetch_assoc()) {
echo '<td> ' . $row[$attribute] . ' ';
echo $row[$optAttribute] . '</td>';
array_push($arrayId, $row['id_employe']);
}
} else {
while ($row = $result->fetch_assoc()) {
echo '<td> ' . $row[$attribute] . '</td>';
}
}
/* free results */
$stmt->free_result();
}
return $arrayId;
}
function selectTableTimesheet($attribute, $arrayId, $month, $year)
{
include "dbConfig.php";
if (!empty($arrayId)) {
foreach ($arrayId[0] as $value) {
$query =
'SELECT DISTINCT commentaire1,commentaire2,commentaire3,commentaire4 FROM timesheet,employe WHERE timesheet.id_employe =' .
$value. ' AND timesheet.annee = ' . $year . ' AND timesheet.mois = ' . $month;
if ($stmt = $db->prepare($query)) {
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo '<td> ' . $row[$attribute] . '</td>';
}
}
}
}
else{
$query =
'SELECT * FROM timesheet';
if ($stmt = $db->prepare($query)) {
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo '<td> ' . $row[$attribute] . '</td>';
}
}
}}
function generateDays($month, $year)
{
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
for ($i = 1; $i <= $daysInMonth; $i++) {
if($month != 10){
$monthFunc = trim($month,0);
}
else{
$monthFunc = 10;
}
$data = getActivity($i,$monthFunc,$year);
$flag_half_day = 0;
$flag_row_number = 1;
$secondRowContent = array();
$numItems = mysqli_num_rows($data);
$checkIndex = 0;
echo "<tr>" . "<td style='text-align: right;font-weight: bold;'>" . $i . "</td>" ;
while ($row = $data->fetch_assoc()) {
if($flag_row_number == 1){
//cas 2b
if ($flag_half_day == 1){
array_push($secondRowContent,'<td>' . $row['code_fiduciaire'] . $row['nombre_heure'] . '</td>');
$flag_half_day = 0;
}
else{
//cas 1
if($row['nombre_heure'] == 8){
echo '<td>' . $row['code_fiduciaire'] . $row['nombre_heure'] . '</td>';
array_push($secondRowContent,'<td></td>');
$flag_half_day = 0;
}
//cas 2a
else if(is_null($row['nombre_heure'])){
echo '<td></td>';
}
else{
echo '<td>' . $row['code_fiduciaire'] . $row['nombre_heure'] . '</td>';
$flag_half_day = 1;
}
}
if($checkIndex++ == ($numItems - 1)){
$flag_row_number = 2;
echo "</tr>";
}
}
}
if($flag_row_number == 2){
echo '<tr> <td style="text-align: right;font-weight: bold;">' . $i . '</td>';
foreach($secondRowContent as $content){
echo $content;
}
echo '</tr>';
}
else{
echo '<tr> <td style="text-align: right;font-weight: bold;">' . $i . '</td> </tr>';
}
}
}
function getActivity($day, $month, $year){
include "dbConfig.php";
$query =
'select time_dimension.db_date, time_dimension.holiday_flag, employe.id_employe, employe.nom, timesheet.nombre_heure, timesheet.date, taches.code_fiduciaire FROM time_dimension left outer join employe on time_dimension.db_date >= employe.date_embauche left outer join timesheet on timesheet.date = time_dimension.db_date AND timesheet.id_employe = employe.id_employe left outer join taches on timesheet.id_tache = taches.id_tache where time_dimension.year = ' . $year . ' and time_dimension.month = ' . $month . ' and time_dimension.day = ' . $day . ' AND COALESCE (timesheet.nombre_heure,1) != 0 ORDER BY employe.id_employe, time_dimension.db_date' ;
if ($stmt = $db->prepare($query)) {
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
return $result;
}
}
?>
If you need more snippets or informations don't hesitate.
Thanks for your help,
Have a great day
For those who have the same kind of problem, the server I was working on didn't have the same PHP version as the one I was working in local.
Try phpinfo() both in local and on your server to check your PHP version is the same.

Update php SQL when checkbox check (no submit button)

I am pulling data out of a database and displaying in a table. I would like my checkbox, when checked/unchecked, to auto-update the value in the database without using a submit button to trigger the action. I'm new to AJAX and tried to adapt some code. I cannot get it to work. One major thing I don't understand is what '#state_span' is for?
Data Page (HTML)
$sql = "SELECT * FROM Orders ORDER BY " .$order;
$myData = mysqli_query($dbconnect, $sql);
while ($record = mysqli_fetch_array($myData)){
if ($record['Sent'] == 0) {
$sent = "";
} else {
$sent = "checked";
}
if ($record['Paid'] == 0) {
$paid = "";
} else {
$paid = "checked";
}
echo "<tr>";
echo '<td class="MenuLeft">' . $count . "</td>";
echo '<td class="MenuMid">' . $record['Name'] . "</td>";
echo '<td class="MenuRight"><input type="checkbox"
name="Sent"
id="'. $record['ID'] .'"
class="ChkSwitch"' . $sent . ' ></td>';
echo '<td class="MenuRight"><input type="checkbox"
name="Paid"
id="'. $record['ID'] .'"
class="ChkSwitch"' . $paid . ' ></td>';
echo "</tr>";
echo '<script>
$(document).ready(function() {
$(".ChkSwitch").click(function() {
var id = this.id;
var col = this.name; //Tell us what column to update
var state = this.checked ? 1 : 0;
$("#state_span").load("ChkUpdate.php?d="+id+"&col="+col+"&state="+state);
}
}
</script>
';
PHP
$id = $_GET['id'];
$state= $_GET['state'];
$col= $_GET['col'];
include("dbconnect.php");
$query = "UPDATE Orders SET '$col' = '$state' WHERE ID = '$id' ";
mysqli_query($dbconnect, $query);

how to export html table to excel, with pagination

I have a form which displays mysql data in the form of an HTML table, using pagination of 5 records per page. I'm trying to export my table to excel, but it's only exporting data of the rows that are currently show, meaning if there are 20 rows, it only shows the first 5 as those get displayed. How can I make it export the one's that are not being displayed but still part of the search? I saw a few other people with a similar question but none have answers( How to export all HTML table rows to Excel file from a paginated table?). Hopefully I can get one!
<?php
if(isset($_GET['submit']) || isset($_GET['page'])){
// Setting up the Pagination below
echo '<center>';
$page_query = "SELECT * FROM tbl_call_log_detail ";
$page_query .= "WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='') ";
$page_result = mysqli_query($conn, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
$start_loop = $page;
$difference = $total_pages - $page;
if($difference <= $total_pages){
$start_loop = $total_pages - $difference;
}
$end_loop = $start_loop + 2;
if($end_loop > $total_pages){
$end_loop = $total_pages;
}
if($difference > $total_pages){
$end_loop = $total_pages;
}
echo '<div class = "center">';
echo '<div class = "pagination">';
if($page > 1){
echo "<a href= 'dealer_call_log.php?page=1".$urlparameter."'>First</a>";
echo "<a href= 'dealer_call_log.php?page=".($page - 1).$urlparameter."'> << </a>";
}
for ($i = $start_loop; $i <= $end_loop; $i++){
echo "<a href= 'dealer_call_log.php?page=".$i.$urlparameter."'>".$i."</a>";
}
if($page < $end_loop){
echo "<a href= 'dealer_call_log.php?page=".($page + 1).$urlparameter."'> >> </a>";
echo "<a href= 'dealer_call_log.php?page=".$total_pages.$urlparameter."'>Last</a>";
}
if($page < 1){
$page = 1;
}
echo '</div>';
echo '</div>';
echo '<br>';
$sql = "SELECT Name, SFID, Comment, Time FROM tbl_call_log_detail
WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='')
ORDER BY Time DESC LIMIT $start_from, $record_per_page ";
$result = mysqli_query($conn, $sql);
$row = mysqli_num_rows($result);
$all_property = array();
echo "<table class = 'data-table' border = '1' cellpadding = '9' bgcolor = '#CCCCCC' id = 'data-table'>
<tr class = 'data-heading'>";
while($property = mysqli_fetch_field($result)){
echo '<td><b> '. $property ->name. ' </b></td>';
array_push($all_property, $property ->name);
}
echo '</tr>';
while ($row = mysqli_fetch_array($result)){
echo '<tr>';
foreach($all_property as $item){
echo '<td> '. $row[$item] . ' </td>';
}
echo '</tr>';
echo '</center>';
}
echo '</table>';
echo '<br>';
?>
// This is what is getting the current rows, but not all
<input type = "submit" onclick = "window.open('data:application/vnd.ms-excel, '+encodeURIComponent(document.getElementById('data-table').outerHTML));" value = "Export into excel" />
<?php
}
?>
UPDATE: Found the answer I was looking for I simply ran a new sql query without the LIMIT clause and stored it in a hidden table. I then use the hidden table to export data
// SQL and hidden table for exporting to excel
$page_query2 = "SELECT * FROM tbl_call_log_detail ";
$page_query2 .= "WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='') ORDER BY TIME DESC ";
$page_result2 = mysqli_query($conn, $page_query2);
$row2 = mysqli_num_rows($page_result2);
$all_property2 = array();
echo "<table class = 'data-table2' border = '1' cellpadding = '9' bgcolor = '#CCCCCC' id = 'data-table2' hidden>
<tr class = 'data-heading2'>";
while($property = mysqli_fetch_field($page_result2)){
echo '<td><b> '. $property ->name. ' </b></td>';
array_push($all_property2, $property ->name);
}
echo '</tr>';
while ($row2 = mysqli_fetch_array($page_result2)){
echo '<tr>';
foreach($all_property2 as $item){
echo '<td> '. $row2[$item] . ' </td>';
}
echo '</tr>';
echo '</center>';
}
echo '</table>';
?>
<input type = "submit" onclick = "window.open('data:application/vnd.ms-excel, '+encodeURIComponent(document.getElementById('data-table2').outerHTML));" value = "Export into excel" />
<?php
}
?>
You can use JQuery table2excel plugin following is the link
http://www.jqueryscript.net/table/Export-Html-Table-To-Excel-Spreadsheet-using-jQuery-table2excel.html
Try following code pen to only JavaScript
https://codepen.io/kostas-krevatas/pen/mJyBwp

How to hide a column in sql generated table? (php+jquery)

Looked through various solutions but unable to resolve. So far what I have implemented, only the first row is getting hid whereas the id of column remains same throughout. Can you please tell me that what needs to be changed?
JAVASCRIPT:
<script>
$(document).on("pagecreate","#pageone",function(){
$("button").click(function(){
var theID = $(this).attr('id');
$("#"+theID).slideToggle("slow");
$("table, tr,th#"+theID).slideToggle("slow");
$("table, tr,td#"+theID).slideToggle("slow");
});
/*
$("button").click(function(){
var theID = $(this).attr('id');
$("#"+theID).slideDown("slow");
$("td.#"+theID).slideDown("slow");
});
*/
});
</script>
The table query
$query = "select * from $table_select";
$result = mysql_query($query);
echo "<table id = 'table-1'>";
$num_columns = mysql_num_fields($result);
echo "<tr>";
for ($i = 0; $i < $num_columns; $i++)
{
echo "<th id='".$i."'>";
$meta = mysql_field_name($result, $i);
if($i == 0) {
$arg1 = $meta;
}
$field_name[] = $meta;
echo "$meta</th>";
}
$k = 0;
while($table = mysql_fetch_array($result)) {
$v[] = $table[0];
echo "<tr class = 'hid_tr'>";
for ($i = 0; $i < $num_columns; $i++) {
echo "<td id='".$field_name[$i]."'>{$table[$i]}</td>";
if($i == $num_columns-1) {
echo '<td><form action="'.$_SERVER['PHP_SELF'].'" method="post"> <input type="hidden" id="quoteid" name="quoteid" value='.$v[$k].' /><input type="hidden" id="db" name="db" value='.$db_select.' /> <input type="hidden" id="table" name="t" value='.$table_select.' /> <input type="hidden" id="field" name="field" value='.$arg1.' /> <input type="submit" name="formDelete" id"formDelete" value="" style="background-color:#f00;color:#fff;"/></form></td>';
}
}
echo "</tr>";
$k += 1;
}
echo '<tr>';
for ($i = 0; $i < $num_columns; $i++) {
//echo 'Slide up';
echo '<td><button id="'.$field_name[$i].'">Toggle '.$field_name[$i].'</button></td>';
}
echo '</tr>';
/*
echo '<tr>';
for ($i = 0; $i < $num_columns; $i++) {
//echo 'Slide Down';
echo '<td><button id="'.$field_name[$i].'">Slide down</button></td>';
}
echo '</tr>';
*/
echo "</table>";
The toggle button
echo '<tr>';
for ($i = 0; $i < $num_columns; $i++) {
//echo 'Slide up';
echo '<td><button id="'.$field_name[$i].'">Toggle '.$field_name[$i].'</button></td>';
}
echo '</tr>';
Thanks!
If what you mean is you want all the rows' 3rd tds to be hidden when someone clicks the button in the 3rd td of the top row, then you need to do something like this:
CREATING THE HEADERS
echo '<tr>';
for ($i = 0; $i < $num_columns; $i++) {
//The button calls a function with the proper position
echo '<td id="hideableHeader' . $i . '"><button onclick="hide(' . $i . ');">Toggle '.$field_name[$i].' </button></td>';
}
echo '</tr>';
CREATING THE COLUMNS WITH DATA
Here, you give each TD an id that combines its row and column index like this:
'<td id="hideable_' . $rowNum . '_' . $colNum . '">datahere</td>';
And keep track of total rows.
HIDING (this is a javascript function)
function hide(colNum)
{
//This is the header which will store its state for toggling
var header = document.getElementById( "hideableHeader" + colNum );
//Hide all of these tds starting after the first header row
for ( var row = 0; row < totalRows; row++ )
{
for ( var col = 0; col < totalCols; col++ )
{
var column = document.getElementById( "hideable_" + row + "_" + col );
//Is hidden, show it
if ( header.isHidden === true ) column.style.visibility = "visible";
//Hide it
else column.style.visibility = "hidden";
}
}
}

Categories

Resources