Undefined but existing - javascript

Here's my code:
js
var priorities = {
banner: '300',
avatar: '301'
};
var editableDiv = $('*[data-edit]');
editableDiv.append('<div class="overlay-edit"></div>');
editableDiv.each(function(index, value) {
var actualPriorities = value.getAttribute("data-edit");
console.log(actualPriorities);
console.log(priorities[actualPriorities]);
});
html/php
<div class="hexagon-wrap" style="height:<?php echo $this->outterHeight;?>px; width:<?php echo $this->outterWidth;?>px"
<?php
if($this->htmlOptions) {
foreach ($this->htmlOptions as $key => $value) {
echo $key . "=" . $value . "&nbsp";
}
}
?>
>
$this->htmlOptions contains
array('data-edit' => 'avatar')
The output :
banner
300
avatarĀ 
undefined
I do not understand why my last result is undefined. When I'm trying
priorities['avatar']; // ouput is 301
The output is good.

The problem is the no breaking space character, and you can improve the code wrapping in quotes:
<div class="hexagon-wrap" style="height:<?php echo $this->outterHeight;?>px; width:<?php echo $this->outterWidth;?>px"
<?php
if($this->htmlOptions) {
foreach ($this->htmlOptions as $key => $value) {
echo $key . "='" . $value . "' ";
}
}
?>
Note that I change the with the ' (with a real space to separate the attributes)

Related

Fill a javascript array with php variable

I want to fill a javascript array with my php variable $jaar. But when I print it in the js file I don't get the right output.
php file
<?php
$jaar = "[";
$result = mysql_query("SELECT jaar FROM agenda");
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
$jaar .= "\"" . $row[0] . "\"";
$jaar .= ",";
}
$jaar{ strlen($jaar)-1 } = ']';
echo "<script type='text/javascript'>var db_jaar = '" . $jaar ."'</script>";
?>
<script src="js/calender.js"></script>
js file
//Get the variable from the php file
alert(db_jaar);
//printed: ["2018","2018"]
//When I make the variable local
var db_jaar = ["2018","2018"];
alert(db_jaar);
//printed: 2018,2018 <-- This is what I want
Some changes required:
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
// create $jaar[]
$jaar[] = $row[0];
}
// echo using json_encode
?><script type='text/javascript'>var db_jaar = <?php echo json_encode($jaar); ?>;</script>";<?php
Read more:
json_encode()

Uncaught SyntaxError: Unexpected token < in CodeIgniter

I am currently working on CodeIgniter charts, but am getting an error like:
Uncaught SyntaxError: Unexpected token <
And charts are not loading showing blank.
var data_course_stats = google.visualization.arrayToDataTable([
['Course', 'Time spent',{ role: 'style' }],
<?php
$i=0;
foreach ($timespent_stats as $course) { $course = (object)$course;
$color_val = 'green';
if(count($i<count($timespent_stats)))
$color_val = $colors[$i++];
?>
['<?php echo $course->title;?>', <?php echo $course->spent_seconds/60;?>,'<?php echo $color_val; ?>'],
<?php } ?>
]);
var options_course_stats = {
title: 'Course Wise Spent Time in Minutes',
curveType: 'function',
height: 400,
bar: {groupWidth: "50%"},
legend: { position: "none" },
};
For longer blocks, to keep PHP open - you're getting in trouble because you're mixing and matching open and closed. Change this:
<?php
$i=0;
foreach ($timespent_stats as $course) { $course = (object)$course;
$color_val = 'green';
if(count($i<count($timespent_stats)))
$color_val = $colors[$i++];
?>
['<?php echo $course->title;?>', <?php echo $course->spent_seconds/60;?>,'<?php echo $color_val; ?>'],
<?php } ?>
to this:
<?php
$i=0;
foreach ($timespent_stats as $course) {
$course = (object)$course;
$color_val = 'green';
if(count($i<count($timespent_stats))) {
$color_val = $colors[$i++];
echo "['" . $course->title . "','" .
$course->spent_seconds/60 . "','" .
$color_val . "']";
}
}
?>
although you have accepted the answer, i want to add the another technique which is little simpler than the previous one. You can perform echo with <?= like <?php echo something; ?> so you can simply do this <?= something ?>
<?php
$i=0;
foreach ($timespent_stats as $course) {
$course = (object)$course;
$color_val = 'green';
if(count($i<count($timespent_stats)))
{
$color_val = $colors[$i++];
?>
[<?= $course->title ?>, <?= $course->spent_seconds/60 ?>, <?= $color_val ?>]
<?php
}
}
?>
If anyone get this problem again, check if your base_url is correct in config/config.php

