Changing two div's with one ajax call - javascript

I have a function on my project which allows users to set certain rss source as favourite.
I'm using codeigniter, and my view is something like that:
<a href="#" data-toggle="collapse">
<h5><b> <span class="glyphicon glyphicon-star-empty"></span> Favorites </b></i></h5>
</a>
<ul class="list-unstyled collapse in" id="favorites">
<?php foreach( $source as $fav ) : if( $fav->favourite == 1 ) {?>
<li>
<a id="some_id"> <?php echo $fav->rss_title; ?></a>
</li>
<?php } endforeach; } ?>
</ul>
<!-- all favorite links are placed in a left sidebar....in header, i have a div with different opperations... -->
<div class="col-sm-12">
<?php if ( $isFavourite == 0 ) { ?>
<li><h4><a class="addfav" id='just_id' href="#favorite">Add this Rss Source to Favourites</a></h4></li>
<?php } else { ?>
<li><h4><a class="removefav" id='just_id' href="#favorite">Remove this Rss Source from Favourites</a></h4></li>
<?php } ?>
// and other options ...
</div>
Here is the script where i use ajax:
<script>
$(document).ready(function(){
$(document).on('click','.addfav',function(){
var id=this.id;
$.ajax( {
type: "POST",
data: {id:id},
url: "<?php echo site_url('rssFeedReader/addFavorites'); ?>",
success: function(msg)
{
$("#favorites").append(msg);
}
})
});
});
</script>
Everything is working fine, but i cannot do something...after i add to favourites the link( via 'append' ), I want to change the option in my header from 'Add this Rss Source to favourites' to 'Remove this rss Source to favourites'. I did this, but only work if i reload the page...I want to do this when i add the link with ajax....
How can i change the div which contain those options, in the same ajax call ? Can i do something after the line '$('#favorites').append(msg); ?

If you want to change the option, do this:
$('.addfav').addClass('removefav').removeClass('addfav').text('Remove this Rss Source from Favourites');
after the
$("#favorites").append(msg);
line
This will transform
<a class="addfav" id='just_id' href="#favorite">Add this Rss Source to Favourites</a>
to
<a class="removefav" id='just_id' href="#favorite">Remove this Rss Source from Favourites</a>
and after you can obviously add listener to the object to add fucntionnalities.

Related

Ajax Tabs for Wordpress that loads and runs different shortcodes when user changes the tab

