I'm fairly new to both PHP and Javascript, so please forgive my ignorance and poor use of terminology, but I'll do my best to explain exactly what I'm struggling to achieve.
I have information stored in a PHP array that I call to my index page using the function below (the code below is in a separate PHP file called articles.php that's included in my index.php) :
<?php
function get_news_feed($article_id, $article) {
$output = "";
$output .= '<article class="img-wrapper">';
$output .= '<a href="article.php?id=' . $article_id . '">';
$output .= '<div class="news-heading">';
$output .= "<h1>";
$output .= $article["title"];
$output .= "</h1>";
$output .= "<p>";
$output .= "Read more...";
$output .= "</p>";
$output .= "</div>";
$output .= '<div id="news-img-1">';
$output .= "</div>";
$output .= "</a>";
$output .= "</article>";
return $output;
}
$articles = array();
$articles[] = array(
"title" => "Andy at NABA",
"description" => "Docendi, est quot probo erroribus id.",
"img" => "img/gym-01.jpg",
"date" => "05/04/2013"
);
$articles[] = array(
"title" => "Grand Opening",
"description" => "Docendi, est quot probo erroribus id.",
"img" => "img/gym-01.jpg",
"date" => "05/04/2013"
);
?>
My index.php looks like the following minus some HTML that plays no role in this process:
<?php
include("inc/articles.php");
?>
<?php
$pageTitle = "Home";
include("inc/header.php");
?>
<section class="col-4 news">
<?php
$total_articles = count($articles);
$position = 0;
$news_feed = "";
foreach($articles as $article_id => $article) {
$position = $position + 1;
if ($total_articles - $position < 2) {
$news_feed .= get_news_feed($article_id, $article);
}
}
echo $news_feed;
?>
</section>
I am aiming to dynamically change the CSS Background-Image property of the div element with ID news-img-1 using Javascript.
I have tried such things as:
document.getElementById('news-img-1').style.backgroundImage = 'url('<?php $article["img"]; ?>')';
document.getElementById('news-img-1').style.backgroundImage = 'url('http://www.universalphysique.co.uk/' + '<?php $article["img"]; ?>')';
document.getElementById('news-img-1').style.backgroundImage = 'url('window.location.protocol + "//" + window.location.host + "/" + '<?php $article["img"]; ?>')';
.....but I'm getting nowhere!! My code in practise works because the following Javascript inserts an image correctly:
document.getElementById('news-img-1').style.backgroundImage = 'url("img/gym-01.jpg")';
Here is my site up and running, the images should be placed in the empty circles you'll see! Any help would be great, this ones tough for me!!
comparing the hard coded javascript to ones that don't work, I notice that you are not including the double-quotes around the <?php $article["img"]; ?> snippet. The hard coded one shows
= 'url("img/gym-01.jpg")'
but the ones with the php snippet will produce
= 'url(img/gym-01.jpg)'
so perhaps if you modify it to
document.getElementById('news-img-1').style.backgroundImage = 'url("'<?php $article["img"]; ?>'")';
OR
edit the get_news_feed function as follows:
replace these lines
$output .= '<div id="news-img-1">';
$output .= "</div>";
with
$output .= '<div class="news-img"><img src="' . $article["img"] . '"></div>' ;
and change your css like so:
article.img-wrapper {
position: relative;
}
div.news-img {
position: absolute;
top: 0;
z-index: -1000;
}
OR
Modify your get_news_feed function, change the statement for the <div id="news-img-1"> output to include a data-url attribute like:
$output .= '<div class="news-img" data-url="' . $article["img"] . '">';
Then add a jquery statement like:
$(".news-img").each( function() {
$(this).css("background-image", "url(" + $(this).data("url") +")" );
});
The jquery statement goes in a static js file as opposed to generating the script in php.
You need to remove the quotes from your PHP tags and see if it works!
Do it like this:
document.getElementById('news-img-1').style.backgroundImage = 'url(' + <?php $article["img"]; ?> + ')';
Hope it helps.
Related
I have created one shortcode to return a tab content and it is working fine
if I am using one time in a page.But if want one more on this same page it is not working. I have tried in several way but its not giving fruits.
Here is the code
if($tab_box == 'tab_box_1' && $tabs_lay == 'awavc-tabs-pos-left') {
$add_class = rand(99,9999);
$q = rand(99,99999);
$html .= '
<div class="awavc-tabs awavc-tabs-'.$add_class.' '.$tabs_lay.' '.$tab_style.' awavc-tabs-response-to-icons '.$el_class.' ">';
$i = 1;
foreach($tab_contents as $tab_content){
$tab_lable = 'Lable';
$tab_icon = '';
if(!empty($tab_content['tab_lbl'])){$tab_lable = $tab_content['tab_lbl'];}
if(!empty($tab_content['icon'])){$tab_icon = $tab_content['icon'];}
$html .= ' <input type="radio" name="awavc-tabs" checked id="awavc-tab-'.$i.'" class="awavc-tab-content-'.$i.'">
<label for="awavc-tab-'.$i.'"><span><span style="font-size:'.$lable_size.'px;color:'.$lable_clr.';"><i class="'.$tab_icon.'" style="font-size:'.$lable_size.'px;color:'.$icon_clr.';"></i>'.$tab_lable.'</span></span></label>';
$i++;
}
$html .= '
<ul>';
$i = 1;
foreach($tab_contents as $tab_content){
$tab_title = 'Title';
$content = '';
if(!empty($tab_content['title'])){$tab_title = $tab_content['title'];}
if(!empty($tab_content['content'])){$content = $tab_content['content'];}
$html .= '<li class="awavc-tab-content-'.$i.'">
<div class="typography">';
if(!empty($tab_title)){ $html .= '<h1 style="font-size:'.$ttl_size.'px;color:'.$ttl_clr.';">'.$tab_title.'</h1>';}
$html .= '
<p style="font-size:'.$content_size.'px;color:'.$content_clr.';font-style:'.$content_style.';">'.$content.'</p>
</div>
</li>';
$i++;
}
I have tried something like $i.$add_class but...
If you want to use the shortcode multiple times on the same page do it like so:
add_shortcode("fmg_shortcode", "fmg_callback");
function fmg_callback($args) {
ob_start();
$html = "";
//your code here
echo $html;
return ob_get_clean();
}
I'm doing this PHP tutorial on OOP and I'm trying to incorporate the procedural code from the essential training into it, to see if I actually learned anything beyond the basics, and I got stuck, big time.
So, I have these two functions inside the class I named Blog:
public function navigation($selected_subject, $selected_page) {
$output = "<ul class=\"subjects\" id=\"accordion\">";
$subject_set = $this->get_all_subjects($public);
while ($subject = mysqli_fetch_array($subject_set)) {
$output .= "<li";
if ($subject["id"] == $selected_subject['id']) { $output .= " class=\"blogselected\""; }
$output .= ">{$subject["menu_name"]}</li>";
$page_set = $this->get_pages_for_subject($subject["id"], $public);
$output .= "<ul class=\"pages\">";
while ($page = mysqli_fetch_array($page_set)) {
$output .= "<li";
if ($page['id'] == $selected_page['id'] ) { $output .= " class=\"blogselected\""; }
$output .= "><a href=\"../public/blog_index.php?page=" . urlencode($page["id"]) .
"\">{$page["menu_name"]}</a></li>";
}
$output .= "</ul>";
}
$output .= "</ul>";
return $output;
}
public function blog_page($selected_page){
if ($selected_page) {
echo "<h2>" . $selected_page['menu_name'] . "</h2>";
echo "<div class=\"page-content\">";
echo $selected_page['content'];
echo "</div>";
} else {
echo "<h2>Welcome to Widget Corp</h2>";
}
}
and this piece of code on the index page:
<?php
$blog = new Blog;
global $selected_page;
global $selected_subject;
?>
<div class="blog">
<div class="blogpost">
<?php echo $blog->blog_page($selected_page); ?>
</div>
<div class="blognav">
<?php echo $blog->navigation($selected_subject, $selected_page); ?>
</div>
</div>
The code partially works. The navigation with subjects and sub-pages gets displayed fine, when the links are clicked the id "?page=1" is passed to the url, but the problem is that the code is not adding a class "blogselected" to the active links, and it also does not display the content when the links are clicked. The only thing that gets displayed in the content area is the h2 "Welcome to Widget Corp" from else condition in the second function, so I believe the variables $selected_subject and $selected_page might be causing the problem, but I just can't figure it out on my own. I spent countless hours trying to solve this and I'm on the brink of giving up completely. What exactly am I missing here?
I've some issues with a geolocation script I'm working on and maybe someone could help me here :).
For this script I have 4 files :
functions.js:
function geolocation(){
GMaps.geolocate({
success: function(position) {
var userLat = position.coords.latitude;
var userLng = position.coords.longitude;
var dataString = 'userLat='+userLat+'&userLng='+userLng;
$.ajax({
type : 'POST',
url : 'getEvents.php',
data : dataString,
dataType : 'text',
success : function(msg){
console.log(msg);
}
});
},
error: function(error) {
alert('Echec de la localisation...');
},
not_supported: function() {
alert('Votre navigateur ne supporte pas la géolocalisation...');
}
});
}
index.php:
<?php require 'php/getEvents.php'; ?>
<!DOCTYPE html>
<html lang="fr">
<?php include('inc/head.html'); ?>
<body>
<div class="mosaic">
<?php echo visitorMosaicBox($data); ?>
</div>
<script type="text/javascript">
$(document).ready(function(){
geolocation();
});
</script>
</body>
</html>
getEvents.php:
<?php
session_start();
require 'db-connect.php';
require 'lib.php';
$userLat = $_POST['userLat'];
$userLng = $_POST['userLng'];
$area = 10;
$i = 0;
$data = array();
if($userLat != '' && $userLng != ''){
if(isset($_SESSION['id'])){
echo 'Logged';
}else{
try{
$sql = "SELECT restaurants.cover, restaurants.name, restaurants.address, restaurants.location, restaurants.zip, events.title, events.trailer, events.id
FROM events
LEFT JOIN restaurants ON restaurants.id = events.fk_restaurants";
$req = $db->query($sql);
}catch(PDOException $e){
echo 'Erreur: '.$e->getMessage();
}
while($res = $req->fetch()){
$fetchAddress = $res['address'].', '.$res['zip'].' '.$res['location'];
$fixedAddress = str_replace(' ','+',$fetchAddress);
$geocode = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$fixedAddress.'&sensor=false');
$output = json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$lng = $output->results[0]->geometry->location->lng;
$distance = distance($userLat, $userLng, $lat, $lng, false);
if($distance <= $area){
$data[$i] = array(
"id" => $res['id'],
"name" => $res['name'],
"cover" => $res['cover'],
"address" => $fetchAddress,
"title" => $res['title'] ,
"trailer" => $res['trailer'],
);
$i++;
}
}
}
}else{
$data = 'ERROR';
}
?>
lib.php :
<?php
function visitorMosaicBox($array){
for($i=0; $i<sizeOf($array);$i++){
$html = '<div class="box" id="box-'.$i.'">';
$html .= '<img src="'.$array[$i]['cover'].'" alt="'.$array[$i]['name'].'" />';
$html .= '<span class="ribbon"></span>';
$html .= '<div class="back"></div>';
$html .= '<div class="infos" id="event-'.$array[$i]['id'].'">';
$html .= '<p class="msg"></p>';
$html .= '<div class="txt-1">';
$html .= '<span class="sits"><span class="dinners">5</span></span>';
$html .= '<h3>'.$array[$i]['title'].'<span class="block">'.$array[$i]['name'].'</span></h3>';
$html .= '<ul class="actions">';
$html .= '<li>Partager</li>';
$html .= '<li>Participer</li>';
$html .= '<li class="last">Info</li>';
$html .= '</ul>';
$html .= '</div>'; // Fin de .txt-1
$html .= '<div class="txt-2">';
$html .= '<h3>'.$array[$i]['title'].'</h3>';
$html .= '<p>'.$array[$i]['trailer'].'</p>';
$html .= 'Fermer';
$html .= '</div>'; // Fin de .txt-2
$html .= '</div>'; // Fin de .infos
$html .= '</div>'; // Fin de .box
return $html;
}
}
?>
So now what's that's supposed to do...
1/ functions.js geolocates the visitor, gets his coordonates (lat,lng) and send them to my getEvents.php
2/ getEvents.php receives the coordonates from functions.js, and compare them with the results from the database.
3/ If the distance between the result and the user is lower than the area (10) then I store all the datas from the result in my array $data.
4/ The function visitorMosaicBox() creates as many divs as there are results in my array.
5/ In index.php, I simply call visitorMosaicBox() by passing my array $data.
My problem is that no divs are created even if there are results. I receive the visitor's coordonates in my getEvents.php file but in my index.php file the coordonates doesn't exists.
Does anyone know why my coordonates can't pass from my getEvents.php file to my index.php file please ? Any solution ?
If I split my script in these 4 files it's because I'll need to do other stuffs on my getEvents.php file depending on the visitor is connected or not, etc...
Thanks and sorry for this long question.
Antho
I am working on integrating two wordpress plugins. What I am trying to do is to add this code<?php DisplayStars(get_the_ID()); ?> into a function of another plugin. I tried $html = '<?php DisplayStars(get_the_ID()); ?>';, but php shows errors. Thanks for your help.
function wpbusdirman_post_excerpt($count)
{
$wpbusdirman_gpid=wpbusdirman_gpid();
$wpbusdirman_permalink=get_permalink($wpbusdirman_gpid);
$html = '';
$html .= '<div id="wpbdmlistings"';
$isasticky = get_post_meta(get_the_ID(),'sticky');
if(isset($isasticky) && !empty($isasticky))
{
$isasticky=$isasticky[0];
}
if(isset($isasticky) && ($isasticky == 'approved'))
{
if($count&1)
{
$html .= ' class="wpbdmoddsticky"';
}
else
{
$html .= ' class="wpbdmevensticky"';
}
}
else
{
if($count&1)
{
$html .= ' class="wpbdmodd"';
}
else
{
$html .= ' class="wpbdmeven"';
}
}
$html .='><div class="listingthumbnail">' . wpbusdirman_display_the_thumbnail() . '</div><div class="listingdetails">';
$html .= wpbusdirman_display_the_listing_fields();
$html .= wpbusdirman_view_edit_delete_listing_button();
$html .= '</div><div style="clear:both;"></div></div>';
return $html;
}
The code base you're working in is php. The code you're adding is php. That means, you don't need to add it inside the html, but simply call the function. (You may need an include at the top of the file for the function to work if it's not in this file)
$html .= DisplayStars(get_the_ID());
should be all you need in the call to add the text to the html.
When you do something like this:
<?php return "<?php echo('foo'); ?>"; ?>
Then PHP doesn't know (or care) about what is between the quotation marks - it's just text, as far as it knows. However, you can get PHP to interpret a string by using eval:
<?php
$command = "echo('foo');";
eval($command);
?>
This will cause PHP to print out "foo". But watch out, eval is dangerous - see the note in the PHP manual.
I'm trying to display the first row in one color and the second row in another color but my code displays the result twice in both colors for example lets say I have 5 results my code will double the results by displaying 10 results. How can I fix this problem?
Here is the php code.
while ($row = mysqli_fetch_assoc($dbc)) {
//first row
echo '<h3 class="title">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
//second row
echo '<h3 class="title-2">' . $row['title'] .'</h3>';
echo '<div class="summary-2">' . substr($row['content'],0,255) . '</div>';
}
You need to change the class on each row:
$count = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
if( $count % 2 == 0 ) {
$classMod = '';
} else {
$classMod = '-2';
}
//first row
echo '<h3 class="title' . $classMod . '">' . $row['title'] .'</h3>';
echo '<div class="summary' . $classMod . '">' . substr($row['content'],0,255) . '</div>';
$count++;
}
your code should be like this
CSS
.odd { background: #CCC }
.event { background: #666 }
PHP
$c = true;
while ($row = mysqli_fetch_assoc($dbc)) {
$style = (($c = !$c)?' odd':' even');
echo '<h3 class="title '.$style.'">' . $row['title'] .'</h3>';
echo '<div class="summary '.$style.'">' .substr($row['content'],0,255) . '</div>';
}
Here's a solution with minimal repetition:
$count = 0;
while (($row = mysqli_fetch_assoc($dbc)) && ++$count) {
printf(
'<h3 class="title%1$s">%2$s</h3>'
. '<div class="summary%1$s">%3$s</div>'
, $count % 2 ? "" : "-2"
, $row['title'] // might want to use htmlentities() here...
, substr($row['content'], 0, 255) // and here...
);
}
$i = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
$color =$i % 2;
echo '<h3 class="title-' .$color . '">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
$i++;
}
Your code just displays every result twice. Use a conditional (e.g. an integer or a boolean) to switch between rows (like: if true, then green; if false, then red).
For a boolean you could change the current value like so:
bool = !bool;
Couple of extra points:
You don't (normally) need so many classes. If you have <div class="stripe"> as your container, you can target the items with e.g. .stripe h3 in CSS.
If you target the odd and even items in CSS with .stripe h3, you can then overwrite just the odd items.
In a perfect world, you should keep presentation in the CSS. All browsers but IE7 and below support div:odd to target any odd child of a parent. This may require changing the structure of your HTML slightly. For IE7 and below, I'd add classes with JavaScript instead of PHP. When IE7 is no more then you can just remove the JS.
By the way, you could do this code too:
while ($row = mysqli_fetch_assoc($dbc)) {
echo '<h3 class="title">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
if($row = mysqli_fetch_assoc($dbc)){
echo '<h3 class="title-2">' . $row['title'] .'</h3>';
echo '<div class="summary-2">' . substr($row['content'],0,255) . '</div>';
}
}
IMO, there is no excuse for not delegating this kind of non-critical, presentation layer decoration to client side code.
Just use a library like jQuery and access the odd and even rows like so:
<script>
$(document).ready(function()
{
//for your table rows
$("tr:even").css("background-color", "#F4F4F0");
$("tr:odd").css("background-color", "#EFF1F2");
});
</script>
You'll have us generating font tags next.