How to dynamically poputate title and meta tags with php and/or javascript

I'm trying to replace my title tag and meta description dynamically using parameters from a search query in PHP. They keep showing up blank, but if I echo the $title or $desc inside the original PHP (first set) of tags, it appears fine. There is no header.php file for reference.
<?php
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
list($chuck, $keep) = explode('?', $url);
$patterns = array();
$patterns[0] = 'foo';
$patterns[1] = 'bar';
$patterns[2] = '123';
$replacements = array();
$replacements[0] = 'good ';
$replacements[1] = 'bad ';
$replacements[2] = 'ugly ';
$mytitle = "my cool " . $keep . " title tag";
$mydesc = "my cool " . $keep . " meta " . $keep . " description";
$title = str_replace($patterns, $replacements, $mytitle);
$desc = str_replace($patterns, $replacements, $mydesc);
//echo $title . "</br>";
//echo $desc . "</br>";
?>
<title><?if (strpos($url, 'foo=') !== false) { echo $title . "</br>"; } else { some other title"; }?></title>
<meta name="description" content="<?php echo $desc; ?>">
Alternatively, would a javascript/php mashup like this work?
<script>
document.title = <?if (strpos($url, 'foo=') !== false) { echo $title . "</br>"; } else { some other title"; }?>;
</script>
You need to amend your title alteration code's else slightly to include echo "
<title><?if (strpos($url, 'foo=') !== false) { echo $title . "</br>"; } else { echo "some other title"; }?></title>
Other than throwing a parse error as is this seems to work fine for me.

PHP Javascript Array

Hi I'm a novice PHP developer to say the least and I'm pretty stuck.
I'm trying to get the below code working I know I need a foreach loop or similar but I'm way out of my depth, I'm really not sure how to get this working, I know to most of you this is basic stuff but I'm lost.
Basically this is a receipt when a tab is settled. It searches the MySql Database for the relevant items and should print them on the receipt.
I know the MySql Query is not linked to the output at the bottom but I don't know how to do it.
<html lang="en">
<head>
<title>Receipt</title>
</head>
<body>
<?php
$invoicenum = $_POST['invoicenum'];
$name = $_POST['name'];
$netrev=$invoicenum - 1;
?>
Items:
<?
$itemQuery = mysql_query("SELECT * FROM sales WHERE invoicenum = '$netrev' AND tabname = '$name'");
$result = array();
while($row = mysql_fetch_array($itemQuery))
{
$result[] = $row['itemname'];
}
echo json_encode($result);
$amounts = json_decode($result['amounts']);
$items = json_decode($result['items']);
$prices = json_decode($result['prices']);
?>
<br>
<?
for ($i = 0; $i < count($items); $i++)
{
echo $amounts[$i] . "x " . $items[$i] . " - " . $prices[$i] . "<br>";
}
?>
</body>
</html>
I've removed code that isn't relevant to this array, if you can help I'd be forever grateful.
no need of encode and decode.
$itemQuery = mysql_query("SELECT * FROM sales WHERE invoicenum = '$netrev' AND tabname = '$name'");
while($row = mysql_fetch_array($itemQuery))
{
echo $row['amounts'] . "x " . $row['items'] . " - " . $row['prices'] . "<br>";
}
?>
Forget all json_decode/encode after filling $result then:
First do:
$result[] = $row;
Then:
foreach ($result as $set){
echo $set['amount'] . "x " . $set['itemname'] . " - " . $set['price'] . "<br>";
#do var_dump($set); here for checking the keys
}

WP archive with custom field filter

Hope someone can help.
I'm currently building a directory, and have used ACF to populate some data. I am now working toward building a filter for the options selected within one of my ACF groups, The field group is called 'Member Directory' the field I'm specifically targeting is: 'wha_service_offered'.
There are four checkbox values within this:
supplier : Supplier
manufacturer : Manufacturer
installer : Installer
consultant : Consultant
I have used checkbox as more than one option may apply to a member.
I have set up functions.php with the following:
// Filter Services
add_action('pre_get_posts', 'my_pre_get_posts');
function my_pre_get_posts( $query )
{
// validate
if( is_admin() )
{
return $query;
}
// allow the url to alter the query
// eg: http://www.website.com/members?wha_service_offered=installer
// eg: http://www.website.com/members?wha_service_offered=consultant
if( isset($_GET['wha_service_offered']) )
{
$query->set('meta_key', 'wha_service_offered');
$query->set('meta_value', $_GET['wha_service_offered']);
}
// always return
return $query;
}
And within my archive-members.php
php
<div id="search-services">
<?php
$field = get_field_object('wha_service_offered');
$values = isset($_GET['wha_service_offered']) ? explode(',', $_GET['wha_service_offered']) : array();
?>
<ul>
<?php foreach( $field['choices'] as $choice_value => $choice_label ): ?>
<li>
<input type="checkbox" value="<?php echo $choice_value; ?>" <?php if( in_array($choice_value, $values) ): ?>checked="checked"<?php endif; ?> /> <?php echo $choice_label; ?></li>
</li>
<?php endforeach; ?>
</ul>
</div>
javascript
<script type="text/javascript">
(function($) {
$('#search-services').on('change', 'input[type="checkbox"]', function(){
// vars
var $ul = $(this).closest('ul'),
vals = [];
$ul.find('input:checked').each(function(){
vals.push( $(this).val() );
});
vals = vals.join(",");
window.location.replace('<?php echo home_url('members'); ?>?wha_service_offered=' + vals);
console.log( vals );
});
})(jQuery);
</script>
When the filter is used it simply returns a blank page.
I would be grateful if anyone could point out where I have made an error.
Thanks.
--
So debug returns:
Declaration of Custom_Nav_Walker::start_el() should be compatible with
Walker_Nav_Menu::start_el(&$output, $item, $depth = 0, $args = Array, $id = 0) in
/Applications/MAMP/htdocs/website.com/wp-content/themes/wha/functions.php on line 169
Warning: Cannot modify header information - headers already sent by (output started at
/Applications/MAMP/htdocs/website.com/wp-content/themes/wha/functions.php:169) in
/Applications/MAMP/htdocs/website.com/wp-includes/pluggable.php on line 1179
The offending item is:
class Custom_Nav_Walker extends Walker_Nav_Menu {
function check_current($classes) {
return preg_match('/(current[-_])/', $classes);
}
function start_el(&$output, $item, $depth, $args) {
global $wp_query;
$indent = ($depth) ? str_repeat("\t", $depth) : '';
$slug = sanitize_title($item->title);
$id = apply_filters('nav_menu_item_id', 'menu-' . $slug, $item, $args);
$id = strlen($id) ? '' . esc_attr( $id ) . '' : '';
$class_names = $value = '';
$classes = empty($item->classes) ? array() : (array) $item->classes;
$classes = array_filter($classes, array(&$this, 'check_current'));
if ($custom_classes = get_post_meta($item->ID, '_menu_item_classes', true)) {
foreach ($custom_classes as $custom_class) {
$classes[] = $custom_class;
}
}
$class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args));
$class_names = $class_names ? ' class="' . $id . ' ' . esc_attr($class_names) . '"' : ' class="' . $id . '"';
$output .= $indent . '<li' . $class_names . '>';
$attributes = ! empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) .'"' : '';
$attributes .= ! empty($item->target) ? ' target="' . esc_attr($item->target ) .'"' : '';
$attributes .= ! empty($item->xfn) ? ' rel="' . esc_attr($item->xfn ) .'"' : '';
$attributes .= ! empty($item->url) ? ' href="' . esc_attr($item->url ) .'"' : '';
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
}
}
I'm not understanding why the walker nav would affect the filter?
--
Corrected line 169 error by amending the following from:
function start_el(&$output, $item, $depth, $args) {
To
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {}
I now have the following errors:
Notice: Undefined index: choices in /Applications/MAMP/htdocs/website.com/wp-content/themes/wha/archive-members.php on line 54
Warning: Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/website.com/wp-content/themes/wha/archive-members.php on line 54
Which relates to:
<?php foreach( $field['choices'] as $choice_value => $choice_label ): ?>

Categories

Resources