How does one execute a shortcode, which is placed in a tab, only when the user clicks on the Tab's Title. How do we do this for five tabs? MY objective is to reduce load time of me website. So, only that content which the user wants must load when he clicks on the tab.
I'm fairly certain the best way to do this is by utilizing Wordpress's admin-ajax.php. I've searched a great deal. And I've found most of the code (I think) to create the AJAX tabs. But, when I fire the code it doesn't show up. Rather the HTML shows us, the AJAX doesn't.
$(document).ready(function() {
$('.my_tabs a').click(function(e) {
e.preventDefault();
var tab_id = $('this').attr('id');
$.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({
action: 'my_tab_menu',
id: tab_id
}),
success: function(data) {
$('#my_tab' + tab_id).html(data);
},
error: function(data) {
alert("Error!");
return false;
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my_tabs">
Tab 1
Tab 2
Tab 3
Tab 4
Tab 5
</div>
<div class="my_section" id="my_tab1">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my_section" id="my_tab2">
<?php echo do_shortcode ('[shortcode-2]'); ?>
</div>
<div class="my_section" id="my_tab3">
<?php echo do_shortcode ('[shortcode-3]'); ?>
</div>
<div class="my_section" id="my_tab4">
<?php echo do_shortcode ('[shortcode-4]'); ?>
</div>
<div class="my_section" id="my_tab5">
<?php echo do_shortcode ('[shortcode-5]'); ?>
</div>
I add all the code directly into the page using a page-builder. So, I'm not using functions.php to add_action for this particular tab that I'm trying to implement.
I found all the code from a similar post on stackover:
Ajax tabs (wordpress)
They call template_parts into the tabs. Where as I want to execute a shortcode.
I'm what you'd call a coding bimbo. All help shall be much appreciated.
Thank you. And if you've managed to read till here, you deserve to have a pleasant day. :D
Okay, so you can't achieve it the way you have laid your template. As soon as you echo the shortcode and the browser renders the page, the shortcode contents must have printed. You need to create a custom-page-template.php, create a page and on that page you need to send the shortcode handler as soon as you click on the tab through GET or POST method using ajax.
In your Custom Template you receive the [shortcode-1]. An example code would be like you see below:
<?php
/*
Template Name: Shortcode Processor
*/
$current_shortcode = $_POST['shortcode_name'];
?>
<div id="shortcode-contents">
<?php echo do_shortcode($current_shortcode); ?>
</div>
Now you have the response in your Ajax Call. You can now inject the success html inside your desired tab.
Try
<button class="tabs" id="my-tabid1" data-target=".my-section1.box">Tab 1</button>
<button class="tabs" id="my-tabid2" data-target=".my-section2.box">Tab 2</button>
<button class="tabs" id="my-tabid3" data-target=".my-section3.box">Tab 3</button>
<div class="my_section1 box active" id="my-tab1">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my-section2 box" id="my-tab2">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my-section3 box" id="my_tab3">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<style>
.box {
display: none;
}
.box.active {
display: block;
}
</style>
<script>
$('.tabs').on('click', function(){
var $target = $($(this).data('target'));
$target.siblings().removeClass('active');
$target.addClass('active');
});
</script>

Getting variable passed from PHP to JS on Click event, returns all elements variable, not just the one that's clicked

I'm working on a WP code, but my problem in specific to JS. So I post my question here at StackOverflow.
Final goal is, clicking on the post image, showing the HTML markup of large img on Console. Here's my code:
<div class="img lightbox-trigger">
<?php the_post_thumbnail(); ?>
<div class="hover" >
<i class="fa fa-arrows-alt"></i>
</div><!--hover-->
</div><!-- .img .lightbox-trigger -->
<?php $large_thumb = get_the_post_thumbnail($post->ID, 'large') ?>
<script type="text/javascript">
jQuery(document).ready(function($){
$(".lightbox-trigger").click(function(){
var largeThumb = <?php echo json_encode( $large_thumb ); ?>;
console.log( largeThumb );
});
});
</script>
The problem is when I click on one of the post's images, the largeThumb value of all other posts (there are 10 posts) printed on Console!
I don't know how to use $(this) in this specific context to just get the value related to the element being clicked on.
Any help is appreciated.
You could use data-* attributes to store the $large_thumb of every lightbox-trigger in the related div :
<div class="img lightbox-trigger" data-large-thumb='<?php echo get_the_post_thumbnail($post->ID, 'large'); ?>'>
<?php the_post_thumbnail(); ?>
<div class="hover" >
<i class="fa fa-arrows-alt"></i>
</div><!--hover-->
</div><!-- .img .lightbox-trigger -->
Then in the js you could get this info :
jQuery(document).ready(function($){
$(".lightbox-trigger").click(function(){
console.log( $(this).data('large-thumb') );
console.log( $(this).html() );
});
});
Hope this helps.

Hide menu item according to user account

On my login mysql table, i have an account type column. If the user has a Manager account type, i want to show a management menu item and if not hide it.
This is pretty simple but its not working:
In my header, i have the following:
<script>
var logged_in_account_type = "<?php echo $_SESSION['account_type'] ; ?>";
if(logged_in_account_type === "Manager") {
document.getElementById('management_menu').style.display = 'block';
} else {
document.getElementById('management_menu').style.display = 'none';
}
</script>
I tried without the echo has well.
<div id="management_menu" style="display:none">
<li>
<i class="menu-icon fa fa-dashboard"></i><span class="mm-text">Dashboard</span>
</li>
</div>
<div class="text-bg"><span class="text-slim">Welcome,</span> <span class="text-semibold"><?php echo $_SESSION['account_type'] ?></span></div>
Have you tried using php if while rendering your menu? Something like this:
<?php if($_SESSION['account_type'] == 'Manager'): ?>
<div id="management_menu">
<ul>
<li>
Dashboard
</li>
<li>
Users
</li>
</ul>
</div>
<?php endif; ?>
Where is your javascript code in the document? If your javascript code is on the top of the document, it possibly shows or hides the <div> element properly, but, because the <div> element is at the bottom of the document, it is hidden because its "style" says so.
The solution is to move the javascript code below the <div> element, this will solve the "execution order" problem you have. Example :
<div id="management_menu" style="display:none">
<li>
<i class="menu-icon fa fa-dashboard"></i><span class="mm-text">Dashboard</span>
</li>
</div>
<?php
session_start();
$_SESSION['account_type'] = "Manager";
?>
<script>
var logged_in_account_type = "<?php echo $_SESSION['account_type'] ; ?>";
if(logged_in_account_type === "Manager") {
document.getElementById('management_menu').style.display = 'block';
} else {
document.getElementById('management_menu').style.display = 'none';
}
</script>

How to change displayed html content in view using jquery - codeigniter

I'm not so sure about how to type this question title, but anyway
I have code like this in my view called content.php
<div class="fix single_content floatleft">
<h2><img src="<?php echo base_url('assets/images/New.png')?>" alt="" width="24" height="24"></img><a href="<?php echo base_url('index.php/Main_Controller/loadKeluhan')?>" >New</a> </h2>
<?php include 'tableLoad.php' ?>
<p class="viewall">view more <i class="fa fa-hand-o-right"></i></p>
</div>
And in its looks like this in tableLoad.php
<div class="fix"><ul id="newTable"><?php
$i=0;
while($i<count($array)){
echo '<li>
<div class="entry_name floatleft"><img src="assets/images/mozilla.png" alt="">'.$array[$i].'</div>
<div class="download-count floatright"><i class="fa fa-download"></i> 4578</div>
</li>';
$i++;
}
?></ul></div>
$array[i] is a forwarded variable from my controller which have list of item I need from my database.
I want to have it refreshed every 2 second so it will change the display if something changed from the database. I use my code in jQuery like this to do it:
$(document).ready(function(){setInterval(function(){
$('#newTable').html("<?php include 'tableLoad.php'; ?>")
}, 2000);});
The problem is that every time jQuery code run, it show nothing and there is no error report in browser's console. The codes in php run well, but the one from jQuery did not.
Can anybody please give me some enlightment?
Thanks in advance and sorry for my bad English
SOLVED
Solution :
I change my js code to Ajax and call function from controller with it like poonam said. The js file become like this :
$(document).ready(function(){
setInterval('autoRefresh_div()', 2000);
});
function autoRefresh_div()
{
$.ajax({
dataType:'text',
type: "POST",
url: BASE_URL+'index.php/Main_Controller/loadKeluhan',
success: function (response){
$("#newTable").html(response);
}
});}
with loadKeluhan is a function in my Main_Controller to load tableLoad view and pass new array value to it.
You should use load()
Try this:
function autoRefresh_div()
{
$("#newTable").load("tableLoad.php");// a function which will load data from other file after x seconds
}
setInterval('autoRefresh_div()', 2000); // refresh div after 2 secs
And use this:
<div class="fix single_content floatleft">
<h2><img src="<?php echo base_url('assets/images/New.png')?>" alt="" width="24" height="24"></img><a href="<?php echo base_url('index.php/Main_Controller/loadKeluhan')?>" >New</a> </h2>
<div class="fix"><ul id="newTable">
<?php include 'tableLoad.php' ?>
</ul>
</div>
<p class="viewall">view more <i class="fa fa-hand-o-right"></i></p>
</div>
Get only <li> from tableLoad.php.
Similarly you can use $.ajax() or $.post() etc instead of load() function and put the response in div or ul.
With $.ajax()
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function autoRefresh_div()
{
$.ajax({
dataType:'text',
type: "POST",
url: 'url_to_your_file or function',
success: function (response){
$("#newTable").html(response);
}
});
}
setInterval('autoRefresh_div()', 2000); // refresh div after 2 secs
</script>

Passing the ID of clicked link to PHP code without reloading the page

I am trying to pass the ID of a clicked link to PHP code without reloading the page.
Currently, I am using the following code to pass the ID in the href attribute in the tag:
<?php
$sql="select * from category";
$execute=mysql_query($sql);
while($row=mysql_fetch_assoc($execute)){ ?>
<li><?php echo $row['category'] ; ?></li>
<?php
}
?>
</ul>
</div>
<div id="waxing" style="display:none">
<h2 id="cat_price" style="color:#f5c658">Price Category Waxing</h2>
<ul class="ul1">
<?php
function sub() {
if(isset($_GET['did']))
{
$id=$_GET['did'];
$sql="select * from midcat where cid=$id";
$execute=mysql_query($sql);
if(mysql_num_rows($execute)>0){
while($row=mysql_fetch_assoc($execute)){
?>
<li><a href="#" id="wax_normal" ><?php echo $row['midcat']; ?> </a></li>
<?php
}
}
}
}
sub();
?>
Is it possible to do the same thing without reloading the page?
As I mentioned, you will want to use AJAX to fetch your other list. I will demonstrate and notate. I am using jQuery because I am familiar with it and I find it easy to use. Traditional javascript AJAX will work just as well:
page1.php (whatever this page is called)
Add jQuery libraries in the <head>:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
Change this line, it doesn't need to be a link, I like to use the data attribute:
<li data-id="<?php echo $row['id']; ?>"><?php echo $row['category'] ; ?></li>
On this same page add the ajax:
<script>
// When the page finishes loading
$(document).ready(function() {
// When the user clicks any <li>, activate script
$("li").click(function() {
// Assign the value of the data attribute
var thisBtn = $(this).data('id');
// If an <li> doesn't have this attribute, stop
if(thisBtn == undefined)
return false;
// Start the ajax
$.ajax({
// Where to send request
url: 'ajax.index.php',
// What to send
data: { did: thisBtn },
// How to send
type: 'post',
// What to do when request succeeds
success: function(response) {
// Save the contents of the response into
// whatever has the id="list"
$("#list").html(response);
}
});
});
});
</script>
Place a drop spot where you want your list to show up on this page:
<!-- this is where ajax will drop the list on your page -->
<span id="list"></span>
Create a new page and put the <ul>, function, execution of function on this new page
ajax.index.php
<?php
function sub()
{
// In the ajax, I told it to use $_POST, so change to
// post instead of get
if(isset($_POST['did'])) {
$id=$_POST['did'];
// Don't do this anymore.............vvv
$sql="select * from midcat where cid=$id";
// Don't use mysql_ anymore
$execute=mysql_query($sql);
if(mysql_num_rows($execute)>0){
while($row=mysql_fetch_assoc($execute)){
?>
<li><a href="#" id="wax_normal" ><?php echo $row['midcat']; ?> </a></li>
<?php
}
}
}
}
?>
<ul class="ul1">
<?php sub().PHP_EOL; ?>
</ul>
if you don't want to refresh page you have to use AJAX:
https://developer.mozilla.org/en-US/docs/AJAX
on your javascript onclick event pass your id and replace href attribute value with a hashtag. like this:
<?php echo $row['category'] ; ?>
Now send an ajax request in show function. and use the response.

Categories

Resources