How to rewrite HTML in to PHP echoes? - javascript

I am trying to split my last post into more sections.
I am working with AJAX & Database. The goal is to a have a clickable division (button) in a view. When this div is clicked the AJAX query is called and retrieves 5 movies from my DB and displays them in the view. What I am struggling the most with, is how to style the newly retrieved array, that I am displaying with jquery in the original division.
I am trying to follow this w3schools tutorial. I am trying to rework my original styling according to how it is done in the tutorial. But I do not know how to write all the opening tags with their attributes into the echoes.
So if anyone here would be so kind and could show me how to rewrite at least few of them I would really appreciate it. All the lines starting with the comment <!--fix--> are those I need to rewrite.
EDIT ----------------------------------------------------
The problem is that I have a CI view page. On that page is a division with content. I am trying to replace this content with new content retrieved using the xmlhttp request. The request calls a file that establishes connection with my DB, runs the query, stores the result in an array and then echoes back the result already split and styled using the while loop. Below is the content of the file called by the jquery request.
<?php
$con = mysqli_connect('localhost','root','root','obs2');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"obs2");
$sql="SELECT * FROM user WHERE id > 5";
$result = mysqli_query($con,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result))
{
<a style="display:block" href="<?php echo base_url('core/detail/'.$row->id) ?>">
<div id="suggested" onmouseover="" style="cursor: pointer;">
<div id="info">
<div id="info_center">
<p><b><?php echo $row->name ?></b></p>
</div>
</div>
<div class="mosaic-block fade">
<a href="<?php echo base_url('core/detail/'.$row->id) ?>" class="mosaic-overlay">
<div class="details">
<p><?php echo $row->summary ?></p>
</div>
</a>
<div class="mosaic-backdrop"><img src="http://puu.sh/5DSWj.jpg"></div>
</div>
<div id="info">
<div id="info_center">
<p>Rating: 7.7</p>
</div>
</div>
</div>
</a>
}
echo "</table>";
?>
So from what I understand from the tutorial is that I need to be echoing each of the lines in inside the while loop. And what I do not know is how to rewrite all the tags and the php echoes that are already in there. I hope this makes it more clear.
----------------------------------------------------
original code
<table>
<?php foreach ($pages->result() as $row): ?>
<a style="display:block" href="<?php echo base_url('core/detail/'.$row->id) ?>">
<div id="suggested" onmouseover="" style="cursor: pointer;">
<div id="info">
<div id="info_center">
<p><b><?php echo $row->name ?></b></p>
</div>
</div>
<div class="mosaic-block fade">
<a href="<?php echo base_url('core/detail/'.$row->id) ?>" class="mosaic-overlay">
<div class="details">
<p><?php echo $row->summary ?></p>
</div>
</a>
<div class="mosaic-backdrop"><img src="http://puu.sh/5DSWj.jpg"></div>
</div>
<div id="info">
<div id="info_center">
<p>Rating: 7.7</p>
</div>
</div>
</div>
</a>
<?php endforeach; ?>
</table>
according to this
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
progress
echo "<table>";
while($row = mysqli_fetch_array($result))
{
<!--fix--><a style="display:block" href="<?php echo base_url('core/detail/'.$row->id) ?>">
<!--fix--><div id="suggested" onmouseover="" style="cursor: pointer;">
<!--fix--> <div id="info">
<!--fix--> <div id="info_center">
echo "<p>" . $row['name'] . "</p>";
echo "</div>";
echo "</div>";
<!--fix--> <div class="mosaic-block fade">
<!--fix--> <a href="<?php echo base_url('core/detail/'.$row->id) ?>" class="mosaic-overlay">
<!--fix--> <div class="details">
echo "<p>" . $row['summary'] . "</p>";
echo "</div>";
echo "</a>";
<!--fix--> <div class="mosaic-backdrop"><img src="http://puu.sh/5DSWj.jpg"></div>
echo "</div>";
<!--fix--> <div id="info">
<!--fix--> <div id="info_center">
<!--fix--> <p>Rating: 7.7</p>
echo "</div>";
echo "</div>";
echo "</div>";
echo "</a>";
}
echo "</table>";

Your original code is the CORRECT way to do it. The w3schools version is completely wrong and you should avoid that.
Everyone would be better able to assist you if you try to describe what is NOT working with your original code.

