foreach slider only shows one db entry - javascript

I've got an array which gets all the testimonials from the database table and displays them via a foreach array. I want some kind of a slider which fades-in and fades-out the results.
This is my query:
$showTestimonials = array();
$getTestimonials = mysqli_query($mysqli,"SELECT * FROM testimonials ORDER BY testimonial_id DESC") OR die (mysqli_error($mysqli));
while($row = mysqli_fetch_array($getTestimonials)){
$row = array(
'testimonialName' => $row['name'],
'testimonialMessage' => $row['message']);
$showTestimonials[] = $row;
}
My PHP foreach code:
$count = 0;
foreach ($showTestimonials as $stt):
echo '<div class="content welcome features container">';
echo '<div class="content welcome features testimonial">';
echo '<div id="goSlide">';
if($count == 0) {
echo '<div class="slide show">';
echo '<div>'.$stt['testimonialMessage'].' '.$stt['dModel'].'</div>';
echo '<div>'.$stt['testimonialName'].'</div>';
echo '</div>';
}
echo '</div>';
echo '</div>';
echo '</div>';
$count++;
endforeach;
My piece of Javascript code
$(document).ready(function(){
var slides = $('#goSlide > .slide').length;
var current = 0;
setInterval(function() {
var next = ( ( current + 1 ) == slides ? 0 : current + 1 );
$( $( "#goSlide > .slide" )[ current ] ).fadeOut(1000).removeClass(".show");
$( $( "#goSlide > .slide" )[ next ] ).fadeIn(1000);
current = next;
}, 4000);
});
It's currently only showing ONE (the latest in the database) and only fades-in and out that one. It does not show the other testimonials.

The problem is you are updating $row inside the loop
while($row = mysqli_fetch_array($getTestimonials)){
$row = array( <---- here $row is getting updated
'testimonialName' => $row['name'],
'testimonialMessage' => $row['message']);
$showTestimonials[] = $row;
}
change it to
while($row = mysqli_fetch_array($getTestimonials)){
$row_1 = array(
'testimonialName' => $row['name'],
'testimonialMessage' => $row['message']);
$showTestimonials[] = $row_1;
}

Related

Is there any way to working with only one array with jQuery.each()?

