Wordpress ajax loop refresh on click - ajax

I display a random post loop on a page. I'd like to put a "refresh" link to refresh the content of the loop via ajax.
Is this possible?
This is my loop:
<ul id="content-inner" class="thumb-grid clearfix">
<?php query_posts('posts_per_page=20&orderby=rand'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<img src="<?php echo $my_image_url = get('thumbnail'); ?>" alt="" />
<span class="title"><?php the_title(); ?></span>
<span class="feat"><?php $articletags = strip_tags(get_the_tag_list('',', ',''));echo $articletags;?></span>
</a>
</li>
<?php endwhile;?>
<?php endif; ?>
<?php wp_reset_query(); ?>
</ul>
Thanks

Put the random post code in a div (if you haven't already), and refresh the contents of that div with JQuery...
Something like this should work (but I haven't had time to test)...
In the Head of your page reference JQuery, then use JQuery.Ready to load the first random post (for initial page load):
<head>
<script> /*...reference JQuery...*/ </script>
<script>
jQuery(document).ready(function($) {
$("#randomdiv").html("<?php getRandomPost() ?>");
});
</script>
</head>
<body>
....
<div id="randomdiv">[placeholder text]</div>
<a id="refresh" href="#">click</a>
<!-- Then for the REFRESH:
make sure this script occurs AFTER your div (above) -->
<script>
$(function() {
$("#refresh").click(function(evt) {
$("#randomdiv").html("<?php getRandomPost() ?>");
evt.preventDefault();
})
})
</script>
</body>
So put your entire loop code in a function called getRandomPost() (or something) and place it in your wordpress "functions.php" file..., then just call "$("#randomdiv").html("");" in the head of your page for initial load, then in the body as I've shown for the refresh...

Related

Magento2 theme mini cart KO templating issue

I have issues with Magento2 theme mini cart KO templating issue.
I have been trying to create a realtime mini cart dropdown in my header and having issue with its data rendering. I tried KO templating but for some reasons my code doesn't works, therefore I had added the number of cart items using PHTML behavior.
But problem with PHTML behavior is that we can't overcome with Magento FPC cache on page rendering.
Any help in initiating and replacement for KO mini cart is very helpful.
I have code publically accessible on github here: https://github.com/OrviSoft-Inc/magento2-bootstrap-theme
Fix or replacement I am seeking for is here: https://github.com/OrviSoft-Inc/magento2-bootstrap-theme/blob/master/app/design/frontend/MyTheme/default/Magento_Theme/templates/cart.phtml
My Cart template referred above looks like this
<?php
$helper = $this->helper('\Magento\Checkout\Helper\Cart');
?>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<div class="right-header" data-mage-init='{"babyTalker": {}}'><i class="fas fa-home"></i><span class="icon-search searchShow"></span><span><?php echo $helper->getItemsCount(); ?></span></div>
<div class="mini-search-form" id="add_data" style="display:none;">
<form action="/catalogsearch/result" method="get">
<input type="text" name="q" Placeholder="Search"/>
<button class="btn btn-primary mini-search" type="submit">Search</button>
</form>
</div>
<script>
require(['jquery'], function ($) {
$(document).ready(function () {
$('.searchShow').click(function(){
$('#add_data').toggle('slow');
});
});
});
</script>
After spending some time, I found that KO template usage with the help of core theme and the final fix was with following code.
<div class="block block-minicart empty"
data-role="dropdownDialog"
data-mage-init='{"dropdownDialog":{
"appendTo":"[data-block=minicart]",
"triggerTarget":".showcart",
"timeout": "2000",
"closeOnMouseLeave": false,
"closeOnEscape": true,
"triggerClass":"active",
"parentClass":"active",
"buttons":[]}}'>
<div id="minicart-content-wrapper" data-bind="scope: 'minicart_content'">
<!-- ko template: getTemplate() --><!-- /ko -->
</div>
<?= $block->getChildHtml('minicart.addons') ?>
</div>
Note the data-mage-init section. And the <!-- ko template: getTemplate() --><!-- /ko --> section
And than loading relevant js was helpful as below.
<script type="text/x-magento-init">
{
"[data-block='minicart']": {
"Magento_Ui/js/core/app": <?= /* #escapeNotVerified */ $block->getJsLayout() ?>
},
"*": {
"Magento_Ui/js/block-loader": "<?= /* #escapeNotVerified */ $block->getViewFileUrl('images/loader-1.gif') ?>"
}
}
</script>

AJAX $.POST function(data)

I have some trouble to instert a condition inside the function(data). It works for the second condition (i.e. else) but not for the first one. In other words when data="success" in my php, nothing appears in my html file. Furthermore console.log(data) is "ReferenceError: data is not defined " in both cases even if it works for the second condition.
Also in my networks(console) in Firefox I can see the data send from php in the second condition but for the first one it says that the data was not saved.
$errors is an array in php.
My code in ajax:
$.post('register3.php', {
username : $("#username").val(),
password : $("#password").val(),
passwordconfirm : $("#passwordconfirm").val(),
email : $("#email").val()
},
function(data){
if(data=="success"){
$("#results").html(data);
}
else{
$("#errors1").html(data.username);
$("#errors2").html(data.password);
$("#errors3").html(data.email);
}
My code in php
<?php
if(!empty($errors)){
header('Content-Type: application/json; Charset=utf-8');
$data = json_encode($errors);
echo $data;
}
else {
$data='success';
echo $data;
}
?>
My code in HTML
<div class="flash2">
<ul>
<li><div id="errors1"> </div> </li>
<li><div id="errors2"> </div> </li>
<li> <div id="errors3"> </div> </li>
<li> <div id="results"> </div> </li>
<ul>
</div>

How Can I check if Page is single page of Custom Post Type in Wordpress

On the Homepage I have called the content of Custpm Post Type with Ajax with this code
jQuery(document).ready(function($){
$.ajaxSetup({cache:false});
$(".sector_item a").click(function(){
var post_link = $(this).attr("href");
$(".sector_item_content").html("<div class='load' style='position:relative;margin-top:50px;padding-bottom:50px;'><img src='<?php bloginfo("template_url"); ?>/images/ajax-loader.gif'></div>");
$(".sector_item_content").load(post_link);
return false;
});
});
But In the single Page of this same Post Type I need to have another design with content so how I can detect the single page. I tried with Wordpess is_single() function but it doesnt work it displayed anyway in ajax.How Can I fix this?
Here is my single template.php
<?php if(is_singular('sector' )){
echo 'Single page' ;
}else{
while (have_posts() ) : the_post(); ?>
<div class="container single_page_inner">
<div class="row clearfix">
<div class="col-md-10 column" style="float:none;margin:auto;">
<div class="sector_single_title">
<?php the_title();?>
</div>
<div class="single_sector_contentmain"> <?php the_content();?></div>
<div class="single_sector_more">
<img src="<?php bloginfo(template_url);?>/images/single_secormoreline.png"/>
<div class="single_sector_button">
<span class="single_sec_leftline"></span>
<span class="single_sec_rightline"></span>
Click Here To Read More
<div class="more_line"></div>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
If you want to be able to do different things when your single.php files is loaded from Ajax, you need to tell it somehow when it is getting an Ajax request.
One approach would be to add a parameter to your call, like this:
var post_link = $(this).attr("href") + '?isajax=1';
Then in your single.php file, test for this parameter:
<?php if(!empty($_GET['isajax'])){
// This is Ajax - display in Ajax format
} else {
// This is not Ajax - display in standard single.php format
}
use this:
is_singular('YOUR_POST_TYPE' );
CODEX

Magento 1.7.0.2 Checkout shipping

I have a small problem with jquery that I want to use in my magento one page checkout.
I currently use flat rate for international delivery that is set to 0 because I have a variable costs of shipping.
For this reason I have a jquery email enquiry that sends all contents of the shopping cart in e-mail.
Now what I want to do is: when the customer arrives and selects flat rate delivery option I want to disable the Continue button and enable Email Enquiry button, but that does not work in my checkout. It does in jsfiddle. I think this is due to the fact that shipping methods are in available.phtml and buttons are in different file - shipping_methods.phtml. Any help will be appreciated
Here's my code:
<script type="text/javascript">
//<![CDATA[
var shippingMethod = new ShippingMethod('co-shipping-method-form', "<?php echo $this- >getUrl('checkout/onepage/saveShippingMethod') ?>");
//]]>
</script>
<div id="onepage-checkout-shipping-method-additional-load">
<?php echo $this->getChildHtml('additional') ?>
</div>
<div class="buttons-set" id="shipping-method-buttons-container">
<p class="back-link"><small>« </small><?php echo $this->__('Back') ?></p>
<button id="the_other_button" type="button" title="Email Enquiry" class="button" onclick="javascript:readEmailInfo();"><span><span style="padding: 0 13px;">Email Enquiry</span></span></button>
<button id="the_button" type="button" class="button" onclick="shippingMethod.save()"><span><span><?php echo $this->__('Continue') ?></span></span></button>
<span id="shipping-method-please-wait" class="please-wait" style="display:none;">
<img src="<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif') ?>" alt="<?php echo
$this->__('Loading next step...') ?>" title="<?php echo $this->__('Loading next step...') ?>"
class="v-middle" /> <?php echo $this->__('Loading next step...') ?>
</span>
</div>
</form>
<script>
if ($("#s_method_flatrate_flatrate:checked")){
$('#the_button').hide();
$('#the_other_button').show();
}
</script>
Try this:
<script>
jQuery.noConflict();
if (jQuery("#s_method_flatrate_flatrate").is(":checked")){
jQuery('#the_button').hide();
jQuery('#the_other_button').show();
}
</script>
$ is also used by Magento's default prototype.js, which will conflict with jQuery's $.
You can do that by this:
<script>
$j = jQuery.noConflict();
if ($j("#s_method_flatrate_flatrate").is(":checked"))
{
$j('#the_button').hide();
$j('#the_other_button').show();
}
</script>
By using this you can resolve jQuery Conflict.

Load an HMVC module view within an Iframe in Codeigniter

I'm new at this and some help will be apprciated.
I'm building a sidebar in a CI-Boilerplate-Project which contains modules (widgets) that i got run with HMVC https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc.
In the sidebar i have a widget that display a friendslist with status online/offline.
The user has the ability to switch the widgets on/off in the managementsection.
In the Profileview:
<aside class="sidebox right">
<?php foreach ($boxes as $boxName => $boxSetting)
{
echo Modules::run($boxName, $boxSetting['box_visible']);
}
?>
</aside>
if box_visible == 1 the widget will be displayed.
Controller:
class Myfriends extends SM_Controller
{
function __construct()
{
parent::__construct();
}
public function index($visible = false)
{
$user = $this->session->userdata('user');
$myf = $this->widget_model->get_friends($user['user_id'], 5);
$data['friends'] = $myf;
if ($visible) $this->load->view('myfriends', $data);
}
}
View:
<html>
<head>
<meta http-equiv="refresh" content="5">
</head>
<body>
<div class="box friendsbox">
<div id="header"><h3><?=$boxTitle?></h3></div>
<div id="boxcontent">
<ul>
<?php foreach ($friends as $friend): ?>
<li>
<div id="thb_img">
<img src="<?=img_thumb($friend['file_path'], 50, 50) ?>" />
</div>
<div id="short_desc">
<a href="<?= site_url('widget_functions/show_user/' . $friend['uu_id']) ?>">
<?= ucfirst($friend['user_name']) . ' ' . ucfirst($friend['user_lastname']) . ' ' ?>
</a>
<?php if ($friend['is_online']): ?>
<span style="color: green">online</span>
<?php endif; ?>
</div>
</li>
<?php endforeach; ?>
</ul>
</div>
<div id="footer">» mehr</div>
</div>
</body>
</html>
Now, i need to update the friendslist every 1-2 min so i tryed to load the moduleview within an iframe:
<aside class="sidebox right">
<?php foreach ($boxes as $boxName => $boxSetting): ?>
<?php if ($boxName == 'myfriends' && $boxSetting['box_visible'] == 1) { ?>
<iframe src="<?php echo site_url('myfriends/index'); ?>" ></iframe>
<?php
}
else
{
echo Modules::run($boxName, $boxSetting['box_visible']);
}
?>
<?php endforeach; ?>
</aside>
BUT this dose not work! The place of the widget is emtpy.
Do you have any idea how to get that to work?
appreciate your help
I believe the main issue is with the way you initialize the index method. the index method is kinda tricky with parameters in Codeigniter. In my projects, the only way to get the vlues of arguments passed to the index parameters is by using the URI library method $this->uri->segment(n). In other words, I believe that the value of $visible is not properly passing to the index() body
Anyway, I think you should create another method in your MyFriends Class called render() for example, and call it instead of relaying on the index() method. now render() can play nicely with the $visible=false initialization trick.
Hope this helps

Resources