How do I use this seemingly simple loop in CodeIgniter's view? - php

In the view, right before the footer, I want to load three JavaScript files. So, the controller sets three variables. For example, $js_1 = "bootstrap.js", $js_2 = '' and $js_3 = "tinymce.js", which may or may not be empty. The logic is, it should echo only if the variable is not empty. I also want to use the ternary if operator.
This was the best I could try.
for ($i = 1; $i <= 3; $i++)
{
echo (!empty ('$js_' . $i)) ? get_jscript('$js_' . $i) : NULL;
}
The function get_jscript() simply returns the HTML script src.
function get_jscript($js)
{
return '<script type="text/javascript" src="' . $js . '"></script> ';
}
Please note that I intend to ask this question to primarily learn the correct PHP syntax and not just load JS in the view.

if you can create a array like this->
$javascript = array('js_1' => "bootstrap.js", 'js_2' => '', 'js_3' = "tinymce.js");
then in your view you have to just call a method
loop_javascript($javascript);
it's better to create a function in codeigniter helper and call that helper in controller's function (check how to use helpers in codeingiter) https://ellislab.com/codeigniter/user-guide/general/helpers.html->
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('loop_javascript'))
{
function loop_javascript($jscript_array)
{
foreach($jscript_array as $key =>$value){
if($value != ''){
echo '<script type="text/javascript" src="' . $value. '"></script>';
}
}
}
}

This has some great info on how to use variable variables.
for ($i = 1; $i <= 3; $i++)
{
echo (!empty (${'js_'.$i})) ? get_jscript(${'js_'.$i}) : NULL;
}

for ($i = 1; $i <= 3; $i++)
{
if(!empty($js.'_'.$i)){ echo get_jscript($js.'_'.$i); echo "</br>";}
}
function get_jscript($js)
{
return '<script type="text/javascript" src="' . $js . '"></script> ';
}

Related

Woocommerce PHP

I have a lot of custom fields in my WooCommerce checkout, and I'm trying to display them all on the admin page.
The number of fields varies from user to user, therefor I need to figure out how many fields of the name "$order-billing_date_of_birth" there is.
$order-billing_date_of_birth1
$order-billing_date_of_birth2
$order-billing_date_of_birth3
...and so on
I thought maybe I could use a loop like this.
for ($x = 0; $x <= 100; $x++) {
echo '<p><strong>'.__('Date of birth').'</strong>: ' . $order->billing_date_of_birth.$x . '</p>';
}
My question is: How do I combine the two "billing_date_of_birth" and "$x" to work as "$order->billing_of_birth1".
There's probably better ways to solve this as well.
Following is what you need to do
for ($x = 0; $x <= 100; $x++) {
$prop = "billing_date_of_birth".$x ;
echo '<p><strong>'.__('Date of birth').'</strong>: ' . $order->$prop . '</p>';
}
Here is an example code to achieve the requirements.
Converting the Object to array and then finding the element.
<?php
$object = new StdClass;
$object->foo1 = 'Hey';
$object->bar1 = 'Friend';
$array_obj=(array) $object;
//var_dump( $array_obj );
$bar='bar';
$num=1;
echo ($array_obj[$bar.$num]);
?>
Try something similar, applied to a class.
for example
list-group-item1
list-group-item2
list-group-item3
With this code
jQuery(function($) {
$('.list-group-item').each(function(i) {
$(this).attr('class',"list-group-item"+i);
});
});

Using PHP to print to HTML5 output tag

I am new to this. If I have some PHP code as in the example below, I can use the echo function to print the result. Echo always prints at the top of the screen. How do I format the tag so that in this case the result "$myPi" is printed to the screen using an HTML5 output tag? I am a newbie so please be kind to me and don't flame my post - I tried to format the code. Thanks QJB.
function taylorSeriesPi($Iteration)
{
$count = 0;
$myPi = 0.0;
for ($count=0; ($count<$Iteration);$count++)
{
if ( ($count%4) == 1)
{
$myPi = $myPi + (1/$count);
}
if ( ($count%4) == 3)
{
$myPi = $myPi - (1/$count);
}
}
$myPi *= 4.0;
echo ("Pi is ". $myPi. " After ".$Iteration. " iterations");
}
You can insert PHP anywhere in your document, and reference functions from any other place within the document or included files.
For example:
<?php
function taylorSeriesPi($Iteration)
{
$count = 0;
$myPi = 0.0;
for ($count=0; ($count<$Iteration);$count++)
{
...
}
$myPi *= 4.0;
// Return the value so we can use this function later.
return $myPi;
}
?>
<html>
<body>
<div id="somediv">
<?php
$iteration = 6/*or whatever*/;
echo "Pi is " . taylorSeriesPi($iteration) . " After " . $iteration . " iterations";
?>
</div>
</body>
</html>
This will put the returned value and associated string within the <div> tag, but you can put it anywhere in your HTML, as the output of the echo will simply be text by the time the markup is seen by your browser.

Use a returned value of a function from another file in PHP

