Crafting HTML elements from dynamic PHP data - php

I apologise for the potentially nebulous title, but I hope that the question will clarify why I've called it that.
I've gotten into webdev from UI design/dev so I'm finding the programming and design aspects fairly easy to handle. However, I'm not used to using three/four different languages with a fair amount of overlap to do a single thing.
In this case, I've written up a PHP script to pull the latest $n tweets from $x user. Currently I'm loading the Twitter PHP via jQuery, crafting the HTML for the tweet in PHP, echoing in the PHP, this is then plopped into a timeline element in the jQuery's callback function.
This way of doing it seems a bit hacky? I was just hoping someone would be able to point me towards another way, or at least waylay my concerns regarding this method.
Here's some Code:
HTML:
<section id="twitterContainer">
<section id="glitchTimeline" class="timeline">
<!--Twitter articles go here-->
</section>
</section>
Javascript:
function getTweets(n,user)
{
//This is run when the page is loaded
//Will be changing this to an ajax call later, aware that it's a bit silly as is.
$('<article class="twitterPost">').load("http://xxxxxxxxx.com/php/index.php?user="+user+"&count="+n, function(data){
$(this).appendTo("#glitchTimeline");
});
}
PHP:
(This is called once the twitter API stuff has come back)
function craftTweet($jsonStr)
{
$json = json_decode($jsonStr);
for($i = 0; $i<count($json); $i++)
{
echo '<img class="twitterAvatar" src=' . $json[$i]->user->profile_image_url .' alt=' . $json[$i]->user->screen_name .' width="48">';
echo '<div class="tweetText">';
echo ' <b>' . $json[$i]->user->screen_name .'</b><span>#' . $json[$i]->user->screen_name . '</span><span> </span>';
echo ' <p>' . $json[$i]->text . '</p>';
echo ' <img class="twitterIconFav" src="img/utils/transBackground.png">';
echo ' <img class="twitterIconRetweet" src="img/utils/transBackground.png">';
echo ' <img class="twitterIconReply" src="img/utils/transBackground.png">';
echo ' <div class="clearfix"> </div>';
echo '</div>';
}
}

Related

How to call an ACF variable with php to replace a nested html element?

I am using the repeater field of Wordpress' advanced custom fields to make the following content dynamic on my site.
Image of how the content looks while marked up statically
This is how I have marked up the content using plain html.
<div class="container">
<h2>A few general rules of thumb</h2>
<p><span>1.</span>Hallways and transitional spaces are best painted...</p>
<p><span>2.</span>It is best to keep expensive furnishings...</p>
<p><span>3.</span>If you want furnishings and accessories...</p>
<p><span>4.</span>Neutral furnishings and accessories?</p>
</div>
The paragraphs have been styled by setting their display to flex so that the span (number) is on the left and the paragraph is on the right.
This is how my code now looks with PHP.
<div class="container">
<h2><?php echo $container3title['title'];?></h2>
<?php
// Check rows existexists.
if(have_rows('rules')):
// Loop through rows.
while(have_rows('rules')) : the_row();
// Load sub field value.
$ruleNumber = get_sub_field('ruleNumber');
$ruleDetails = get_sub_field('ruleDetails');
// Do something...
echo '<span>' . $ruleNumber . '</span>';
echo '<p>' . $ruleDetails . '</p>';
// End loop.
endwhile;
// No value.
else :
// Do something...
endif;
?>
</div>
The problem is that I do not know how to echo the php so that the paragraphs aren't displayed as two block elements that are stacked on top of one another. I want it to be marked up the same way as I have marked it up using plain html so that my CSS will style it accordingly.
I tried the following but it didn't work.
echo '<p>' '<span>' . $ruleNumber . '</span>'; . $ruleDetails . '</p>';
Can someone please tell me how to put this together correctly? Thank you
Just store the span in a variable and concatenate it in:
$span = '<span>' . esc_html($ruleNumber) . '</span>';
echo '<p>' . $span . esc_html($ruleDetails) . '</p>';
I threw some escapes in there, too. It is generally recommended to always escape user-generated input when outputting, just in case. And even though you might “know” that the number is always numeric, it doesn’t really hurt to escape it anyway, and it makes it easier to scan for unescaped values.

Apache Server Not Loading in New Resources

I'm currently building a website using PHP and using Apache for the web server. I recently added some sub-folders to my images folder and am trying to load in those images on the site. However, the images aren't loading, and when I view the sources tab in DevTools, I'm seeing that it's not even loading in the new folders I've added, as well as some test images I've tried adding in. It had no issues with the initial dump of files I gave it, but won't load any new folders/images:
Images directory with new folders
Sources tab only loading original image files
Below is the PHP code that loads images onto the page:
<?php
$newsSql = "SELECT newsID, newsTitle, newsDescription, newsPicturePath, newsPicAlt, newsURL, newsBtnText FROM news_items ORDER BY newsID DESC";
$newsResult = $conn->query($newsSql);
if ($newsResult->num_rows > 0) {
while($row = $newsResult->fetch_assoc()) {
echo '<div class="row justify-content-center">';
echo ' <div class="card contentC">';
echo ' <img src="' . $row["newsPicturePath"] .'" class="card-img-top" alt="' . $row["newsPicAlt"] .'">';
echo ' <div class="card-body">';
echo ' <h5 class="card-title">' . $row["newsTitle"] .'</h5>';
echo ' <p class="card-text cardC">' . $row["newsDescription"] .'</p>';
echo ' ' . $row["newsBtnText"] .'';
echo ' </div>';
echo ' </div>';
echo '</div>';
}
}
?>
It's definitely going to be something simple and stupid but I cannot figure it out for the life of me.
There was nothing wrong with my Apache environment or my code; was victim to commas instead of periods in strings I was passing for image paths.
Called it that it was something stupid.