Don't follow the convention used in that tutorial. Not only can't you trust everything W3schools says (they even say that in their disclaimer), but it's just less readable. Especially when you have a propert editor, you can benefit from code highlighting in your HTML. That will be gone if you echo all your html. Apart from that you just clutter your code, and you have to escape every quote. Long story short: don't do that. :)
Regarding the echos of the values inside the html, you can shorten this:
<?php echo base_url('core/detail/'.$row->id) ?>
to this:
<?=base_url('core/detail/'.$row->id) ?>
<?= is just a shorthand. I think it even works when the short opening tag (<?) is disabled, but if you want your code to be independent of that setting you should verify that.
Also, though I prefer the { .. } style of blocks, I think using : ... endforeach is much clearer when combined with HTML. So I wouldn't change that either.
If you do want to change it anyway, you will still need the PHP closing tag, which you have forgotten now. So:
while($row = mysqli_fetch_array($result)): ?>
becomes:
while($row = mysqli_fetch_array($result))
{ ?>
Of course you can put { ?> or only the { on the same line as the while statement, if you like.
[edit]
Regarding your comment: Everything outside PHP tags gets outputted as-is. So the code:
Hello <?php echo 'lovely'; ?> world <?php /* More code without output*/ ?>
results in the phrase:
Hello lovely world
So as you can see, it is often much easier to put large chunks of plain text/html outside of PHP tags, and only briefly open and close PHP tags to echo some variable content.

Related

Is there a way to get all fetched ids from a PHP while loop?

I want to know if I can get all fetched ids from a PHP while loop to use them in a jQuery for a flip effect?
while ($fetch_locomotion = mysqli_fetch_assoc($result_locomotion))
{
$id = $fetch_locomotion['id'];
echo
'<a href="index.php?price='.$hash.'" style="text-decoration: none;" id="object_a_jquery">
<div id="'.$id.'" style="perspective:1000px;height:100%;width:13%;display:inline-table;">
<div class="front">
<div id="object_list_price_bg" style="background-image:url(images/bg_price_f.png);"></div>
</div>
<div class="back">
<div id="object_list_price_bg_b" style="background-image:url(images/bg_price.png);"></div>
</div>
</div>
</a>';
}
<script>$(<?php echo $id;?>).flip();</script>
You can dump them into an array and use them at a later time.
// do this before entering the loop so it isn't overwritten
$ids = [];
// Do this part inside of the while loop
$ids[] = $fetch_locomotion ['id'];
?>
/* do this part in the html section you wish to execute the javascript code */
<script>
jQuery(function ($) {
<?php foreach ($ids as $id): ?>
<?php echo "$('#". $id . "').flip();\n"; ?>
<?php endforeach; ?>
});
</script>
Edited for your exact code:
$ids = [];
while ($fetch_locomotion = mysqli_fetch_assoc($result_locomotion))
{
$ids[] = $fetch_locomotion['id'];
echo
'<a href="index.php?price='.$hash.'" style="text-decoration: none;" id="object_a_jquery">
<div id="'. $fetch_locomotion ['id'] .'" style="perspective:1000px;height:100%;width:13%;display:inline-table;">
<div class="front">
<div id="object_list_price_bg" style="background-image:url(images/bg_price_f.png);"></div>
</div>
<div class="back">
<div id="object_list_price_bg_b" style="background-image:url(images/bg_price.png);"></div>
</div>
</div>
</a>';
}
<script>
jQuery(function ($) {
<?php foreach ($ids as $id): ?>
<?php echo "$('#". $id . "').flip();\n"; ?>
<?php endforeach; ?>
});
</script>
I would suggest adding a class attribute and querying on it (instead of each ID separately).
Also, using the alternative PHP syntax would be cleaner in this context.
This becomes:
<?php while ($fetch_locomotion = mysqli_fetch_assoc($result_locomotion)): ?>
<a href="index.php?price=<?= $hash ?>" style="text-decoration: none;" id="object_a_jquery_<?= $id ?>">
<div id="<?= $fetch_locomotion['id'] ?>" class="js-flipMe" style="perspective:1000px;height:100%;width:13%;display:inline-table;">
<div class="front">
<div id="object_list_price_bg" style="background-image:url(images/bg_price_f.png);"></div>
</div>
<div class="back">
<div id="object_list_price_bg_b" style="background-image:url(images/bg_price.png);"></div>
</div>
</div>
</a>
<?php endwhile ?>
<script>
jQuery(function ($) {
$('.js-flipMe').flip();
});
</script>
Note that I also changed your <a>'s id attribute to be unique, as it should be.

PHP/HTML Add onclick function to subcategories with certain name

I am trying to add an onclick function for only certain recursively generated subcategories.
This code currently displays the subcategories correctly:
<?php if($parent) { ?>
<?php $search_params['sCategory'] = $parent['pk_i_id']; ?>
<a href="<?php echo osc_search_url($search_params); ?>" class="parent active" data-name="sCategory" data-val="<?php echo $parent['pk_i_id']; ?>">
<span class="name"><?php echo $parent['s_name']; ?></span><em>(<?php echo ($parent['i_num_items'] == '' ? 0 : $parent['i_num_items']); ?>)</em>
</a>
<?php } ?>
<?php foreach($categories as $c) { ?>
<?php $search_params['sCategory'] = $c['pk_i_id']; ?>
<a href="<?php echo osc_search_url($search_params); ?>" class="child<?php if($c['pk_i_id'] == $search_cat_id) { ?> active<?php } ?>" data-name="sCategory" data-val="<?php echo $c['pk_i_id']; $
<span class="name"><?php echo $c['s_name'];?></span><em>(<?php echo ($c['i_num_items'] == '' ? 0 : $c['i_num_items']); ?>)</em>
</a>
<?php } ?>
</div>
I would like to call say functionX(); written in JS for only the subcategory named "catx".
FunctionX() is working correctly when called else where.
I've tried something like this but get a White screen:
<?php if($search_params == "catX") {
echo '<a onclick="functionX();" href="<?php echo osc_search_url($search_params); ?>" class="parent active" data-name="sCategory" data-val="<?php echo $parent['pk_i_id']; ?>">
<span class="name"><?php echo $parent['s_name']; ?></span><em>(<?php echo ($parent['i_num_items'] == '' ? 0 : $parent['i_num_items']); ?>)</em>
</a>;'
} else {
echo '<a href="<?php echo osc_search_url($search_params); ?>" class="parent active" data-name="sCategory" data-val="<?php echo $parent['pk_i_id']; ?>">
<span class="name"><?php echo $parent['s_name']; ?></span><em>(<?php echo ($parent['i_num_items'] == '' ? 0 : $parent['i_num_items']); ?>)</em>
</a>;' ?>
Pretty new to this, thanks for the help!
When you use an echo you are using ' to specify the borders of what you are going to output.
In your code you have echo 'Some content' but your content contains an ' aswell. Named: $parent['pk_i_id']
There a several ways to do this. Here is an example (Concatenation):
echo '<a onclick="functionX();" href="' . osc_search_url($search_params) . '">Click me</a>'; // ...
The inline notation is useful, in case you have surrounding HTML-Code:
<b>My name is<?php echo $name ?></b>
Just dont mix em :)
It's not an approach that works for everyone but in this kind of scenario I find it visually helpful (and very useful if I need to debug anything) to incrementally build a string using
statements
variables; and
conditional statements
and then echo the string, once I have built it.
Example:
<?php
$Item_Number = ($parent['i_num_items'] === '') ? 0 : $parent['i_num_items'];
$Link = '';
$Link .= '<a ';
if ($search_params === 'catX') {
$Link .= 'onclick="functionX();" ';
}
$Link .= 'href="'.osc_search_url($search_params).'" class="parent active" data-name="sCategory" data-val="'.$parent['pk_i_id'].'">';
$Link .= '<span class="name">'.$parent['s_name'].'</span>';
$Link .= '<em>('.$Item_Number.')</em>';
$Link .= '</a>';
echo $Link;
?>

Adding a second custom field

I have a custom field 'ExtraCSS' which brings in custom post css using the following code. (It is brought in from a 'have_posts()' loop)
html
<?php $extraCSS = get_post_meta(get_the_ID(),'ExtraCSS',true);?><!-- get specific css for post -->
<article>
<div id="post-<?php the_ID(); ?>" class="img-cell" style="background-image:url('<?php echo $thumbnail_url ?>');" <?php post_class('col-md-12'); ?> >
<a class="linkage" href="<?php the_permalink(); ?>"</a>
</div><!-- /#post -->
<div class="text-cell">
<div class="<?php echo $extraCSS?>" >
<h1><?php the_title(); ?></h1>
<h3><?php the_category(', '); ?></h3>
</div>
</div>
</article>
*EDIT
I want to add 1 more custom field ('BG-align') with either values 'BG-align-L' or 'BG-align-R'. I figured I just add another similar line of code under the current one.
ex.
<?php $extraCSS = get_post_meta(get_the_ID(),'ExtraCSS',true);?>
<?php $BGalign = get_post_meta(get_the_ID(),'BGalign',true);?>
but it doesn't work
According to *edit:
'BGalign' have to be defined in post (by "Add New Custom Field"), otherwise it is just empty.
You could set default value (edit "default-value") if not set in post:
<?php
$BGalign = get_post_meta(get_the_ID(),'BGalign',true);
$BGalign = ( !empty($BGalign) ? $BGalign : "default-value" );
?>
Then remember to echo that new php variable. For example:
<div class="<?php echo $extraCSS . " " . $BGalign; ?>" >
. is dot joining variables into one string
" " is empty space for sure that your both classes names will not be connected

jQuery addClass within a foreach loop

I have a few foreach loops with a trigger and a content div. The intent is for the trigger to be clicked, then addClass to content div, making it visible on screen.
foreach markup
<?php foreach( $posts as $post ) : ?>
<a class="slide-trigger" href="#loc<?php echo $post->ID;?>"><?php the_title(); ?></a>
<span>
<?php
$speakers = get_field('speakers');
?>
<?php if( $speakers ): ?>
<ul class="flat">
<?php foreach( $speakers as $speaker ): ?>
<li>
<a href="<?php echo get_permalink( $speaker->ID ); ?>">
<?php echo get_the_title( $speaker->ID ); ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</span>
<div class="slide" id="loc<?php echo $post->ID;?>">
<div class="close"></div>
<?php echo $post->post_title;?>
<?php echo $post->post_content;?>
</div>
<?php endforeach; ?>
jQuery
$(".slide-toggle[href^='#loc']").click(function(e){
e.preventDefault();
$(".slide[id^='loc']").addClass("open");
})
$(".close").click(function(){
$(".slide").removeClass("open");
});
What I'm looking for is each slide-toggle to trigger it's slide.
Any thoughts?
The ID is in the href, so just grab it and remove the #loc prefix, then you can select the corresponding slide to open. Also this way, the startsWith selector is no longer required.
$(".slide-toggle[href^='#loc']").click(function(e){
e.preventDefault();
$(".slide[id='loc" + this.href.replace('#loc', '') + "']").addClass("open");
})
Having to parse out the ID, then concatenate like this seems a bit hacky. It would be nicer to use data-* attributes.
Link:
<a class="slide-trigger" data-id="<?php echo $post->ID;?>" href="#loc<?php echo $post->ID;?>"><?php the_title(); ?></a>
Slide:
<div class="slide" data-id="<?php echo $post->ID;?>" id="loc<?php echo $post->ID;?>">
jQuery:
$(".slide-toggle[data-id]").click(function(e){
e.preventDefault();
$(".slide[data-id=" + $(this).data('id') + "]").addClass("open");
})
#MrCode had two great solutions to this. The data-id method is a bit more elegant and what I went with.
Note, the $post->ID is a number which just won't work as an id= - https://css-tricks.com/ids-cannot-start-with-a-number/ - and was causing the issue where things just wouldn't work.
The answer; follow #MrCode's method of using a data attribute. It's elegant and works great w/ the loop.

Dynamic jQuery with same ID

Im trying to make a dynamic jQuery function with some help from Advanced Custom Fields in Wordpress. This may not have something to do with the question, but I work in Wordpress with this plugin, anyway.
My code is like this:
<div id="restaurangmeny">
<h2>Vår meny</h2>
<? if( get_field('meny_for_restaurangen') ): ?>
<?php while( has_sub_field('meny_for_restaurangen') ): ?>
<div class="kategori">
<div class="kategorinamn" id="<?php the_sub_field('namn_for_kategorin'); ?>"><?php the_sub_field('namn_for_kategorin'); ?></div>
<div class="matratter" id="<?php the_sub_field('namn_for_kategorin'); ?>">
<? if( get_sub_field('matratter') ): ?>
<?php while( has_sub_field('matratter') ): ?>
<div class="matratt">
<div class="left">
<div class="namn"><?php the_sub_field('namn_pa_matratt'); ?></div>
<div class="beskrivning"><?php the_sub_field('beskrivning_av_matratten'); ?></div>
</div>
<div class="pris"><?php the_sub_field('pris_pa_matratten'); ?>:-</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div><!--#restaurangmeny-->
So what I want is when I click on the div called "kategorinamn" I want to div called "matratter" be shown or hidden. That's why I use same id for "kategorinamn" and "matratter" just because these 2 belong together.
Simply, if I click on 1 I want everything that got the same id (1) be shown. If I click on 2 I want everything that got the same id (2) be shown.
I don't know what dynamic jQuery like this is called, but I'm far away from being good with jQuery so that's why I'm asking.
Something like this http://jsfiddle.net/gwK6d/18/, but with jQuery only and that fit's my code above.
1) Import jquery
2) Make sure you are not using the same id for multiple elements
3) Change this bit:
<div class="kategorinamn" id="<?php the_sub_field('namn_for_kategorin'); ?>"><?php the_sub_field('namn_for_kategorin'); ?></div>
<div class="matratter" id="<?php the_sub_field('namn_for_kategorin'); ?>">
To this:
<div class="kategorinamn" id="<?php the_sub_field('namn_for_kategorin'); ?>">
<?php the_sub_field('namn_for_kategorin'); ?>
<div class="matratter" id="<?php the_sub_field('namn_for_kategorin'); ?>">
</div>
4) Declare this function after load:
$(".kategorinamn").click(function(){
$(this).children('.matratter').toggle();
});
JSFIDDLE: http://jsfiddle.net/uRpc8/

Categories