I have a project where I filter the elements by clicking on the checkbox. I think biggest problem is with jQuery.each() function. You can see code below what it does. I need to create only one array and filter values only in this array, because now, i am getting duplicates. Is there any way how to fix this with jQuery.each() or i need to use another function? I know how this problem arises, but I didn't find a solution.
Of course, data for every checkbox are mixed. For example, some data fall under all checkboxes, another data only to one checkbox etc. You can see get_filter function.
filter_data();
function filter_data()
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var brand = get_filter('brand');
var jackpot = get_filter('jackpot');
var volatility = get_filter('volatility');
var special_features = get_filter('special_features');
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, brand:brand, jackpot:jackpot, volatility:volatility, special_features:special_features},
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
console.log(filter);
});
return filter;
}
$('.common_selector').click(function(){
filter_data();
});
fetch_data.php
<?php
//fetch_data.php
include 'template.php';
$pdo = pdo_connect_mysql();
if(isset($_POST["action"]))
{
$query = ('SELECT * FROM slotselect.slot WHERE 1');
$query2 = ('SELECT * FROM slotselect.slot, slotselect.slot_features, slotselect.special_features WHERE slot_features.id_slot = slot.id_slot AND slot_features.id_sf = special_features.id_sf');
if(isset($_POST["special_features"]))
{
$sf_filter = implode("','", $_POST["special_features"]);
$query .= " AND special_features.id_sf IN('".$sf_filter."') ";
$query2 .= " AND special_features.id_sf IN('".$sf_filter."') ";
}
if(isset($_POST["brand"]))
{
$brand_filter = implode("','", $_POST["brand"]);
$query .= " AND id_provider IN('".$brand_filter."') ";
$query2 .= " AND id_provider IN('".$brand_filter."') ";
}
if(isset($_POST["jackpot"]))
{
$jackpot_filter = implode("','", $_POST["jackpot"]);
$query .= " AND id_jackpot IN('".$jackpot_filter."') ";
$query2 .= " AND id_jackpot IN('".$jackpot_filter."') ";
}
if(isset($_POST["volatility"]))
{
$volatility_filter = implode("','", $_POST["volatility"]);
$query .= " AND id_vol IN('".$volatility_filter."') ";
$query2 .= " AND id_vol IN('".$volatility_filter."') ";
}
$statement = $pdo->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if(isset($_POST["special_features"]))
{
$statement = $pdo->prepare($query2);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$pom= $row['id_provider'];
$pom2= $row['id_slot'];
$provi = $pdo->prepare('SELECT logo FROM slotselect.provider WHERE id_provider = ?');
$provi->execute([$pom]);
$provik = $provi->fetch(PDO::FETCH_ASSOC);
$name = $pdo->prepare('SELECT name FROM slotselect.slot WHERE id_slot = ?');
$name->execute([$pom2]);
$namee = $name->fetch(PDO::FETCH_ASSOC);
$output .= '
<div class="col-sm-6 col-lg-4 col-xl-3 wow bounceInUp" data-wow-duration="1.4s" id="services">
<div class="box">
<div class="logo pasik">
<img src="admin/uploads/'. $provik['logo']. '" width="80" height="60">
</div>
<img src="admin/uploads/'. $row['image'] . '" width="100%" height="150">
<p></p>
<h4 class="title">'.$namee['name'].'</h4>
<p></p>
View
<p></p>
</div>
</div>';
}
}
else
{
$output = '<h3>No Data Found</h3>';
}
echo $output;
}
if($total_row > 0)
{
foreach($result as $row)
{
$pom= $row['id_provider'];
$pom2= $row['id_slot'];
$provi = $pdo->prepare('SELECT logo FROM slotselect.provider WHERE id_provider = ?');
$provi->execute([$pom]);
$provik = $provi->fetch(PDO::FETCH_ASSOC);
$name = $pdo->prepare('SELECT name FROM slotselect.slot WHERE id_slot = ?');
$name->execute([$pom2]);
$namee = $name->fetch(PDO::FETCH_ASSOC);
$output .= '
<div class="col-sm-6 col-lg-4 col-xl-3 wow bounceInUp" data-wow-duration="1.4s" id="services">
<div class="box">
<div class="logo pasik">
<img src="admin/uploads/'. $provik['logo']. '" width="80" height="60">
</div>
<img src="admin/uploads/'. $row['image'] . '" width="100%" height="150">
<p></p>
<h4 class="title">'. $namee['name']. '</h4>
<p></p>
View
<p></p>
</div>
</div>
';
}
}
else
{
$output = '<h3>No Data Found</h3>';
}
echo $output;
}
?>
Some examples:
https://imgur.com/UbeZv72
https://imgur.com/DzMvIMe
https://imgur.com/NTIMbtg
If you just want to transmit one Array with all the ID's to your fetch_data.php you coud rewrite your js-code like this:
var filter_array = [
'brand',
'jackpot',
'volatility',
'special_features'
];
filter_data(filter_array);
function filter_data(filter_array)
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var selected_filters = get_filter(filter_array);
console.log(selected_filters);
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, filters:selected_filters}, //selected_filters Structure = [brand:'brand_value',jackpot:'jackpot_value', ... ]
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(filter_array, filter = []){
if (filter_array === undefined || filter_array.length == 0) { //check if array exists or if there are filters left to add
var class_name = filter_array.shift(); //Removes and returns first element of filter_array
$('.'+class_name+':checked').each(function(){
filter[class_name] = $(this).val();
get_filter(filter_array,filter); //called recursivly as long as there are filters to add
});
}
else{
return filter;
}
}
$('.common_selector').click(function(){
filter_data();
});
This might not use jquery.each() but it will produce an array with all the checked boxes names and values which you can iterate in you php by using foreach like this:
foreach($_POST['filters'] as $key => $value){
//$key = the name of the checkbox selector | $value = the value of the associated checkbox
}
This code is NOT TESTET, but i still hope it helps.

JavaScript/AJAX prints weirdly