Issue with AJAX and displaying multiple html tags

So I am using the code that I got off W3C here: http://www.w3schools.com/php/php_ajax_database.asp
modified it to fit with my file names and database etc, however I am having a weird issue with echoing my responses to look correct.
For every product that collects from the product database it needs to print it in a section tag like so:
while($row = $result->fetch_assoc())
{
echo "<section class='sideWays'>" . $row['product_ID'] . " " . $row['product_name'] . " " . $row['description'] . " " . "<div class='colHeaderImageRight'>" . '<img src="'.$row['image'].'"">' . "</div>" . "</section>";
}
However this code isn't working anymore, the closest I have gotten is it to only display one and then breaks the rest.
the PHP echo is being returned into the following div tag
<article>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</article>
so I have tried changing my CSS to stuff like article > .txtHint > #sideWays or even just making the #sideWays css the same as .txtHint to skip the > #sideWays but nothing is working to display my CSS on the echo.
I'm not sure why but changing the keyword echo to print fixed the issue of it not recognising my html tags and applying the CSS to them.

Creating a variable template to display a database content

I'm working on a database website currently and part of the project is to display the content of a database in a custom form using pixels to position the various fields.
I am however having trouble getting the code to work as the way I'm creating the form doesn't seem to work in a php tag, but It requires a WHILE loop in order to continue running until the database field is empty.
I'm only including the relevant code section so as to not clog up the post, all my coding is segmented so I can isolate bugs.
<?php
$usernameh = 20;
$units = "px";
for ($x=0; $x<=2; $x++) {
$pix=$value . $units;
<div style="position:absolute;left:10px;top:20px;width:100px;height:20px;z- index:5;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:15px;">Field Name:</span></div>
$value += 150;
}
?>
The idea is to substitute the 20px on the first line of the divcommand with $pix so that with each iteration the value increases by a set amount and separates out the entries.
I'm very new to php coding, as in only really started 2 weeks ago. I'm sure there is a simple solution to this but I'm not sure what question to ask Google to get the response I'm after.
I hope my problem makes sense. The database is in MySQL but all that is fine, its just the formatting I'm struggling with. Even without using a variable in the formatting code the script crashes while the php tag is in effect.
Can anyone offer any advice on where my problem is or suggest another alternative to this.
Thanks!
You need to break out of PHP ?> before HTML and then switch back to PHP <?php before more PHP code
$value = 20;
$units = "px";
for ($x=0; $x<=2; $x++) {
$pix = $value . $units;
?>
<div style="position:absolute;left:10px;top:<?php echo $pix ?>;width:100px;height:<?php echo $pix ?>;z- index:5;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:15px;">Field Name:</span></div>
<?php
$value += 150;
}
Or for the HTML you can echo it from PHP:
echo '<div style="position:absolute;left:10px;top:' . $pix . ';width:100px;height:' . $pix . ';z- index:5;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:15px;">Field Name:</span></div>';

Use search output string to open a local network file

I have been trying for ages with all types of "file, file_get_contents, fopen, opendir and etc" to acomplish what I am triying to do, but just no can do for me, this goes beyong my understanding, sadly. But here I am to learn.
What I want to do? I work with LucidWorks, and I have built an Intranet search that searches the specific path given "C://example/example/..." and does a full text search through all the files. The output of the search on my intranet website is simple:
Document title
Body title with highlighted keyowrds
Path to the file
Now, that not being enough, my lazy fellow Companions would like to be able to click the Document title(which does indeed have a full path to the document behind it, just so you can picture it better "C:/Ex/ex/ex/docs/sap/text.txt(or any other termination)) and open it locally.
Here is the part of the code that I believe to be relevant for what I am trying to acomplish. The "solution" i have built in does not work, but it may give you an idea of what I am trying to accomplish here.
$searchParams = array(
'hl' => 'true',
'hl.fl' => 'body'
);
$response = $LWS->search($query, $offset, $limit, $searchParams);
if ($response->response->numFound > 0) {
foreach ($response->response->docs as $doc) {
?>
<div id="resultbox">
<span id="resulttitle"> <?php echo "<a href={$doc->id}'>{$doc->title}</a><br />"; ?> </span>
<?php
$content = (("{$doc->id}'>{$doc->title}"));
print_r( '<a href= ' . fopen(str_replace('%', ' ', $content), "r+") . '>Open File</a><br />');
?>
<SPAN ID="copytext" >
<?php echo substr($content, -100); ?>
<br></SPAN>
<div id="sbody">
<?php
echo "..." . $response->highlighting->{$doc->id}->body[0] . "...<br /><br />";
}
echo '<br />';
return;
} else {
echo "No results for \"" . $query . "\"";
return;
}
?>
There is a little bit more code above it, but it's irrelevant for the asked question.
So there you go folks, I am hoping for help, and to be able to learn something new :)
It looks as though you're trying to put the contents of the files into the href attribute of you anchor/link (<a>) tag.
What you need to be doing, instead, is using a url which links to the specified file. This could possibly look like this in your implementation;
print_r('Open File<br />');
and the output would look something like;
Open File<br />

Categories