Execute JavaScript, into the divs opened previously with jQuery/JavaScript - javascript

I am doing a comment system. Yesterday I asked for the same problem in stackoverflow and I didn't get any answer. Now I have simplified the code, so I hope that its easier to understand. I also write complete code if someone what to try it.
The main HTML page has multiple divs:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://code.jquery.com/jquery-3.0.0.min.js"></script>
<script type="text/javascript" src="jscripts/actions.js"></script>
</head>
<body>
<div class="comments_div" id="comments_div" data-id="22" >
div_22--->
<div class="comments_more_22" id="comments_more"> </div>
</div>
<br>
<div class="comments_div" id="comments_div" data-id="23" >
div_23--->
<div class="comments_more_23" id="comments_more"> </div>
</div>
<br>
<div class="comments_div" id="comments_div" data-id="24" >
div_24--->
<div class="comments_more_24" id="comments_more"> </div>
</div>
<br>
</body>
The jQuery/JavaScript functions open/hide the div and show the post_id (data-id). It works perfectly.
//Open div
$(function() {
$(".comments_div").click(function() {
var post_id = $(this).attr('data-id');
$.ajax({
url: "jscripts/comment.php",
type: "POST",
data: { post_id: post_id },
success: function(datos) {
$('.comments_more_' + post_id).html(datos);
$('.comments_more_' + post_id).show('slow');
//alert(post_id);
}
});
});
})
//Hide div
$(document).mouseup(function (e){
var container = $('div[id^="comments_more"]');
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{ container.hide('slow'); }
});
//Put text in some div
function showText()
{ document.getElementById("flash").textContent = 'works!';}
...and comment.php (here the code will be more complicated, with forms, captchas, etc)
<?php
echo 'post_id: ';
echo $_POST['post_id'];
?>
<div class="flash" id="flash">- </div>
<span style="margin-left:20px;"><small>click<a href='javascript: showText();'>here</a> </small></span><br/>
Nice, isn't it?.
But I need to execute another JavaScript: showText(). This script works when you click in this order: div_24, div_23, div_22. But stop works when you try click first div_22, then div_23,... etc.

Well I solved the problem: the div "flash" must have a unique id, so showText can find the correct div.
<?php
echo 'post_id: ';
echo $_POST['post_id'];
$post_id=$_POST['post_id'];
?>
<div class="flash" id="flash_<?php echo $post_id; ?>">- </div>
<span style="margin-left:20px;"><small>click<a href='javascript: showText();'>here</a> </small></span><br/>
<script type="text/javascript">
//Put text in some div
function showText()
{
var post_id = "<?php echo $post_id; ?>" ;
document.getElementById("flash_" + post_id).textContent = 'works!';
}
</script>
:P

Related

PHP read more read less - Magento 2

I made an read more read less script for my Magento 2 webshop. This is used on a category page where there are serval subcategorie blocks to choose, each subcategory has a description with.
The problem: if I click read more all the descriptions of the subcategories will expand in stead of only the description of the subcategory I clicked read moreI am starting to learn PHP and Magento 2 but I can't fix this, does someone know the solution?
<div class="product description product-item-description">
<div class="more">
<?php if ($_subCategory->getDescription()) {
$string = strip_tags($_subCategory->getDescription());
if (strlen($string) > 250) {
// truncate string
$stringCut = substr($string, 0, 250);
$string = substr($stringCut, 0, strrpos($stringCut, ' ')).'... Lees meer';
}
echo $string;
?>
</div>
<?php
}else {?>
<?php /* #escapeNotVerified */ echo $_attributeValue;
}
?>
</div>
<div class="less" style="display:none">
<?php echo $_subCategory->getDescription(); ?>
Lees minder
</div>
<script type="text/javascript">
console.log('test');
require(["jquery"],function($){
$('.readmore').on("click",function(){
$('.less').show();
$('.more').hide();
});
$('.readless').on("click",function(){
$('.less').hide();
$('.more').show();
});
});
</script>
</div>
This is because, when you type $('.less').hide(); this is grabbing every element with the attribute class='less'. This is the way I would overcome this:
Start by attaching a unique attribute to each <div class="more"> or <div class="less"> - in this case, we use the class attribute: (and move 'more' or 'less' to an id)
<div id="read-more-block" class="cat-<?php echo $_subCategory->getId(); ?>">
<!-- my "read more" content -->
<a class="link" href="#read-more-block">Read Less</a>
</div>
<div id="read-less-block" class="cat-<?php echo $_subCategory->getId(); ?>">
<!-- my "read less" content -->
<a class="link" href="#read-less-block">Read More</a>
</div>
We now have a read-more-block and a read-less-block for each subcategory. When we click the inside link a jQuery event should fire which will hide itself and display the other.
And then, in your jQuery:
$('#read-more-block .link').on('click', function() {
var $readLessBlock = $('#read-less-block.' + $(this).parent().attr('class'));
$readLessBlock.show(); //Show the read less block
$(this).parent().hide(); //Hide the read more block
});
..and vice versa for read less.