I am using a function in a separate file, that gets should return me an array containing the enum values of a field:
<?php
function getEnumValues($table, $field) {
$enum_array = array();
$query = "SHOW COLUMNS FROM '{$table}' WHERE Field = '{$field}'";
$result = mysqli_query($query);
$row = mysqli_fetch_row($result);
preg_match_all('/\'(.*?)\'/', $row[1], $enum_array);
return $enum_array;
}
?>
and in the main file, I do this:
<?php
require 'common.php';
for ($i=0; $i <= 5; $i++) {
getEnumValues(property, value_type);
echo "<input type='radio' name='tipo_valor' value='$enum_array[$i]' required>" . ' ' .$enum_array[$i] . '<br>';
}
?>
The problem is that the function returns nothing.
So is the function ok for what I need?
And can I use a variable returned in another file, as a local variable?
Thanks for your time, and suggestions!
The function is returning a value; you're just not capturing it. The $enum_array in your function body only lives in the scope of that function. You need to put the return value of the function in a variable in scope. In your main file:
<?php
require 'common.php';
for ($i=0; $i <= 5; $i++) {
$enum_array = getEnumValues(property, value_type);
echo "<input type='radio' name='tipo_valor' value='$enum_array[$i]' required>" . ' ' .$enum_array[$i] . '<br>';
}
?>

Wordpress theme options - wp_localize_script();

I'm using wp_localize_script(); to alter the JS in a theme I'm building, like so:
wp_enqueue_script('custom', get_bloginfo('template_directory') . '/js/script.js');
$settings = get_option('bro_options');
wp_localize_script('custom','settings',$settings);
While this is good, the way this works is it writes inline JS right before the JS file in question loads, that way you can use certain variables to modify the JS and how it functions.
Problem is, I don't really like this option and how it outputs inline JS. Does anyone know of an alternative to this? I'm pretty sure this isn't how everyone does this with their theme options so there must be another way.
Any help whatsoever would be appreciated, please no links to plugins either.
In short: I'm looking for an alternative to using wp_localize_script(); or a better way of using it.
What I did was create a file called settings.js.php and in that I included the wp-config.php file.
Like so:
<?php
header("Content-type: application/x-javascript");
$c = 0;
while($exists !== true && $notfound !== true) {
$c++;
$str = $str . '../';
if(file_exists($str.'wp-config.php')) {
$exists = true;
include($str.'wp-config.php');
$i = 0;
$amount = sizeof($bro);
echo 'var settings={';
foreach($bro as $key => $value) {
$i++;
if($i<$amount) {
echo $key . ':"' . $value . '",';
} else {
echo $key . ':"' . $value . '"';
}
}
echo '};';
}
if($c === 20) {
$notfound = true;
}
}
?>
Which would output my options in a variable like this:
var settings = {
foo: true,
bar: false
};
I would enqueue this file before my custom.js file that way I could determine if some settings were on and off.
if(settings.foo === true) {
...
}
All this so I don't have inline JS, there may be some cache issues but I'd rather have that than it output all options inline.

Jquery/ Javascript getting information from PHP scope issue?

I am trying to get some information from our database and then use it in javascript/JQuery and I think I might be doing something wrong with the scope of the coding.
Here is the current segment of code on my phtml page (magento)
<script type="text/javascript">
<?php
echo 'var $image-paths = new Array();';
for ($i = 0; $i < count ($_child_products); $i++)
{
echo '$image-paths[';
echo $i;
echo '] = ';
echo $this->helper('catalog/image')->init($_child_products[$i], 'image');
echo ';';
}
?>
document.getElementById('main-image').href = $image-paths[1];
</script>
The bottom getElementById is just for testing to see if it really grabbed that image path. So far the php stuff is working and echo'ing the correct links. However, is simply echo'ing them not enough; does it actually register it into the javascript code?
Here is what my source code looks like on my server:
<script type="text/javascript">
var $image-paths = new Array();
$image-paths[0] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5f b8d27136e95/feeds/MrsMeyers/MRM-64565-a.jpg;
$image-paths[1] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-64566-a.jpg;
$image-paths[2] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-64568-a.jpg;
$image-paths[3] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-D43114-a.jpg;
document.getElementById('main-image').href = $image-paths[1];
</script>
But the image link does not change to image-path[1]. Any ideas?
Thanks in advance!
$image-paths[0] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5f b8d27136e95/feeds/MrsMeyers/MRM-64565-a.jpg;
^-- no quote here, or at the end of the string
You're producing invalid javascript. Pop up your javascript console (shift-ctrl-J in chrome/firefox) and you'll see the error.
Producing javascript dynamically is problematic. Anytime you insert something from a PHP variable/function, you should run that through json_encode(), which guarantees you get valid javascript:
echo json_encode($this->helper('catalog/image')->init($_child_products[$i], 'image'));
Or better yet, change the code to:
$links = array();
for ($i = 0; $i < count ($_child_products); $i++)
$links[] = $this->helper('catalog/image')->init($_child_products[$i], 'image');
}
echo '$image-paths = ', json_encode($links);
<script type="text/javascript">
<?php
echo 'var $image_paths = new Array();';
for ($i = 0; $i < count ($_child_products); $i++)
{
echo '$image_paths[';
echo $i;
echo '] = "'; // Here the starting of quotes.
echo $this->helper('catalog/image')->init($_child_products[$i], 'image');
echo '";'; // Here the ending of quotes.
}
?>
document.getElementById('main-image').href = $image_paths[1];
</script>
This should work now. Hope it helps.

Categories