run javascript on separate ajax file - php

I have a question where I'd like to execute ReadMore/ReadLess javascript when button is clicked.
The clicked function is an ajax PostData() function .
The article or paragraph is located at a separate file called gethint.php
I dont get the javascript works in this scenario. However if I moved article or paragraph to the display.php , then it sucessfully run.
display.php
echo '<head><script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script></head>';
<input type="url" id="Url" name="Url" placeholder="http://example.com " class="form- control"/>
<span class="input-group-btn">
<button type="button" id="tx" class="btn green" onclick="PostData()"></button>
</span>
<div id="result"> </div>
<script>
function PostData() {
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
var target = document.getElementById('result');
if (xhr.readyState === 4) {
if (xhr.status === 200 && xhr.status < 300) {
document.getElementById('result').innerHTML = xhr.responseText;
}
}
};
// 2. Define what to do when XHR feed you the response from the server - Start
var url = document.getElementById("Url").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'gethint.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("Url=" + url);
// 3. Specify your action, location and Send to the server - End
}
</script>
//script for Read More /Read Less
<script>// Hide the extra content initially, using JS so that if JS is disabled, no problemo:
$(".read-more-content").addClass("hide");
$(".read-more-show, .read-more-hide").removeClass("hide");
// Set up the toggle effect:
$(".read-more-show").on("click", function(e) {
$(this).next(".read-more-content").removeClass("hide");
$(this).addClass("hide");
e.preventDefault();
});
$(".read-more-hide").on("click", function(e) {
$(this).parent(".read-more-content").addClass("hide");
var moreid=$(this).attr("more-id");
$(".read-more-show#"+moreid).removeClass("hide");
e.preventDefault();
}); </script>
gethint.php
<?php
if(isset($_POST['Url'])) {
$query = $_POST['Url'];
echo "<p> URL is " . $query . "</p>"
echo '<article>
<p>Egestas quos curabitur cum. <a class="read-more-show hide" href="#" id="1">Read More</a> <span class="read-more-content">Suspendisse! Rutrum cupidatat! <a class="read-more- hide hide" href="#" more-id="1">Read Less</a></span></p>
<p>Egestas mollitia quos natus. <a class="read-more-show hide" href="#" id="2">Read More</a> <span class="read-more-content">Suspendisse! Rutrum cupidatat! <a class="read-more- hide hide" href="#" more-id="2">Read Less</a></span></p>
<p>Egestas mollitia curabitur cum. <a class="read-more-show hide" href="#" id="3">Read More</a> <span class="read-more-content">Suspendisse! Rutrum conubia cupidatat! <a class="read-more-hide hide" href="#" more-id="3">Read Less</a></span></p>
</article> ' ;
}

You need to execute the code in your last script tag after the AJAX call has completed. Move it to a function and call the function. Given that you're using jQuery already, I'd recommend using jQuery.post and, in the callback, you can execute the code from your last script tag.

Related

Why does ajax only work on the newest post?

I'm creating a social media site with php & mysqli. On the index page all post are loaded using a while loop and on the profile page that specific users post are loaded the same way. I have the like button hooked to ajax so you can like without refresh but it only works on the latest post.
The inside the while loop I have include('post.php') and this is what is in there.
<div class="post_options" id="post_options">
<div class="op_container like<?php echo $row['id'] ?>">
<i class="fa-regular fa-heart"></i> Like
</div>
<div class="op_container">
<i class="fa-regular fa-comment"></i> Comment
</div>
<div class="op_container">
<i class="fa-solid fa-share"></i> Share
</div>
</div>
</div>
<script>
const button = document.querySelector(".post_options .like<?php echo $row['id'] ?>")
button.onclick = () => {
let xhr = new XMLHttpRequest();
xhr.open("GET", "db/like_unlike.php?userid=<?php echo $_SESSION['id'] ?>&contentid=<?php echo $row['id'] ?>", true);
xhr.onload = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
button.classList.toggle("active")
}
}
}
xhr.send();
}
</script>
What i understand from your code is that your script is outside the while loop. Hence it is taking the last value from your loop as the $row variable will store latest value.
You can add data attribute to your post div and then get that value on button click
<div class="post_options" id="post_options" data-id="<?php echo $row['id'] ?>">
<div class="op_container like<?php echo $row['id'] ?>">
<i class="fa-regular fa-heart"></i> Like
</div>
<div class="op_container">
<i class="fa-regular fa-comment"></i> Comment
</div>
<div class="op_container">
<i class="fa-solid fa-share"></i> Share
</div>
</div>
<script>
const button = document.querySelector(".post_options")
button.onclick = () => {
var contentid = $(this).data('id');
let xhr = new XMLHttpRequest();
xhr.open("GET", "db/like_unlike.php?userid=<?php echo $_SESSION['id'] ?>&contentid="+contentid, true);
xhr.onload = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
button.classList.toggle("active")
}
}
}
xhr.send();
}
</script>

