This is a part fo php code, which use the contentArray, which is a JSON, and generate the UI to the user, it generate html tags, also, it generate js code too.... It works, but I think the code is pretty difficult to read and maintain, any ideas??? thank you.
for($i = 0; $i < count($contentArray); $i++){
if($i %2 == 0){
echo ("<li class='even_row'>");
}else{
echo ("<li class='odd_row'>");
}
$content = $contentArray[$i];
echo("<textarea class='userdata' id='user_data_textarea_".$content->{'m_sId'}."'>");
echo($content->{'m_sDataContent'});
echo("</textarea>");
echo("</li>");
echo("<script type='text/javascript'>");
echo("$('#user_data_textarea_".$content->{'m_sId'}."').bind('keydown', function(e){");
echo(" TypingHandler.handleTypingInUserDataTextArea(".$content->{'m_sId'}.", e);");
echo(" });");
echo("</script>");
}
first for your odd and even styling there is not need for a class just use css
here is info on that
then in php only echo what you need in one line
$count = count($contentArray);
for($i = 0; $i < $count; $i++){
$content = $contentArray[$i];
echo('<li><textarea class="userdata" id="user_data_textarea_"'.$content->{'m_sId'}.'">'.$content->{'m_sDataContent'}.'</textarea></li>');
}
and lets put the jquery in the html page away from php
we get can get every item by using starts with selector
$('[id^=user_data_textarea_]').bind('keydown', function(e){
var id = this.id.str_replace("user_data_textarea","");
TypingHandler.handleTypingInUserDataTextArea(id, e);
});
One tip on your "for" loop, you should calculate the count of $contentArray before the loop. Every time the loop executes, it has to call that function.
$count = count($contentArray);
for ($i=0; $i<count; $i++) {
// ...
}
You could try real HTML:
<?php
for($i = 0; $i < count($contentArray); $i++){
$rowClass = $i %2 == 0 ?'even_row' : 'odd_row';
?>
<li class='<?= $rowClass ?>'>
<textarea class='userdata' id='user_data_textarea_<?=$content->{'m_sId'}?>'>
<?= $content->{'m_sDataContent'} ?>
</textarea>
</li>
<script type='text/javascript'>
//etc...
</script>
<?php } ?>
It should look something like this, for better readability in the IDE.
<?php
foreach($contentArray as $content){
?>
<li>
<textarea class="userdata" id="user_data_textarea<?php echo htmlentities($content['m_sId']); ?>">
<?php echo htmlspecialchars($content['m_sDataContent']); ?>
</textarea>
<script type="text/javascript">
$('#user_data_textarea_<?php echo htmlspecialchars($content['m_sId']); ?>').bind('keydown',function(e){
TypingHandler.handleTypingInUserDataTextArea('<?php echo htmlspecialchars($content['m_sId']); ?>',e);
});
</script>
</li>
<?php
}
You could remove the ( ) from the echo statements, they're not necessarily needed and might help make it look a little neater...
That actually looks pretty understandable to me; I could figure out what you're doing without difficulty. The only difference I would suggest would be the use of ternary operators for the row class:
echo "<li class='".( ($i%2 == 0) ? "even" : "odd" )."_row'>";
...but that's just me, some would find that MORE confusing, rather than less. I personally like putting it all in one line.
Personnaly, I like to use printf to write html code in php. It could look like:
for($i = 0; $i < count($contentArray); $i++){
printf("<li class='%s'>", $i % 2 ? "odd_row" : "even_row");
$content = $contentArray[$i];
printf("<textarea class='userdata' id='user_data_textarea_%s'>%s</textarea>",
$content->{'m_sId'},
$content->{'m_sDataContent'});
echo("</li>");
echo("<script type='text/javascript'>");
printf("$('#user_data_textarea_%1$s').bind('keydown', function(e){
TypingHandler.handleTypingInUserDataTextArea(%1$s, e);
});",
$content->{'m_sId'});
echo("</script>");
}
<?php
foreach($contentArray as $content){
$class = ($i %2 == 0) ? "even_row": "odd_row"; ?>
<li class="<?php echo $class ?>">
<textarea class='userdata' id='user_data_textarea_<? echo $content['m_sId'] ?>'>
<? php echo $content['m_sDataContent'] ?>
</textarea>
</li>
<script type='text/javascript'>
$('#user_data_textarea_<?php echo content['m_sId'] ?>').bind('keydown', function(e){
TypingHandler.handleTypingInUserDataTextArea(<?php $content['m_sId'] ?>, e);
});
</script>
<?php } // end foreach ?>
jQuery code should be already in the HTML, using some main selector and not binding elements one by one, it not makes sense for me. That should clarify your code.
for($i = 0; $i < count($contentArray); $i++){
$content = $contentArray[$i];
echo "<li class='" . (($i %2 == 0) ? "even_row" : "odd_row") . ">";
echo "<textarea class='userdata' id='user_data_textarea_".$content->{'m_sId'}."'>";
echo $content->{'m_sDataContent'};
echo "</textarea>";
echo "</li>";
}
ADDED
A generic case:
$(function() {
$('.userdata').click(function() {
some_function($(this).attr('id');
});
})
That is, bind using a class selector and late use some unique identifier for doing the job.
Put everything in arrays, then echo them at the END of your loop.
// Put each item in the array, then echo at the end
$items = array();
$js = array();
// I'm assuming that your content array has numeric keys
// if not, use the for statement from your original code
foreach ($contentArray as $i => $content)
{
// using sprintf
$items[] = sprintf('<li class="%s_row"><textarea class="userdata" id="user_data_textarea_%s">%s</textarea></li>'
, ($i % 2) ? 'even' : 'odd'
, $content->m_sId
, $content->m_sDataContent
);
// or just plain old concatenation
$js[] = "$('#user_data_textarea_{$content->m_sId}').bind('keydown', function(e){TypingHandler.handleTypingInUserDataTextArea({$content->m_sId}, e);});";
}
echo "<ul>" . join("\n", $items) . "</ul>\n"
. '<script type="text/javascript">' . join("\n", $js) . "</script>\n";
Separate your content and code using for example smarty. It requires some infrastructure investment in the short term, but improves maintenance in the long run.
Reflecting the comments, let's then treat PHP as a real templating language.
$contentCount = count($contentArray);
for($i = 0; $i < $contentCount; $i++)
{
$rowType = ( $i % 2 ) ? 'even' : 'odd';
$content = $contentArray[$i];
echo <<<EOT
<li class='{$rowType}_row'>
<textarea class='userdata' id='user_data_textarea_{$content->m_sId}'>
{$content->m_sDataContent}
</textarea>
</li>
<script type="text/javascript">
$('#user_data_textarea_{$content->m_sId}').bind('keydown', function(e)
{
TypingHandler.handleTypingInUserDataTextArea({$content->m_sId}, e);
}
</script>
EOT;
}
Related
So I have this php foreach-loop that gets data from my database.
I use a $i++ to number up the same div.
$i=0;
foreach ($pages as $page){
echo '<div class="class_'.$i++.'">
echo '</div>';
}
Now I have a piece of jQuery in my footer that does something to the <div>
<script>
jQuery(document).ready(function($){
$('.class_1');
$('.class_2');
$('.class_3');
});
</script>
Because I will never know how many instances there are I want the jQuery to add up with the foreach-loop but the script is outside the loop so it won't add up.
I don't really know my jQuery that much so any help would be appreciated.
M.
You can get every element with that class and then use $.each for it.
$('[class^="class_"]').each(function() {});
$i=0;
foreach ($pages as $page){
echo '<div class="class_'.$i++.'">';
echo '</div>';
}
echo '<div number-of-divs=' . $i . ' style="display:none;"/>';
Your js code:
<script>
jQuery(document).ready(function($){
var number = $('div[number-of-divs]').attr('number-of-divs');
for (i = 1; i <= number; i++) {
$('.class_' + i);
}
});
</script>
A good approach for this is you should pass another class in your code or pass this only if above is the only case. $('[class^="class_"]').each(function() {}); This will not work in some cases so use below code
$i=0;
foreach ($pages as $page){
echo '<div class="catch_me class_'.$i++.'">
echo '</div>';
}
and get it from this script
$('.catch_me').each(function(){
//You code here
});
I have this JS inside my php code:
echo " for (var i = 0; i<length; i++){
alert('array[i]');
}";
Assuming all variables were defined and initialized, i'm not getting any output from the alert.
However, if i replace array[i] with array[2], I get that value alerted.
any advice?
Updated variant:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['DayNum'];
}
$length = count($storeArray);
for($i=0; $i < $length; $i++) {
echo "alert(".$storeArray[$i].");";
}
You need a script tag..Its not possible to alert something the way you are doing it.
<script>//write your javascript here</script>
Example:
<?php
function alert($myArray)
{
echo '<script type="text/javascript">alert("' . $myArray . '"); </script>';
}
?>
Can it be length is not defined and you think it's giving you the array lenght? in that case you should have i < array.length otherwise length is thought to be a variable.
Check also that array[i] being an "array" where you get the values from in the for loop you don't need the '. Just write alert(array[i]);
alert('array[i]') in this part JavaScript not execute array[i] as variable, instead, it prints it as string because its enclosed with single quota, change it to:
echo '<script>';
echo '
for (var i = 0; i<length; i++){
alert(array[i]);
}
';
echo '</script>';
<?php echo "<script> for(var i=0; i<array.length; i++){alert(array[i]);} </script>"; ?>
I am studying PHP from a book. The author uses echo to output HTML. At first I thought that this was how it supposed to be done, but then I picked up a more "advanced" book. The author of the second book inserted PHP code between HTML rather then echo the whole thing. How is it done in large web development companies that work on large projects? Can you use either, or is one more accepted than the other?
Take this code for example:
<?php
//pagination
if ($pages > 1) {
//determine the current page
$current_page = ($start / $display) + 1;
//print out Previous Page button
if ($current_page != 1) {
?>
<div class="pages"><strong> < </strong></div>
<?php
}
//print the page numbers
for ($i = 1; $i <= $pages; $i++) {
if ($i == $current_page) {
?>
<div class="pages active"><span> <?php echo $i; ?> </span></div>
<?php
}
else {
?>
<div class="pages"><strong> <?php echo $i; ?> </strong></div>
<?php
}//end of $i = $current_page conditional
}//end of FOR loop
if ($current_page < $pages) {
?>
<div class="pages"><strong> > </strong></div>
<?php
}
}//end of pagination
include('includes/footer.php');
?>
Is that the correct way of doing it, or should I use something like this:
echo '<a href="view_users.php?s=' . ($display * ($i - 1)) .
'&p=' . $pages . '&sort=' . $sort . '">' . $i . '</a> ';
The reason why I'm asking is because I find it difficult to properly align the HTML when using the second technique, and I don't want to develop any bad habits early on.
The first method makes your code more readable. The second method is useful when you need to print some little amount of html code. Also you can use short open tags to insert your php code between html tags. For example if you need to print language parameter of URL you can do like this:
<a href="index.php?lang=<?=$lang?>" >A Link</a>
This is equal to this:
<a href="index.php?lang=<?php echo $lang; ?>" >A Link</a>
I'd recommend using a good framework in general, and a templating engine for outputting pages. This way, your data models, your application logic, and your HTML are all kept separate.
This is a somewhat subjective question, but:
echo '<a href="view_users.php?s=' . ($display * ($i - 1)) .
'&p=' . $pages . '&sort=' . $sort . '">' . $i . '</a> ';
This is not very good, because it quickly becomes hard to read. It's the worst option to use IMO.
Here an evolution on how this can be improved:
<a
href="view_users.php?s=<?php echo $display * ($i - 1); ?>&p=<?php echo $pages; ?>&sort=<?php echo $sort; ?>">
<?php echo $i; ?>
</a>
<?php
printf('%i',
$display * ($i - 1), $pages, $sort, $i);
?>
<?php
$q = http_build_query(array(
's' => $display * ($i - 1),
'p' => $pages,
'sort' => $sort
));
?>
<?php echo $i; ?>
<?php
printf('%i',
http_build_query(array(
's' => $display * ($i - 1),
'p' => $pages,
'sort' => $sort
)),
$i);
?>
Paul, what you're looking at in that code is a combination of PHP, CSS and HTML. echo just means print on page and it is a PHP function which is why you see it with the tags.
<?php ?>
Does this answer your question?
Also PHP and HTML and CSS will not parse any whitespace so indenting is done to enhance readability. I suggest you comment your code and format it however it is easier for you to understand. From a professional standpoint check out the W3C validator for proper code formatting.
Both are acceptable really, using echo for short statements and completely breaking out of php for long bits of html. Indentation of your HTML doesn't matter that much, it just looks pretty when someone checks out your source.
wrapping html generation in functions and building output strings can be a good practice. That way you can have complex logic expressed in a readable way:
<?php
function get_pagination_html($pages, $start, $display) {
$html = "";
if ($pages <= 1) return $html;
$current_page = ($start / $display) + 1;
if ($current_page != 1) {
$previous = $start - $display;
$html .= "<div class='pages'><strong><a href='view_users.php?s={$previous}&p={$pages}'> < </a></strong></div>";
}
for ($page_number = 1; $page_number <= $pages; $page_number++) {
if ($page_number == $current_page) {
$html .= "<div class='pages active'><span> {$page_number} </span></div>";
} else {
$page_start = $display * ($page_number - 1);
$html .= "<div class='pages'><strong><a href='iew_users.php?s={$page_start}>&p={$pages}'> {$page_number} </a></strong></div>";
}
}
if ($current_page < $pages) {
$next = $start + $display;
$html .= "<div class='pages'><strong><a href='view_users.php?s={$next}&p={$pages}'> > </a></strong></div>";
}
return $html;
}
echo get_pagination_html($pages, $start, $display);
Notice how much easier it reads. You also don't need any comments because variable names are self explanatory
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.
A complete beginners question.
I have a large number of divs (>80) on a page (page2.php) and what I would like to do is open page1.php, click on a link to open page2.php and show only one of these divs depending on which link was clicked.
I have a basic working version of this by adding an if else to the divs. I've only done this on 5 of the divs so far and it works but it also seems a fairly in-eloquent way of doing things.
Page 1:
this is a link
Page 2:
<?php
$divID = $_GET['id'];
?>
<div id="r0101" <? if($divID == r0101): ?>class="show"<? else: ?>class="hidden"<? endif; ?> >
This then applies a css class to hide or show the div.
Would it be possible to have a function or whatever at the top of the page that takes the id from the url, figures out that there is a div with that id also, show it and hide all the others? This is probably an easy thing to do but it has me stumped.
Any help greatly appreciated.
Thanks.
Let alone the divs and work on css (as you relay on that to hide/show the divs).
You can generate not only markup but css stylesheet too. Use a similar one (put it at
the end of your head section). And let the browser do the work for you ;)
<style type="text/css">
div {
display: none;
}
div#<?php echo $_GET['id']; ?>:{
display: block;
}
</style>
$divs = array('r0101', 'r0102', 'r0103');
$divID = $_GET['id'];
foreach($divs as $div)
{
echo '<div id="'.$div.'" class="';
if ($div == $divID)
{
echo 'show';
}
else
{
echo 'hidden';
}
echo '">';
}
Assuming I have read the question correctly, you have a set of divs (r0101, r0102, etc.) and wish to show only one of these depending on the page you are on. The code above creates an array of these divs, loops through and creates the div. The class of the div is 'show' if the div matches the div from the page url, and 'hidden' otherwise.
First of all, you should consider a way of making your divs to be printed dynamically. Something like:
<?php
for($i = 1; $i <= 80; $i++):
?>
<div id="r<?php print $i; ?>">div contents</div>
<?php
endfor;
?>
Also, if you find a way of doing what's stated above, you can also do something like:
<?php
for($i = 1; $i <= 80; $i++):
if($i == $_GET['id']){
$class = 'show';
} else {
$class = 'hidden';
}
?>
<div id="r<?php print $i; ?>" class="<?php print $class; ?>">div contents</div>
<?php
endfor;
?>
or
<?php
for($i = 1; $i <= 80; $i++):
$class = ($i == $_GET['id']) ? 'show' : 'hidden';
?>
<div id="r<?php print $i; ?>" class="<?php print $class; ?>">div contents</div>
<?php
endfor;
?>
which is exactly the same but (using the ternary operator) spares a few lines and (some people think) it decreases readability.
If you want to make your download faster, you should output only the div you want to show. You could do something like this:
$divs = array('r0101', 'r0102', 'r0103');
$divID = $_GET['id'];
foreach($divs as $div)
{
if($div == $divID){ echo '<div> /* CONTENT HERE */ </div> };
}
Hope this helps.