My JavaScript/AJAX prints comments. It's all good, until I want to insert/get more than one comment. It duplicates itself. This feels like a nesting/missed parenthesis problem in my code, but I can't be able to find it...
My JS code:
$(document).ready(function(){
var url = 'comment-get.inc.php';
$.getJSON(url, function(data) {
$.each(data, function(index, item) {
var t = '';
t += '<div class="comment_holder" id="_'+item.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+item.username+'<br>';
t += ''+item.date+'<br>';
t += '<button class="button2" type="button" id="'+item.id+'">Delete</button>';
t += '</div></div>';
t += ''+item.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
});
});
add_delete_handlers();
$('#postButton').click(function(){
comment_post_btn_click();
});
function comment_post_btn_click()
{
//text in textarea with username, page and date
var _username = $('#postUsername').val();
var _page = $('#postPage').val();
var _date = $('#postDate').val();
var _message = $('#postMessage').val();
if(_message.length > 0)
{
//proceed with ajax callback
$('#postMessage').css('border', '1px solid #ABABAB');
$.post("comment-set.inc.php",
{
task : "comment-set",
username : _username,
page : _page,
date : _date,
message : _message
}
).success(
function(data)
{
//Task: Insert html into the div
comment_set(jQuery.parseJSON(data));
console.log("ResponseText: " + data);
});
}
else
{
//text in area is empty
$('#postMessage').css('border', '1px solid #FF0000');
console.log("Comment is empty");
}
//remove text after posting
$('#postMessage').val("");
}
function add_delete_handlers()
{
$('.button2').each(function()
{
var btn = this;
$(btn).click(function()
{
comment_delete(btn.id);
});
});
}
function comment_delete(_id)
{
$.post("comment-del.inc.php",
{
task : "comment-del",
id : _id
}
).success(
function(data)
{
$('#_' + _id).detach();
});
}
function comment_set(data)
{
var t = '';
t += '<div class="comment_holder" id="_'+data.comment.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+data.comment.username+'<br>';
t += ''+data.comment.date+'<br>';
t += '<button class="button2" type="button" id="'+data.comment.id+'">Delete</button>';
t += '</div></div>';
t += ''+data.comment.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
}
});
Comments.php:
<?php
class Comments {
public function set($message, $username, $date, $page) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "INSERT INTO comments VALUES ('', '$username', '$page', '$date', '$message')";
$query = mysqli_query($connect, $sql);
if($query){
$std = new stdClass();
$std->id = mysqli_insert_id($connect);
$std->message = $message;
$std->username = $username;
$std->date = $date;
$std->page = $page;
return $std;
}
return null;
}
public function del($id) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "DELETE FROM comments WHERE id = $id";
$query = mysqli_query($connect, $sql);
if($query)
{
return true;
}
}
}
?>
Comment-get.inc.php:
<?php
$page = htmlentities("/index.php?page=maplepancakes", ENT_QUOTES);
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "SELECT * FROM comments WHERE page='$page' ORDER BY id DESC";
$result = $connect->query($sql);
$data = array();
while ($row = $result->fetch_assoc()) {
$row_data = array(
'id' => $row['id'],
'username' => $row['username'],
'date' => $row['date'],
'message' => $row['message']
);
array_push($data, $row_data);
}
?>
<?php
echo json_encode($data);
?>
Comment-set.inc.php:
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-set'){
$username = $_POST['username'];
$date = $_POST['date'];
$page = $_POST['page'];
$message = $_POST['message'];
require_once 'comments.php';
if(class_exists('Comments')){
$userInfo = $username;
$commentInfo = Comments::set($message, $username, $date, $page);
$std = new stdClass();
$std->user = $userInfo;
$std->comment = $commentInfo;
echo json_encode($std);
}
}
?>
Picture of the problem (json_encode in the bottom of the picture containing 3 comments):
your comments div container has class .comment_holder so each time with new comment you prepend to all class's so create comment container with unique id an prepend to this. like this $('#comment_container').prepend(t); this with work.

How to add custom html to ajax load more (wordpress)