Change class toggle to multiple span element with Jquery

I need to change the class of a span child that uses a toggle when I click on one of the browser rows.
But it only works when there is a single row, when there are several rows it does not find the span and it does not work.
I also tried to use the href to select the correct span, but I don't know how to use it in the JQuery code
<div>
<a id="menu-toggle" data-toggle="collapse" data-parent="#accordion" href="#01" class='btn btn-default' title='Ver pagos'>
<span class="glyphicon glyphicon-chevron-down"></span>
</a>
</div>
<div>
<a id="menu-toggle" data-toggle="collapse" data-parent="#accordion" href="#02" class='btn btn-default' title='Ver pagos'>
<span class="glyphicon glyphicon-chevron-down"></span>
</a>
</div>
jQuery(function($) {
$('#menu-toggle').on('click', function() {
var $el = $(this),
textNode = this.lastChild;
var $href = $(this).attr('href');
var $href = $href.substring(1);
$el.find('span').toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});
});```
Try this
var el = 2
for(var i=0; i<el.length; i++) {
document.getElementsByClassName("glyphicon").find('span').toggleClass('glyphicon-
chevron-down glyphicon-chevron-up');
}
Finally I simplified the code so I commented the span and then call with the function onclick CambiaClass, using a class data1, data 2 ... dataN (to identify the item) and now is working fine.
Thanks for your help Rahul!!!
<a id="menu-toggle" data-toggle="collapse" data-parent="#accordion" href="#<?php echo $id_item; ?>"
class='btn btn-default glyphicon glyphicon-chevron-down <?php echo 'dato'.$id_item; ?>'
title='Ver pagos' onclick="CambiaClass('<?php echo 'dato'.$id_item; ?>')">
<!-- span class="glyphicon glyphicon-chevron-down"></span -->
</a>
//Jquery
<script type="text/javascript">
function CambiaClass(idclass) {
$("[class*='"+ idclass+"']").toggleClass('glyphicon glyphicon-chevron-down').toggleClass('glyphicon glyphicon-chevron-up');
}
</script>

How to get new session value after some time using PHP

I need to get the new session value after some second using PHP. My code is below.
<button class="btn nextbtnbgdiv open2" type="button">Next <span class="fa fa-arrow-right"></span></button>
<div class="fyndspacecategory fyndsheightsubc nano">
<div class="nano-content">
<?php
$cat_id= $_SESSION['cid'];
?>
</div>
</div>
Here when user is clicking on next button the div section is opening and the the value is fetching from session. Here i need after some second always the updated $_SESSION['cid'] will fetch at each time click on next button.
In order to fetch the updated $_SESSION['cid'] you will need to make a call to the server to return this value, you can do so by embedding the value into an element i.e.
Back-end (i.e. get_session.php):
<html>
<body>
<div id="session"><?= $_SESSION['cid'] ?></div>
</body>
</html>
Front-end:
<button class="btn nextbtnbgdiv open2" type="button">Next <span class="fa fa-arrow-right"></span></button>
<div class="fyndspacecategory fyndsheightsubc nano">
<div class="nano-content"><?php $cat_id= $_SESSION['cid']; ?></div>
</div>
<script>
jQuery(function($) {
$(document).on( 'click', '.nextbtnbgdiv', function() {
$('.fyndspacecategory .nano-content').load('/get_session.php', '#session');
});
});
</script>
Or you could use a header within a page to access $_SESSION['cid'].
<?php
if ( isset( $_GET['get_session'] ) && $_GET['get_session'] ) {
header( 'X-Session: ' . $_SESSION['cid'] );
exit;
}
?>
<button class="btn nextbtnbgdiv open2" onclick="javascript:getSession();" type="button">Next <span class="fa fa-arrow-right"></span></button>
<div class="fyndspacecategory fyndsheightsubc nano">
<div class="nano-content" id="sessionId"><?php $cat_id= $_SESSION['cid']; ?></div>
</div>
<script>
function getSession() {
var request = new XMLHttpRequest();
request.onerror = function() { console.warn('An error occurred while checking session.'); };
request.open('HEAD', '?get_session=true', true);
request.onload = function() {
if ( request.getResponseHeader('X-Session') ) {
document.getElementById("sessionId").innerHTML = request.getResponseHeader('X-Session');
}
};
request.send();
}
</script>
This is not tested but should be enough to give you a start to complete your goal.

jQuery code does work after updating

I have page where an instant search results are displaying using PHP & AJAX and <a> tag onclick from response item, it generate preview of track. Everything is working fine but when I update my jQuery version from 1.7.2 to 1.11.3 or 2.1.4. It open link instead of generating preview.
My code
<!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function($)
{
$(".videos .expand-video a.soundcloud").live("click", function(){
var scURL = $(this).attr("href");
var scID = $(this).attr("id");
var embedAudio = "<iframe width=\"100%\" height=\"166\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url="+scURL+"&color=ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false\"></iframe>";
$("#sc-"+scID).html(embedAudio);
return false;
});
var timer = null;
$("#keyword").keyup(function()
{
if(timer)
{
clearTimeout(timer);
}
timer = setTimeout(function()
{
var sc_keyword = $("#keyword").val();
var obj = $(this);
if(sc_keyword != '')
{
$(".ajax_indi").show();
var str = $("#fb_expand").serialize();
$.ajax({
type: "POST",
url: "fetch.php",
data: str,
cache: false,
success: function(htmlresp)
{
$('#results').html(htmlresp);
$(".ajax_indi").hide();
}
});
}
else
{
alert("Search for your favourite news");
$("#keyword").focus();
}
}, 1000);
});
});
</script>
I know .live() has been removed in version 1.9 onwards. So, I tried to update it to .on() but does not done it successfully
What I have tried to update from .live() to .on() is below
$(".videos .expand-video a.soundcloud").on("click", 'a', function(){
var scURL = $(this).attr("href");
var scID = $(this).attr("id");
var embedAudio = "<iframe width=\"100%\" height=\"166\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url="+scURL+"&color=ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false\"></iframe>";
$("#sc-"+scID).html(embedAudio);
return false;
});
HTML OUTPUT Response of ajax request
<div class="videos" id="sc-80912043">
<div class="expand-video"> <a class="soundcloud" id="80912043" href="https://api.soundcloud.com/tracks
/80912043"><span></span> <img src="https://i1.sndcdn.com/avatars-000033051760-4ugg0i-large.jpg" width
="120" height="90" title="Play" alt="Play"/> </a> </div>
<div class="details">
<h6>DJ MHA - Menu Chad De (MHA Remix)</h6>
<p class="link">Gangzta Khan</p>
<p class="desc">DJ MHA - Menu Chad De (MHA Remix)..
Gangzta Khan ..</p>
</div>
</div>
<div class="videos" id="sc-24508938">
<div class="expand-video"> <a class="soundcloud" id="24508938" href="https://api.soundcloud.com/tracks
/24508938"><span></span> <img src="https://i1.sndcdn.com/avatars-000002625883-ve8pmk-large.jpg" width
="120" height="90" title="Play" alt="Play"/> </a> </div>
<div class="details">
<h6>Halka Halka Suroor - MHA Mix</h6>
<p class="link">DJ MHA</p>
<p class="desc">Yeh Jo Halka Halka Suroor Hai
Direct Download Link:
http://www.djmha.com/get.php?file=Halka_Halka_Suroor_-_MHA_Mix.mp3</p>
</div>
</div>
<div class="videos" id="sc-65996317">
<div class="expand-video"> <a class="soundcloud" id="65996317" href="https://api.soundcloud.com/tracks
/65996317"><span></span> <img src="https://i1.sndcdn.com/avatars-000002625883-ve8pmk-large.jpg" width
="120" height="90" title="Play" alt="Play"/> </a> </div>
<div class="details">
<h6>Zarina Taylor - (DJ MHA Remix)</h6>
<p class="link">DJ MHA</p>
</div>
</div>
You're being too specific with your selector before calling .on(). The way the function works is you select elements that will always exist on the page, and bind the delegated event handler to those. Since you're replacing the content of the <div> elements with class videos, your code should be this:
$(".videos").on("click", ".expand-video a.soundcloud", function(){
var scURL = $(this).attr("href");
var scID = $(this).attr("id");
var embedAudio = "<iframe width=\"100%\" height=\"166\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url="+scURL+"&color=ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false\"></iframe>";
$("#sc-"+scID).html(embedAudio);
return false;
});
First, we select the .videos elements, then we bind a delegated event handler for a.soundcloud elements which are inside a .expand-video element (which are in turn inside a .videos element). That way, when you update the content of one of those elements in this line - $("#sc-"+scID).html(embedAudio); - the delegated event handler still exists.
I dont know why this worked in an old version!!!
So just for one video
<div class="videos" id="sc-80912043">
<div class="expand-video"> <a class="soundcloud" id="80912043" href="https://api.soundcloud.com/tracks
/80912043"><span></span> <img src="https://i1.sndcdn.com/avatars-000033051760-4ugg0i-large.jpg" width
="120" height="90" title="Play" alt="Play"/> </a> </div>
<div class="details">
<h6>DJ MHA - Menu Chad De (MHA Remix)</h6>
<p class="link">Gangzta Khan</p>
<p class="desc">DJ MHA - Menu Chad De (MHA Remix)..
Gangzta Khan ..</p>
</div>
</div>
This is a problem i have had a few times .on does not act the same as live with the active binding even though it's supposed to...
function gotAJAXResults(){
$(".videos .expand-video a.soundcloud").unbind("click");
$(".videos .expand-video a.soundcloud").click(function(e){
e.preventDefault();
var scURL = $(this).attr("href");
var scID = $(this).attr("id");
var embedAudio = "<iframe width=\"100%\" height=\"166\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url="+scURL+"&color=ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false\"></iframe>";
$("#sc-"+scID).html(embedAudio);
return false;
});
}
Ok so now your AJAX call becomes
$.ajax({
type: "POST",
url: "fetch.php",
data: str,
cache: false,
success: function(htmlresp)
{
$('#results').html(htmlresp);
gotAJAXResults();
$(".ajax_indi").hide();
}
});
This method will then force it to bind the event when ajax receives and has inserted them into the page. (DOM scope)

Attaching jQuery/AJAX scripts to elements added using window.setInterval(, 1000*60) method

I have a problem with auto updating a div. I have a script as shown below which refreshes the page content (like facebook) every 1 minute. The problem is that this div is newly added to the page and that it contains some ajax/jQuery elements to add effects.
function loadNewPosts(){
var id = $(".altbgcolor:first").attr("id");
$.get('/update.php', { updateid: id ,catid:'technology' }, function(data){
$(".newslist").prepend(data);
}, 'html');
}
window.setInterval(loadNewPosts, 1000*60)
Below is an example of div its supposed to populate if found via update.php
<li class="altbgcolor" id=755>
<div> <a href=http://mashup2.sunnydsouza.com/technology/755/ target="_blank" rel="nofollow">
<div class="newsthumb" center center no-repeat;"><img src="http://mashup2.sunnydsouza.com/timthumb.php?src=/images/tech/thumb-755.jpg&h=100&w=100&zc=1&a=t" /></div>
</a>
<div class="newstext" style="margin:0px;">
<h1 style="color:#081C28;"><img width="11" height="9" src="/content/icon_topic_newest.gif"> Top 5 Android Apps for Travel </h1>
<!--<i><font color=red size=1.2>Technology</font></i><br>-->
<div style="font-size: 0.4em; color:#666666;">
<!-- AddThis Button BEGIN -->
<!--<span class="st_email" st_url="http://mashup2.sunnydsouza.com/technology/755/" st_title="Top 5 Android Apps for Travel" ></span>
<span class="st_facebook" st_url="http://mashup2.sunnydsouza.com/technology/755/" st_title="Top 5 Android Apps for Travel" ></span>
<span class="st_twitter" st_url="http://mashup2.sunnydsouza.com/technology/755/" st_title="Top 5 Android Apps for Travel" ></span>
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=sunnydsouza"></script>-->
<!-- AddThis Button END -->
<span style="text-decoration:none; color:none; "><i> via demo1</i></span>
<span style="text-decoration:none; color:none; ">
<a class="example7" href="comments_3.php?id=755" style="text-decoration:none; color:#666666; "><img src="content/comment/comments.png" width=18 height=18><i>No comments</i></a></span>
<span style="text-decoration:none; color:none; margin:5px;"><img src="content/voting/eye.png" > 17</span>
<!-- Vote Buttons #vote-->
<span class="vote" id="755" name="up" style="text-decoration:none; color:none; margin:5px; ">
<img src="/content/voting/yes-enb.png" width=12 height=12 alt="">
<span style="text-decoration:none; color:none">1 </span></span>
<!-- Vote Buttons ENDS #vote-->
<br>
<i><font color=red size=1.2>Technology</font></i>
</div>
<!--<h1>read...</h1>-->
</div><div class="clear"></div>
</div>
<div class="sharedp">
<span class="st_email" st_url="http://mashup2.sunnydsouza.com/technology/755/" st_title="Top 5 Android Apps for Travel" ></span>
<span class="st_facebook" st_url="http://mashup2.sunnydsouza.com/technology/755/" st_title="Top 5 Android Apps for Travel" ></span>
<span class="st_twitter" st_url="http://mashup2.sunnydsouza.com/technology/755/" st_title="Top 5 Android Apps for Travel" ></span>
</div>
</li>
Though the above code calls the update.php every 1 minute and adds elements to the current page. The current div is devoid on the javascript element
This is the javascript on the main page which attaches itself to every div on every element initially to the span class="vote"
// thumbs up / thumbs down code
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
{
//$(this).fadeIn(200).html('<img src="/content/voting/yes-enb.JPG" />');
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.find('span').html(html);
}
});
}
return false;
});
});
However for the new elements added during the auto update, when clicking on the vote button..nothing happens.
Why is this happening. Why is the jQuery mentioned in the page at start not working for the auto newly added divs?
Please help
EDIT:: I have 2 more javascript elements. How do i convert them to .live ?
$(document).ready(function(){
$(".altbgcolor").hover(function() {
$(this)
.addClass('altbgcolor-active')
.find(".sharedp")
.slideDown('slow');
},function () {
$(this)
.removeClass('altbgcolor-active')
.find(".sharedp")
.slideUp('slow');
});
$(".example7").colorbox({
onOpen:function(){ alert('onOpen: colorbox is about to open'); },
onLoad:function(){ alert('onLoad: colorbox has started to load the targeted content'); },
onComplete:function(){ alert('onComplete: colorbox has displayed the loaded content'); },
onCleanup:function(){ alert('onCleanup: colorbox has begun the close process'); },
onClosed:function(){ alert('onClosed: colorbox has completely closed'); }
)};
});
EDIT2: This is what I am trying, Please validate if its correct...
$(".altbgcolor").live('hover',function() {
$(this)
.addClass('altbgcolor-active')
.find(".sharedp")
.slideDown('slow');
},function () {
$(this)
.removeClass('altbgcolor-active')
.find(".sharedp")
.slideUp('slow');
});
$(function() {
$(".vote").live('click', function () {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
{
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function (html) {
parent.find('span').html(html);
}
});
}
return false;
});
});
Have you considered jQuery's live() for this? It will attach the eventhandler to all current and future elements.

Categories