Loading PHP Response with Jquery Ajax POST

I have a php script that loops over the results of a database query and prints them out. I am trying to load them into an Admin Interface Panel with AJAX, but to no avail. My job requires me to write mostly backend code, so I haven't gotten around to learning much JS/Jquery. Anyways, I have a page "insert.php" that has a button I want to click and have it call the results from the "posts.php" page. Here are my files
insert.php
Load Posts
</div>
</div>
<div class="row main">
<div class="small-8 columns" id="posts">
</div>
</div>
</div>
posts.php
<?php
require_once 'connect.php';
$user = 'admin';
$sql = "SELECT * FROM posts WHERE author = ?";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $user);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row)
{
$id = $row['id'];
$title = $row['title'];
$author = $row['author'];
$date = $row['date'];
$smalltext = $row['smalltext'];
$bodytext = $row['bodytext'];
$images = $row['images'];
$imagelist = split(' ', $images);
$shorttext = str_replace(
array("\r\n", "\n"),
array("</p><p>", "</p><p>"),
$smalltext);
echo
"
<div class='row main'>
<h1 class='padding-top-12 bottom-rule-green'>$title</h1>
<div class='small-2 columns'>
<p class='text-justify small-text'>
Post MetaData goes here
</p>
</div>
<div class='small-10 columns bottom-rule-red text-justify'>
<p>
$shorttext
";
foreach ($imagelist as $key => $value)
{
echo "<img src='users/$author/img/$value'>";
}
echo
"
</p>
</div>
</div>
<div class='row main small-text padding-top-1'>
<div class='small-2 small-oofset-2 columns'>
<a href='posts/$author/$id'>Edit Post</a>
</div>
<div class='small-4 columns'>
Timestamp: $date
</div>
<div class='small-4 columns'>
Author: <a href='users/$user'>$user</a>
</div>
</div>
";
}
?>
postAjax.js
$.ajaxSetup ({
cache: false
});
var loadUrl = "../../includes/posts.php";
$(function(){
$('#ajaxbtn').on('click', function(e){
e.preventDefault();
$('#ajaxbtn').fadeOut(300);
$.post(loadUrl, {language: "php", version: 5},
function(res){
$("posts").html(res)
}, "html");
});
});
This is the file that loads my scripts into the page
<!--Foundation Framework Necessities-->
<script type="text/javascript" src="../../assets/js/vendor/jquery.js"></script>
<script type="text/javascript" src="../../assets/js/foundation/foundation.min.js"></script>
<script type="text/javascript" src="../../assets/js/postAjax.js"></script>
<script type="text/javascript">
$(document).foundation();
</script>
When I click the #ajaxbtn button, it fades out so I know the JS is being called to that element onclick, but it doesn't post the results of posts.php. I think this may just be my misunderstanding of how Ajax works; if you would please tell me what I did wrong.
Try changing,
$("posts").html(res)
to
$("#posts").html(res)
Also I see some mistakes in your code in posts.php
You are not embedding php variables in strings properly.
I believe you need to use a delegated event. Change your code from:
$('#ajaxbtn').on('click', function(e)
to:
$('#ajaxbtn').on('click', 'a', function(e)
This way event handlers will fire as expected even if the contents of that parent element change. I had the same issue and this solved it. Good luck.

How can I get Jquery event listener to work with div link?

I have the following html:
<a href="#">
<div id="post-<?php echo $i++; ?>"></div>
<div class="like-icon-container">
<span class="icon-thumbs-up"></span>
</div>
</a>
And a listener to pick out the ID of the link that was clicked:
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});
</script>
The script does NOT work in the above example where I'm trying to link the icon that is in the div (it's not an image, but a font icon rendered in css). But the script works if I add text in the first div like this:
<a href="#">
<div id="post-<?php echo $i++; ?>">asdfasdf</div>
<div class="like-icon-container">
<span class="icon-thumbs-up"></span>
</div>
</a>
How can I get this to work without adding text in the first div?
You should not put div inside an anchor element. I'd suggest you to do it like this:
<div id="post-<?php echo $i++; ?>" class="clickable like-icon-container"><span class="icon-thumbs-up"></span></div>
CSS (pointer cursor):
.clickable { cursor: pointer; }
And then the JS:
<script type="text/javascript">
$(document).ready(function() {
$(".clickable").click(function() {
alert($(this).attr('id'));
// alternatively:
alert(this.id);
});
});
</script>
you can try this
$(document).ready(function() {
$("a").click(function() {
var id = $(this).children(":first").attr("id");
alert(id);
});
});
see
JS Fiddle
Firstly try to put a b/w the div instead of text if this doesn`t work apply a class to the div(s) and get a function call at click of that class
<div id="post-<?php echo $i++; ?>" class="isclicked"></div>
<div class="like-icon-container">
<span class="icon-thumbs-up"></span>
</div>
$(document).ready(function() {
$(".isclicked").click(function() {
console.log($(this).attr('id'));
});
});

jquery + php load more

I'm facing problem with jquery
here is my code
<script type='text/javascript' src='jquery-1.10.2.min.js'></script>
<script type="text/javascript">
$(function() {
$(".more2").click(function() {
var element = $(this);
var msg = element.attr("id");
$.ajax({
type: "POST",
url: "insta2.php",
data: "lastmsg="+ encodeURIComponent(msg),
success:function (data) {
$("#morebutton").replaceWith(data);
}
});
return false;
});
});
</script>
<span class="more" id="morebutton">
<a id="1" class="more2" title="Follow" href="#" style="color:#000">
Read More
</a>
</span>
and here is insta2.php
<?php
if(isset($_POST['lastmsg']))
{
$a= $_POST['lastmsg'];
$a = $a++;
?>
<br>
<span class="more" id="morebutton">
<a id="<?php echo $a;?>" class="more2" title="Follow" href="#" style="color:#000">
<?php echo $a;?> Read More
</a> </span>
<?php }?>
my jquery only one 1 set and after that every click not working
is there any way to continue counting ?
like this
Read More
1 Read More
2 Read More
3 Read More
4 Read More
and so on...
Your ajaxed in content does not have the jquery listener attached to it. Basically, your jquery will run only on your original HTML.
You can bind your click event to an element that is always on the page using the .on() function, and use the selector parameter to define your read more links. (Please read the jQuery manual for more info on this).
Eg:
$('body').on('click', 'span.more', function(){
// Do your ajax stuff
});
This will bind the click event to your body as opposed to 'span.more' and will work for any span.more added to the body.
Edit - JS Fiddle:
http://jsfiddle.net/g8G83/
<span id="more">
<a id="1" class="more2" title="Follow" href="#" style="color:#000">
Read More
</a>
</span>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(function() {
$(".more2").click(function readmore() {
var element = $(this);
var msg = element.attr("id");
$.ajax({
type: "POST",
url: "insta2.php",
data: "lastmsg="+ encodeURIComponent(msg),
success:function (data) {
$("#more").append(data);
$(".more2").off("click");
$(".more2").on("click",readmore);
}
});
return false;
});
});
</script>

How to autorefresh every 1 minute a single div in single post wordpress with inner page template

How to setup an div to auto refresh?
I use Transcript theme for wordpress, in single.php is on call for inner php page:
</div><!-- /innerLeft -->
<?php include (TEMPLATEPATH . '/innerNarrowSidebar.php'); ?>
<?php include (TEMPLATEPATH . '/innerWideSidebar.php'); ?>
<div class="clear"></div>
The code inside innerNarrowSidebar.php
<?php if($trns_options['enArc'] == 1) { ?>
<div class="widget">
<h3 class="widget_sTitle_b"><?php _e('Archives','Transcript'); ?></h3>
<ul>
<?php wp_get_archives('type=monthly'); ?>
</ul>
</div>
<?php } ?>
And than in innerpage_120x600.php
I have some google adsense
**NOTE**: I added this code in innerNarrowSidebar.php but dosn't work , the div dosn't autorefresh
There is the code that i have added:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script language="JavaScript">
setInterval( "SANAjax();", 10000 ); ///////// 10 seconds
$(function() {
SANAjax = function(){
$('#narrowSidebar').fadeOut("slow").load('ads/innerpage_120x600.php').fadeIn("slow");
}
});
</script>
If this is not possible, how to make an text widget to auto refresh?
As described in comments:
<script language="JavaScript">
$j(function($) {
var SANAjax = function(){
//Add here anticache modificator:
var rnd=Math.random();
$('#narrowSidebar').fadeOut("slow").load('ads/innerpage_120x600.php?nc='+rnd).fadeIn("slow");
}
setInterval(SANAjax, 10000 ); ///////// 10 seconds
});
</script>

Categories