I have added a "load more" button with ajax by following this posting...
Load More Posts Ajax Button in Wordpress
However, I need to add in some custom HTML for the content to sit in. I tried making a template and adding that into my ajax call but I couldn't get it working as the entire template would post 5 times.(I'm incrementing posts by 5). My question is, how do you structure the HTML in PHP for the ajax object?
My ajax function is here (in functions.php):
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 5;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$myposts = get_posts( $args );
$postcounter = 1;
$mediumcounter = 0;
$smallcounter = 0;
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
// 'cat' => 8,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
/******I NEED TO CHANGE THE BELOW*******/
$out .= '<div class="parent">
<h1>play ball '.get_the_title().'</h1>
<p>'.get_the_content().'</p>
</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
The template file I was trying to load up looks like this...
<?php
$args = array(
'posts_per_page' => 5
);
$myposts = get_posts( $args );
$postcounter = 1;
$mediumcounter = 0;
$smallcounter = 0;
foreach ( $myposts as $post ) : setup_postdata( $post );
if($postcounter == 1 ){
echo '<div class="parent">';
echo '<div class="single postwrapper child-2 postwrapper'.$postcounter.' mediumpost gray">';
}
else if($postcounter == 2 ){
echo '<div class="multi postwrapper child-2 ">';
echo '<div class="parent">';
}else{
$smallcounter = $smallcounter + 1;
if(in_array($smallcounter, array(1,2))){
$postcolor = 'blue';
}else{
$postcolor = 'gray';
}
}
echo '<div class="postwrapper child-2 postwrapper'.$postcounter.' smallpost '. $postcolor .'">';
get_template_part( 'homenew', get_post_format() );
echo '</div>';
if($postcounter == 1 || $postcounter == 5 ){
echo '</div>';
if($postcounter == 5){
echo '</div>';
}
}
$postcounter = $postcounter + 1;
endforeach;
wp_reset_postdata();?>
Would I have to write the template file out in the ajax function? Or just send post info to the javascript and append custom js with jquery?

Send and set 3 selected values from Dropdown menu to JavaScript function PHP

I have three drop down menus:
<?php
if(isset($som)) {
=======first drop down=======
echo "<select id="."som-patch1"." class="."form-control".">";
echo "<option value="."select".">Please Select SOM patch...</option>";
for ($i=0; $i < count($som) ; $i++) {
echo '<option value="'.$som[$i]['som'].'">'.$som[$i]['som'].' </option>';
}
echo "</select>";
=======second drop down=======
echo "<select id="."som-patch1-month"." class="."form-control".">";
echo "<option value="."select".">Please Select Month ...</option>";
for ($i=0; $i < 12 ; $i++) {
$month = date('F', strtotime('-'.$i.' month', strtotime(date('Y-m-01'))));
echo '<option value="'.$month.'">'.$month.'</option>';
}
echo "</select>";
=======third drop down=======
echo "<select id="."som-patch1-year"." class="."form-control".">";
echo "<option value="."select".">Please Select Year ...</option>";
for ($i=0; $i < 12 ; $i++) {
$year = date('Y', strtotime('-'.$i.' year', strtotime(date('Y-m-01'))));
echo '<option value="'.$year.'">'.$year.'</option>';
}
echo "</select>";
}
?>
I can successfully send the selected values to the following JavaScript function:
$('[id^=som-patch1]').on('change', function() {
alert( this.value );
});
The problem I have is:
I am unable to set the relevant values in the variables so that I could call the add_som_donut_chart_org_data() method.
Also I need to make sure all THREE values have been selected before the function call.
I have tried the following:
$('[id^=som-patch1]').on('change', function() {
var som = null;
var month = null;
var year = null;
if (id=='som-patch1'){
som = this.value;
}
alert( som );
});
But this doesn't set the som value.
The desired outcome should be:
if (som !== null && month !== null && year !== null) {add_som_donut_chart_org_data(som,month,year)}
Thanks in advance.
UPDATE: The following code resolved the issue
$('[id^=som-patch1]').on('change', function() {
var id = $(this).attr("id");
if (id == 'som-patch1') {
som = this.value;
}
if (id == 'som-patch1-month') {
month = this.value;
}
if (id == 'som-patch1-year') {
year = this.value;
}
if (som !== null && month !== null && year !== null) {
add_som_donut_chart_org_data(som,month,year);
}
});
As per your current code condition if (id=='som-patch1') would never be true, because id is not defined yet. Hence it will not set som variable. The reason is very basic that you have not defined id variable in your code. Before your condition use following code:
var id = $(this).attr("id");

How to change onhover list show/close in Magento Community

