I have a wordpress site, and one of the functions has started working.
On my agenda page here: http://staging.chinahiking.cn/agenda/
it used to be that when you clicked the tabs, the upcoming trip would change. I just realized now it has stopped working, and I'm not sure why. What's even weirder is sometimes when I do a hard refresh, and while the page is still loading and I click the tabs, its working again, but when the page is fully loaded it stops working. Here is the JS function:
<?php get_header();
$cur_month = date('n');
$month = array(1=>"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
$agenda = get_agenda_by_month();
?>
var $=function(objectId){
if(document.getElementById&&document.getElementById(objectId)){
return document.getElementById(objectId)
}
else if(document.all&&document.all(objectId)){
return document.all(objectId)
}
else if(document.layers&&document.layers[objectId]){
return document.layers[objectId];
}
else{
return false;
}
};
function tabTurn(presObj, classon, showdiv){
var pObj = presObj.parentNode;
var items = pObj.getElementsByTagName('li');
for(var i=0; i<items.length; i++){
var n = i + 1;
var cntDiv = $('location_desc_' + n);
if(items[i] == presObj){
items[i].className=classon;
cntDiv.className = showdiv;
}
else{
items[i].className='off';
cntDiv.className = 'undis';
}
}
};
And here is the html:
<div class="monthes">
<div class="month_list">
<ul class="month">
<?php for($i=1; $i<=12; $i++){
if($i!=$cur_month)
echo "<li onclick=\"tabTurn(this, 'on', 'month_desc');\" class=\"off\">$month[$i]</li>";
else
echo "<li onclick=\"tabTurn(this, 'on', 'month_desc');\" class=\"on\">$month[$i]</li>";
}?>
</ul>
</div>
</div>
<?php
for($i=1; $i<=12; $i++):
if((isset($agenda[$i]))):
?>
<div id="location_desc_<?php echo $i;?>" class="month_desc <?php if($i!=$cur_month) echo "undis";?>">
Does anyone know why this would all of a sudden stop working? And only sometimes work while the page is still loading, but then stop once it's fully loaded?
I don't think you're using jquery properly. You should be using the addClass and removeClass functions.
Opening devtools on your site, I can make the page change by running:
$('#location_desc_6').addClass("undis")
$('#location_desc_8').removeClass("undis")
As a side note, the selectors need to start with # if you are wanting to select elements by id.
If you really wanted to use className = whatever then you would need to specify that you want to run on the first item returned by the selector, like:
$('#location_desc_6')[0].className = "undis"
Related
I want to trigger a JavaScript function after the page loads all the elements and I have to echo some HTTP request data into the page somewhere and use JavaScript to get the information from the DOM.
Therefore, I create the function and fire it on page load using jQuery but it didn't call the javascript (I think the DOM hasn't loaded) so how can I fix this?
<script>
$( document ).ready(function(){
myFunction(); // firing the function
});
</script>
<script>
function myFunction(){
var target = document.getElementById("target");
var formscount = target.textContent(); // the number of items from [#target]
alert(target);
if (formscount > 0) {
active="";
for (i=0; i < formscount; i++) {
var str='active'
if (i > 0){
str = ''
}
$('#DOM').append($('SOME HTML ELEMENTS');
event.preventDefault()
}
}
}
</script>
DOM Called (target) for passing the data ($_POST['itemscount']):
<?
$count = $_POST['itemscount'];
?>
<div id="target" style="display:none;">
<? $output = $_POST['productscount']; // or $Count //
echo htmlspecialchars($output);
?>
</div>
First, textContent is not a function.
So it should be written like this:
var formscount = target.textContent;
Second thing, you are missing the closing bracket ) in line $('#DOM').append($('SOME HTML ELEMENTS');
$('#DOM').append($('SOME HTML ELEMENTS'));
Third thing, event.preventDefault() will not work, as event is undefined. You may remove it.
and lastly, php tags begins with <?php and not with only <?.
<?php
$count = $_POST['itemscount'];
?>
<div id="target" style="display:none;">
<?php
$output = $_POST['productscount']; // or $Count //
echo htmlspecialchars($output);
?>
</div>
I have a website retrieving images from database. The database has multiple records (ROWS). I am using while loop to retrieve the records. Every record having three or four images. I want to use a horizontal image slider into the while loop to retrieve all the records. I searched in the net. there are lot of slider. But nothing was in the loop. if I put them into the loop it was not working. please help me some one.
example slider: http://wowslider.com/automatic-jquery-slider-noir-squares-demo.html?affid=331J-S9
for example:
<?php
While($row=mysql_fetch_array($result)){
**I need horizontal slider here**;
}
?>
I (obviously) won't write you you the whole widget but I'm wailing to give you all you need:
First, you need PHP. I suggest you to learn PDO. It's very easy to use and pretty safe:
Example:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
PDO documentation
Then, use HTML and CSS to style the thing.
Then, you use PHP to generate the HTML.
Then, you will use an javascript setInterval
Example for setInterval
setInterval(function() {
// Do something every 5 seconds
}, 5000);
If you need a different ID for each, the easiest way would be to do this:
$counter = 0;
foreach($foo as $bar){
echo '<div id="slider'.$counter.'"></div>';
//somecode
$counter++;
}
Tho, I do not recommand using this, you should just give one class to each of them and initiate them all at the same time in jQuery using the selector after
$('.slider').myPlugin({
//Plugins options
})
as per my understanding, it seems you're looking for this kind of solution.
Use of js "jquery.bxslider.js", required css "jquery.bxslider.css"
//assuming this is your database retrieval
$slideImage[] = "clody.jpg";
$slideImage[] = "heaven.jpg";
$slideImage[] = "park.jpg";
$slideImage[] = "pool.jpg";
$slideImage[] = "provence.jpg";
$slideStr = "";
//utlize while loop if required
foreach($slideImage as $indKey=>$indSlideImg) {
$slideStr .= '<div class="slide"><img src="http://wowslider.com/sliders/demo-5/data/tooltips/'.$indSlideImg.'" /></div>';
}
here in the above loop we created a sliding string, which we are going to utilize that into our slider.
<div class="bx-wrapper">
<div class="bx-viewport">
<div class="slider1">
<?php echo $slideStr; ?>
</div>
</div>
</div>
here comes the javascript
$(document).ready(function(){
$('.slider1').bxSlider({
slideWidth: 200,
minSlides: 2,
maxSlides: 3,
slideMargin: 10
});
});
hope it is helpful.
Here is my site.
If you hover over one of the projects and click the plus icon, the Ajax call goes out and the response returns in 1-4 seconds on average. I'm not understanding why it's so slow compared to a similar site that also uses admin-ajax.php (try hovering/clicking on one of the projects on that site to compare). All of the images called by Ajax are optimized. I also optimized my database tables. I'm not sure what else I can do.
Here is a comparison of the response time of admin-ajax.php from both sites. As you can see, the other site takes 480ms while mine takes 2s:
Here is how I have my Ajax call set up. Sorry, I didn't simplify the code because I think maybe the reason for the delay can only be found in the full code. The actual Ajax call is about halfway down.
(function($) {
// Function to allow an event to fire after all images are loaded
$.fn.imagesLoaded = function () {
var imgs = this.find('img[src!=""]');
// If there are no images, just return an already resolved promise
if (!imgs.length) {
return $.Deferred().resolve().promise();
}
// For each image, add a deferred object to the array which resolves when the image is loaded
var dfds = [];
imgs.each(function(){
var dfd = $.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();};
img.src = this.src;
});
// Return a master promise object which will resolve when all the deferred objects have resolved
// IE - when all the images are loaded
return $.when.apply($, dfds);
};
// Function for additional styling
function projectStyles() {
// Check the first slide input
$('#slider input:first').attr('checked', 'checked');
$('#project-wrapper').addClass('activated');
// Make the articles grey again after activation
$('article.project').addClass('grayscale grayscale-fade').css('opacity', '0.4');
// CSS effects
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeInDown');
// Remove pesky, sticky 'hover' class
$('article.project').removeClass('hover');
}
// Make the max-height of the container exact for a smoother transition
function matchContainerHeight() {
var heightHandler = function() {
var containerHeight = $('#project-container').outerHeight();
$('#project-wrapper.activated').css('max-height', containerHeight);
};
setTimeout(heightHandler, 100);
$(window).on('resize', heightHandler);
}
// Open the project container
function openProject() {
var post_id = $(this).data('id'), // data-id attribute for .post-link
ajaxURL = site.ajaxURL; // Ajax URL localized from functions.php
// Add a loading icon
$('<span class="loading-icon"></span>').insertBefore(this);
// Add the 'active' class to make sure the div stays dark while loading
$(this).closest('article.project').addClass('active hover-sticky');
// Make all the articles grey when an article is clicked
$('article.project').addClass('grayscale grayscale-fade grayscale-sticky').css('opacity', '0.4');
// No hover on images while a project is loading
$('article.project img').addClass('nohover');
// Remove all corner ribbons
$('article').removeClass('current');
$('.corner-ribbon').remove();
// Add a corner ribbon to note the current activated project
$(this).closest('article.project').removeClass('active').addClass('current');
$('<div class="corner-ribbon">Current</div>').prependTo('article.current');
// Call Ajax
$.ajax({
type: 'POST',
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
success: function(response) {
// Wait until all images are loaded
$('#project-container').html(response).imagesLoaded().then(function() {
// Fire again to rearrange the slide in the DOM
resize();
// Remove all 'hover' classes
$('article.project').removeClass('hover-sticky grayscale-sticky');
$('article.project img').removeClass('nohover');
// Remove the loading icon
$('.loading-icon').remove();
// If the user has scrolled...
if ($(window).scrollTop() !== 0) {
// First scroll the page to the top
$('html, body').animate({
scrollTop : 0
},400, function() {
matchContainerHeight();
projectStyles();
});
// If the user has not scrolled...
} else {
matchContainerHeight();
projectStyles();
}
return false;
});
}
});
}
// User event
$('#content').on('click', '.post-link', function(e) {
e.preventDefault();
var projectTitle = $(this).data('title'), // data-title attribute for .post-link
projectSlug = $(this).data('slug'); // data-slug attribute for .post-link
// Calls openProject() in context of 'this' (.post-link)
openProject.call(this);
$('head').find('title').text(projectTitle + ' | Keebs');
});
})(jQuery);
Here is the Ajax response file. I'm using the ACF plugin, but I tried the response without any of the ACF fields and the wait time was the same. I also tried removing everything within the my_load_ajax_content() function but the wait time was still the same as well. So I'm guessing something else is causing the long wait time. I also tried GET instead of POST but the response time was around the same:
<?php
/**
* Ajax functions
*/
// Return the post content to the AJAX call
function my_load_ajax_content () {
$args = array(
'p' => $_POST['post_id'],
'post_type' => 'projects'
);
$post_query = new WP_Query( $args );
while( $post_query->have_posts() ) : $post_query->the_post(); ?>
<div class="post-container">
<div id="project-left-content">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
<?php the_content(); ?>
<?php if( get_field('client') ): ?>
<div class="client">
Client(s): <?php the_field('client'); ?>
</div>
<?php endif; ?>
<div class="project-cats">
<?php
$cat_names = wp_list_pluck( get_the_category(), 'cat_name');
echo join( ', ', $cat_names );
?>
</div>
<?php if( get_field('url') ): ?>
<div class="project-link">
<a class="first after" href="http://<?php the_field('url'); ?>" target="_blank"><?php the_field('url'); ?></a>
</div>
<?php endif; ?>
</div>
<div id="project-right-content">
<?php if( have_rows('slides') ): ?>
<div id="slider">
<!-- Slider Setup -->
<?php if( have_rows('slides') ):
$slideNumber = 0;
while ( have_rows('slides') ) : the_row();
$slideNumber++;
?>
<input type="radio" name="slider" id="slide<?php echo $slideNumber; ?>">
<?php endwhile;endif; ?>
<!-- Slide -->
<?php if( have_rows('slides') ): ?>
<div id="slides">
<div id="overflow">
<div class="inner">
<?php if( have_rows('slides') ):
while ( have_rows('slides') ) : the_row();
$slideImage = get_sub_field('slide_image');
?>
<article>
<img src="<?php echo $slideImage; ?>" alt="<?php the_title(); ?>">
</article>
<?php endwhile;endif; ?>
</div><!-- #inner -->
</div><!-- #overflow -->
</div><!-- #slides -->
<?php endif; ?>
<!-- Controls -->
<?php if( have_rows('slides') ):
$slideNumber = 0;
?>
<div id="active">
<?php while ( have_rows('slides') ) : the_row();
$slideNumber++;
?>
<label for="slide<?php echo $slideNumber; ?>"></label>
<?php endwhile; ?>
</div><!-- #active -->
<?php endif; ?>
</div><!-- #slider -->
<?php endif; ?>
</div><!-- #project-right-content -->
</div><!-- .post-container -->
<?php
endwhile;
wp_die();
}
add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' ); // when the user is logged in
add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' ); // when the user is not logged in
Does anybody see something that I should be doing differently?
Looks like your site is hosted on dreamhost and most likely on shared hosting offering they have. The other website you mentioned looks like it is hosted on its own VPS. Shared hosting is often known for their slow database performance.
Your best option might be to use a caching solution like 'WP Super Cache' or 'W3 Total Cache' that saves the webpage to memory or disk on first request and serves from there on subsequent requests bypassing the database.
These are both wordpress plugin and can be easily installed from the admin plugins section.
https://wordpress.org/plugins/wp-super-cache/
https://wordpress.org/plugins/w3-total-cache/
Other option is trying to create indexes on the databse for faster searching. You could also look at using a small VPS (AmazonEC2 free tier or $5/month from digital ocean etc) if you know how to install Apache/mysql etc.
I would want to suggest you that rather then echoing HTML code from your php file you just return the main data(only raw information based on the click) as json response and then generate the html tags based on that and append it . Creating HTML from javascript is much faster than echoing HTML , specially during ajax call. I am sure if you do this you can get quite fast performance. Any big or large site they dont send HTML in ajax response. Majorly pure json response containing the key information is echoed. And on basis of that the divs are generated to load the section faster.
Can I make a suggestion?
Instead of defining your function like this:
(function($)
try something like this:
jQuery(document).ready(function($) {
$('selector').whatever();
})
I'm still learning Wordpress myself but I have found that defining the function as using jQuery can make a difference. I think this is because Wordpress is unsure of which library you want to use.
I am attempting to call a javascript function inside a php where loop. I've succeeded in calling the variable, however the function only works on the first line, and then breaks a subsequent query.
The javascript is a simple show/hide of a div or span tag with a specific id. I'm trying to have this appear for every instance of a variable, but only open the span associated with that entry, so I used a php variable from the query.
The javascript code is contained in the header; it works fine without the php, and the php works fine without the javascript but I can't seem to make them work together.
Here's the code:
while($row = mysqli_fetch_array($qir)) {
$ingredient_id = $row['ingredient_id'];
echo '<input type="checkbox" value="' . $ingredient_id . '" name="markdelete[]">';
echo $row['amt'] . ' ' .$row['ingredient_name']; ?> <button onclick="showHide('<?php echo $row['ingredient_id']; ?>'); return false">Edit amount</button> <br />
<span id="<?php echo $row['ingredient_id']; ?>" class="hide">
<?php include_once('amt.php');
echo '</span> ';
// }
echo '<br />';
}
echo '<input type ="submit" name="remove" value="Remove">';
First of all, the showHide is only working on the first record
It is also making this query not respond at all.
if (isset($_POST['remove'])) {
iF (!empty($_POST['markdelete'])) {
foreach ($_POST['markdelete'] as $delete_id) {
// remove specific source from source_subject
$rem_ing = "DELETE from dish_ingredient
where ingredient_id = $delete_id
and dish_id = $dish_id ";
mysqli_query($dbc, $rem_ing)
or die ('Error removing ingredient: '.mysqli_error($dbc));
}
}
}
I tried removing the return false;, to no avail. Please let me know if I need to show more of the code (e.g. the javascript itself)
Edit:
I've tried working within the php string (this is actually what I had tried first) but it seems to break everything (no javascript, no php)
echo $row['amt'] . ' ' .$row['ingredient_name'] . '<button onclick="showHide(\''. $row['ingredient_id'] .'\') return false">Edit amount</button> <br />';
echo '<span id=" '. $row['ingredient_id'] .' " class="hide">';
include_once('amt.php');
echo '</span> ';
Edit: I am open to other solutions if this is not something that is possible. I'm feeling a bit stumped. Realistically I just want to have a list of items called from a mysql database, and have a field appear onclick to edit an associated variable if desired without having to send it to another page or reload the script for usability (hence the javascript piece).
Thanks again, anyone who can assist.
Note: this is the script that I am calling:
<script language="JavaScript" type="text/JavaScript">
menu_status = new Array();
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(menu_status[theid] != 'show') {
switch_id.className = 'show';
menu_status[theid] = 'show';
}else{
switch_id.className = 'hide';
menu_status[theid] = 'hide';
}
}
}
</script>
You don't need tag there as you are already in php block.Try it without and use
showHide(\''.$row['ingredient_id'].'\')
and change
<?php include_once(....);
to
include_once(........);
Hopefully that would work
===========
try this for you javascript
<script language="JavaScript" type="text/JavaScript">
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(!switch_id) {
switch_id.className = (switch_id.className.indexOf("show") > -1) ? "hide" : "show"
}
}
}
Okay after a long time on this, I finally figured out what was going on. Part of the issue was that I was trying to call a form inside a form, which I had forgotten is not permitted in HTML, so this required some redesign.
Other issues involved calling loops within inside loops, which caused problems where the first record would work, but not for the remaining records.
The javascript above did not need to be modified, only the way that it was called.
Here is what worked. The main key was using include() instead of include_once().
while($r = $qir->fetch_assoc()) {
$ingredient_id = $r['ingredient_id'];
$amt = $r['amt'];
$ingredient_name = $r['ingredient_name'];
echo $r['amt'] . ' ' .$r['ingredient_name'];
if ($row['user_id'] == $user_id) {
echo ' <span class="openlink"><button onclick="showHide(\''.$ingredient_id. '\')">edit amount</button></span><br/>';
echo '<div id="'.$ingredient_id.'" class="hide">';
include('amt1.php');
echo '</div>';
}
}
I'm new to PHP and jquery-ui,
I have a problems in my php projects, I'm doing pagination within a jquery-ui tabs, but when click on next page or page number the page refreshed and display the 1st tab, while the pagination table is in 2nd tab. The following is my pagination code.
<?php
$range = 3;
if ($currentpage > 1) {
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
$prevpage = $currentpage - 1;
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
}
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo " [<b>$x</b>] ";
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
}
}
}
if ($currentpage != $totalpages) {
$nextpage = $currentpage + 1;
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
}
?>
I had tried to replace $_SERVER['PHP_SELF'] with #usersTab2 (the tab I wanted to go) but it wont work.
I'm using php $_GET method to get the current page data.The pagination works well, just I can't link back to the specific tab I want...
Hope to get replay and your help is much appreciate~ =)
ps: I'm sry for my english...
Add an id to all tabs;
And when load this page, create a rule to get value in hash from url and fire a click event in js.
Example:
url = test.com/#tab2
When page is ready, get the value in hash and fire event:
var div = get the value in hash url;
$("#"+div).click();
You will need to use JavaScript to target and load your pages. By using HTML links, the browser will refresh the page. I would suggest using the jQuery load() function.
Example:
<a href='javascript:void()' class='nextpage'>ยป</a>
Then in your script:
$('.nextpage').click(function() { $('#page').load('loader.php?page=number'); });