I have a minor problem.
Left side navigation menu toggle <--- website link - see left category navigation.
As you see in the link above, this is a left side navigation with toggle option. When clicking on the + sign the submenu gets unfolded and the + sign becomes a - sign, when clicking the - sign it gets back to normal.
The title on the left side is a link, when clicking on the title on the left it gets be directly ex. to the Fast Food category. However, I would like the title to have the same option as the +/- sign - and removing the link class.
The HTML code is:
<div class="block block-side-nav-container">
<div class="block-title">
<strong><span><?php echo $this->__('Categories') ?></span></strong>
</div>
<div class="block-content">
<div class="side-nav">
<ul id="category-treeview" class="treeview-side treeview">
<?php foreach ($this->getStoreCategories() as $_category): ?>
<?php echo $this->drawItem($_category) ?>
<?php endforeach ?>
</ul>
</div>
</div>
I might think that the code is a php language, please see below:
protected function _renderCategoryMenuItemHtml($category, $level = 0, $isLast = false, $isFirst = false,
$isOutermost = false, $outermostItemClass = '', $childrenWrapClass = '', $noEventAttributes = false)
{
if (!$category->getIsActive()) {
return '';
}
$html = array();
// get all children
if (Mage::helper('catalog/category_flat')->isEnabled()) {
$children = (array)$category->getChildrenNodes();
$childrenCount = count($children);
} else {
$children = $category->getChildren();
$childrenCount = $children->count();
}
$hasChildren = ($children && $childrenCount);
// select active children
$activeChildren = array();
foreach ($children as $child) {
if ($child->getIsActive()) {
$activeChildren[] = $child;
}
}
$activeChildrenCount = count($activeChildren);
$hasActiveChildren = ($activeChildrenCount > 0);
// prepare list item html classes
$classes = array();
$classes[] = 'level' . $level;
$classes[] = 'nav-' . $this->_getItemPosition($level);
if ($this->isCategoryActive($category)) {
$classes[] = 'active';
}
$linkClass = '';
if ($isOutermost && $outermostItemClass) {
$classes[] = $outermostItemClass;
$linkClass = ' class="'.$outermostItemClass.'"';
}
if ($isFirst) {
$classes[] = 'first';
}
if ($isLast) {
$classes[] = 'last';
}
if ($hasActiveChildren) {
$classes[] = 'parent';
}
// prepare list item attributes
$attributes = array();
if (count($classes) > 0) {
$attributes['class'] = implode(' ', $classes);
}
if ($hasActiveChildren && !$noEventAttributes) {
$attributes['onmouseover'] = 'toggleMenu(this,1)';
$attributes['onmouseout'] = 'toggleMenu(this,0)';
}
// assemble list item with attributes
$htmlLi = '<li';
foreach ($attributes as $attrName => $attrValue) {
$htmlLi .= ' ' . $attrName . '="' . str_replace('"', '\"', $attrValue) . '"';
}
$htmlLi .= '>';
$html[] = $htmlLi;
$html[] = '<a href="'.$this->getCategoryUrl($category).'"'.$linkClass.'>';
$html[] = '<span>' . $this->escapeHtml($category->getName()) . '</span>';
$html[] = '</a>';
// render children
$htmlChildren = '';
$j = 0;
foreach ($activeChildren as $child) {
$htmlChildren .= $this->_renderCategoryMenuItemHtml(
$child,
($level + 1),
($j == $activeChildrenCount - 1),
($j == 0),
false,
$outermostItemClass,
$childrenWrapClass,
$noEventAttributes
);
$j++;
}
if (!empty($htmlChildren)) {
if ($childrenWrapClass) {
$html[] = '<div class="' . $childrenWrapClass . '">';
}
$html[] = '<ul class="level' . $level . '">';
$html[] = $htmlChildren;
$html[] = '</ul>';
if ($childrenWrapClass) {
$html[] = '</div>';
}
}
$html[] = '</li>';
$html = implode("\n", $html);
return $html;
}
Please help.
Thank you!
You could fix this with jQuery.
All you have to do is add a slideToggle function to your menutitle.
First be sure to include jQuery in your site
Create a js file for little js fixes (i usually call it customjs.js) and include from the footer of your site
Add the following jQuery
$(".block-title").click(function(){
$(".block-content").slideToggle(); //SLIDE TOGGLE FOR SLIDING UP AND DOWN
return false; // PREVENTS LINK FROM WORKING
})
Check jsfiddle.net/pTg68/17/ for an example
Cheerz
Firstly find what the function is called, I would imagine it look something like this:
var menu = "closed";
function toggleMenu(){
if(menu = "closed"){
openTree();
}else{
closeTree();
}
}
function openTree(){
//code to open the menu
};
function closeTree(){
//code to close the menu
};
And all you would do is change the link from each category from
Fast Food
to
Fast Food

Categories