How to update a RSS feed presented in a slideshow? - php

I'm trying to put a rss feed on my webpage and would like to present the articles in a slideshow (Cycle 2).
I'm using a php script ("functions.php)to get the feed and everything works fine but I need help on how to update the feed every 5 minute to check if there are any new articles in the feed.
This is what I have in my div:
<div id="rss-news" class="cycle-slideshow"
data-cycle-fx="fade"
data-cycle-speed="500"
data-cycle-timeout="6000"
data-cycle-slides="> div"
>
<?php
include("functions.php");
//Runs function with feed url and number of posts as arguments
$my_rss = fetch_rss_feed('http://www.thefeed.com/rss', 10);
?>
<?php foreach ($my_rss as $k => $v) : ?>
<div>
<span class="title"><b><?php echo $v['title']; ?></b></span>
<!--<span class="date"><?php echo $v['date']; ?></span> -->
<span class="descr"><?php echo $v['descr']; ?></span>
<span class="enclosure"><img src="<?php echo $v['enclosure']; ?>"></span>
</div>
<?php endforeach; ?>
Update:
I've tried with this code. But it shows all articles at the same time - no cycling:
<html>
<head>
<title>Test</title>
<!--<link rel="stylesheet" href="style.css">-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.cycle2.js"></script>
<script type="text/javascript">
function update() {
$("#notice_div").html('Loading..');
$.ajax({
type: 'GET',
url: 'getrss.php',
timeout: 2000,
success: function(data) {
$("#div-one").html(data);
$("#notice_div").html('');
window.setTimeout(update, 10000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
});
}
$(document).ready(function() {
update();
});
</script>
</head>
<body>
<div id="div-one" class="cycle-slideshow"
data-cycle-fx="fade"
data-cycle-speed="500"
data-cycle-timeout="6000"
data-cycle-slides="> div"
></div>
<div id="notice-div"></div>
</body>
</html>
Any ideas?

You need Javascript/jQuery for this, have a look at this here: Jquery/Ajax call with timer so basically you are setting up a function that gets called every 5min and this function pulls the new data and inserts it in the area where the slideshow is located (the jQuery .html() function will come in handy here)

Related

how to load others comments with out page refresshing

Loading comments others automatically like facebook
**php code updated **
<section class="panel-body">
<div class="container">
<div class="comment">
<div class="commenter" name="comments">
<img width="80px" height="80px" src="uploads/<?php echo $row['photo']; ?>">
</div>
<div class="comment-text-area">
<textarea class="textinput"id="comment" name="comments" placeholder="Comment Here......"></textarea>
<button type="submit" class="butn"name="compost">post comment</button>
</div>
</div>
</div>
</div>
</fotm>
<div id="comments">
<?php include'cajax.php'; ?>
</div>
</section>
</section>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js">
</script>
<script type="text/javascript">
$(document).ready( function(){
$('#comments').load('cajax.php');
refresh();
});
function refresh()
{
setTimeout( function() {
$('#comments').load('cajax.php');
refresh();
}, 1000);
}
</script>
how to load comments automatically without page refreshing I know its
possible with ajax but how to implement code please help us
first create another php file named comments.php or whatever you want and cut and paste the code that fetch the comment from DB in that file
And in your main file where you want to show comments create a div , id="comments" or whatever you want .. and inside that div include the new php file like this
<div id="comments">
<?php include'comments.php'; ?>
</div>
now above that code paste the following javascript code:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js">
</script>
<script type="text/javascript">
$(document).ready( function(){
$('#div_name').load('filename.php');
refresh();
});
function refresh()
{
setTimeout( function() {
$('#div_name').load('filename.php');
refresh();
}, 1000);
}
</script>
Replace the div_name with the name of your div and filename.php .. with your file name

Send argument to dynamic PHP nested inside a PHP page

I have two pages. test1.php and test2.php.
All I want to do is hit submit on test1.php and test2.php be displayed within a div. This is actually working fine, BUT I need to pass an argument to test2.php to limit the results shown from the mySQL database (there'll only ever be one result from a database of 3000 items).
To be honest, I think this is within the javascript, but just not sure how to go about it....
test1.php is
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
// Handler for .ready() called.
$('#SubmitForm').submit(function( event ) {
$.ajax({
url: 'test2.php',
type: 'POST',
dataType: 'html',
data: $('#SubmitForm').serialize(),
success: function(content)
{
$("#DisplayDiv").html(content);
}
});
event.preventDefault();
});
});
</script>
<body>
<div id="page">
<form id="SubmitForm" method="post">
<div id="SubmitDiv" style="background-color:black;">
<button type="submit" class="btnSubmit">Submit</button>
</div>
</form>
<div id="DisplayDiv" style="background-color:red;">
<!-- This is where test2.php should be inserted -->
</div>
</div>
</body>
test2.php is
$pageNum_test1 = 0;
if (isset($_GET['pageNum_test1'])) {
$pageNum_test1 = $_GET['pageNum_test1'];
}
$startRow_test1 = $pageNum_test1 * $maxRows_test1;
mysql_select_db($database_wing, $wing);
$query_test1 = "SELECT * FROM pilots";
$query_limit_test1 = sprintf("%s LIMIT %d, %d", $query_test1, $startRow_test1, $maxRows_test1);
$test1 = mysql_query($query_limit_test1, $wing) or die(mysql_error());
$row_test1 = mysql_fetch_assoc($test1);
if (isset($_GET['totalRows_test1'])) {
$totalRows_test1 = $_GET['totalRows_test1'];
} else {
$all_test1 = mysql_query($query_test1);
$totalRows_test1 = mysql_num_rows($all_test1);
}
$totalPages_test1 = ceil($totalRows_test1/$maxRows_test1)-1;
?>
<div id="page" style="background-color:yellow;">
<?php do { ?>
<?php
echo "Hello World.";
echo $row_test1['firstname']
?>
<?php } while ($row_test1 = mysql_fetch_assoc($test1)); ?>
</div>
<?php
mysql_free_result($test1);
?>
url: 'test2.php?pageNum_test1=' + num,
I think that's what you want.

Jquery AJAX returning empty response on selected values

I am trying to cascade update a SELECT tag using jQuery AJAX.
The criterium is passed as POST/JSON to a PHP script which, in turn, pulls the data from a MySql database using PDO. The response is then displayed using JSON.
My problem is that with 2 specific records, the response will be empty.
The form (selectBB.php):
<?php
include_once '../core/classes/bbClasses.php';
$db=new workingDB();
?>
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<link href="../Core/css/css.css" rel="stylesheet" type="text/css"/>
<script src="../Core/jquery/jquery-1.11.1.js" type="text/javascript"></script>
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>-->
<title>Liste des départements</title>
</head>
<body>
<div id="wrapper">
<header>
<div id="logoZone"></div>
<nav>
<li>Clients</li>
<li>Positions</li>
<li>Clients</li>
<li>Maintenance</li>
<li>Rapports</li>
</nav>
</header>
<aside>
<ul>
<li>Reservation</li>
<li>Location</li>
<li>Renouvellement</li>
</ul>
</aside>
<div id="content">
<form method="$POST" name="frmSlctBB">
<label for="slctDPT">Departement</label>
<select id= "Dpt" name="slctDPT">
<?php
$listDPT=$db->loadDPT();
if(count($listDPT)){
foreach ($listDPT as $DPT) {
echo ("<option value=".$DPT['IDDepartment'].">".$DPT['DepartmentName']."</option>");
}
}
?>
</select>
<label for ="slctVille">Ville</label>
<select id="slctVille" name="slctVille">
</select>
<label for ="slctFormat">Format</label>
<select id="slctFormat" name="slctFormat"></select>
<label for ="slctStatut">Statut</label>
<select id="slctStatut" name="Statut"></select>
</form>
<!--Error log-->
<div class="errorlog"></div>
<!-- End of error log-->
</div> <!-- end of content-->
<footer>
<ul>
<li> <address><strong>Dauphin s.a.</strong>bldg #8, complexe Acra <br>route de Delmas,<br>Delmas, HT6120<br>Haiti</address></li>
</ul>
</footer>
</div> <!-- end of wrapper-->
<script src="../Core/js/searchCritFunctions.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#Dpt").change(function(){
fetchCities();
});
});
</script>
AJAX request
function fetchCities(){
// Uses Ajax to return a list of cities based on selected department
var selDpt= $("#Dpt").val();
$(".errorlog").empty();
$.ajax({
url :'listCities.php',
data:{d:selDpt},
type: 'POST',
dataType: 'JSON'
})
.done( function(result){
// Clear Select from previous entries
$('#slctVille').empty();
//load new entries
for(var i=0;i<result.length;i++){
$('#slctVille').append('<option value='+ result[i].IDCity +'>'+result[i].CityName+'</option>');
};
console.log(result);
})
.fail(function (){
$(document).ajaxError(function(jqXHR,textStatus,thrownError){
$(".errorlog").append("<h3>An error has occured</h3><p>"+textStatus+"</p>");
console.log(thrownError);
})
;
});
};
PDO Statement
<?php
require_once '../core/config/config.php';
class workingDB extends db {
public function loadDPT(){
$sql="SELECT * FROM tblDepartments ORDER BY DepartmentName";
$q = $this->conn->prepare($sql);
$q->execute();
return $row=$q -> fetchAll();
}
public function loadCities($dpt){
$sql="SELECT IDCity, IDDepartement, CityName FROM tblCities WHERE IDDepartement=".$dpt;
$q = $this->conn->prepare($sql);
$q->execute();
$row=$q -> fetchAll();
return $row;
}
}
As a tentative to debug the code, I have outputted the response to the console. If, for example, the data sent thru AJAX is "5", the html response would be :
[{"IDCity":"22","0":"22","IDDepartement":"5","1":"5","CityName":"Hinche","2":"Hinche"},{"IDCity":"23","0":"23","IDDepartement":"5","1":"5","CityName":"Mirebalais","2":"Mirebalais"}]
On the opposite, if Ajax data is "1" or "9", the response would be empty.
Thanks in advance for your help.
P.S.: I have verified the database and these specific rows aren't empty.
P.S.: #Sean, thanks for noting I had forget to add listCities.php
<?php
//Output list of cities based on departments selected
include_once '../core/classes/bbClasses.php';
$d=$_POST['d']; //array of departments selected
$base= new workingDB();
$villes=$base ->loadCities($d);
echo json_encode($villes);
$base="";
?>

AJAX in PHP function is applying to every next instance of the function

Here I have an .ajax function within a PHP function, like this:
function phpFunction($ID) {
print "<script>
$('.uparrow').click(function(){
request = $.ajax({
etc... the rest isn't important.
Anyway, the class .uparrow is an html element that runs this .ajax function when clicked. The other thing you should know is that this function: phpFunction() is called a few times in the document, like this:
phpFunction(1)
phpFunction(2)
phpFunction(3)
However, the problem is that when I load phpFunction(), and I click on the .uparrow element, the .ajax call is made on behalf of each instance of phpFunction() that follows the one whose element I clicked on.
So if I clicked on the .uparrow of phpFunction(1), I would also be virtually clicking on the .uparrows of phpFunction(2) and phpFunction(3). Essentially, I need .uparrow to just be a local class that only applies to the instance of phpFunction() that is currently being called.
The only solution I could think of is to replace .uparrow's class name with something unique to each call of this function. The only difference between each instance of phpFunction() is their input $ID and I was thinking I could redefine .uparrow as:
class = '$ID.uparrow'
or
class = $ID + 'uparrow'
But that doesn't work. So how do I make sure that when I click on .uparrow within phpFunction(1), that the .ajax function only gets called that one time?
This is pretty confusing to explain and probably to understand, so please tell me if there's something that needs elaboration.
Let's say you have a list of elements, and when you click one of them, you want to do an ajax call.
click me
click me
<script>
$(function(){ //on DOM ready
$('.uparrow').on('click', function(){
//do ajax call
$.ajax({
url: 'url here'
type: 'post|get'
data: $(this).attr('data-id'), // you only send the ID of the clicked element
... callbacks, etc
})
});
})
</script>
Now you only have a function that makes an ajax call and takes the parameter to send from the element you clicked.
I hope this is what you wanted to achieve
Try something like this
$('[class="uparrow"]').click( function () {
var request = $.ajax({
// Your ajax call
});
});
this will execute ajax on the clicked element with .uparrow class
HTML
<a class="uparrow" href="#" data-ajax="I'm the first element">Click Me</a>
<a class="uparrow" href="#" data-ajax="I'm the second element">Click Me</a>
<a class="uparrow" href="#" data-ajax="I'm the third element">Click Me</a>
JS:
$('[class="uparrow"]').click(function () {
var currentAjax = $(this).data('ajax')
console.log(currentAjax);
});
And the DEMO
Do not call your php function multiple times. Just one time is sufficient.
Modify the markup of your .uparrow element to include the id like so:
<a class="uparrow" data-id="<?php echo $id; ?>" href="#">TextM/a>
Then re-write your php function like so:
function phpFunction() { /* no need to pass the ID */ ?>
<script>
$(function(){
$(document).on('click', '.uparrow', function(){
$.ajax({
url: 'URL',
type: 'POST'.
data: $(this).attr('data-id')
})
});
})
</script>
<?php } ?>
Call your phpFunction like so:
phpFunction();
UPDATE
<!doctype html>
<html>
<head>
<title>trop</title>
<meta charset='utf-8'>
<link rel='stylesheet' href='css/postStyle.css' />
<link href='http://fonts.googleapis.com/css?family=Exo+2:400,300,200|Homenaje&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel='shortcut icon' href='http://icons.iconarchive.com/icons/visualpharm/icons8-metro-style/256/Music-Note-icon.png'>
<script src='../jquery.js'></script>
<script type='text/javascript' src='../script.js'></script>
</head>
<body>
<?php
$ids = array(1,2,3); // IDs of the posts you want
$result = mysql_query("SELECT * FROM all_posts WHERE ID IN($ids)");
while ($data = mysql_fetch_array($result)){
?>
<div class='post' style='width:470px'>
<h3><?php echo $data['Title']; ?></h3>
<div class='date'><?php echo $data['DateTime']; ?></div>
<iframe width='470' height='300' src='http://www.youtube.com/embed/WF34N4gJAKE' frameborder='0' allowfullscreen></iframe>
<p><?php echo $data['Body']; ?></p>
<div class='postmeta1'>
<p><a href='<?php echo $data['DownloadLink']; ?>' target='_blank'>DOWNLOAD</a></p>
</div>
<div class='verticalLine' style='height:39px'></div>
<div class='postmeta2'>
<p class='uparrow' data-id="<?php echo $data['id']; ?>">▲</p>
<div class='votes'>3</div>
<p class='downarrow'>▼</p>
</div>
<div class='verticalLine' style='height:39px'></div>
<div class='postmeta3'>
<div class='tags'>
<p><?php echo $data['Tags']; ?></p>
</div>
</div>
</div>
<?php } ?>
<script>
var request;
$('.uparrow').click(function(){
request = $.ajax({
url: 'votesHandler.php',
type: 'post',
data: { add : '1', ID : $(this).attr('data-id') }
});
request.done(function (response, textStatus, jqXHR){
alert('Voted!');
});
request.fail(function (jqXHR, textStatus, errorThrown){
alert(
'Oops, something went wrong'
);
});
request.always(function () {
alert('Done.');
});
});
</script>
</body>
</html>

append data to webpage by iterating json object returned (echo) by php

I am using cakephp to develop a webpage that dynamically append data retrieved from server. The appended data can be turned in jquery accordions (not shown).
I've tried some suggestions as seen in other topics, but still nothing shows up on the webpage.
The javascript is as such:
<script type="text/javascript">
$.getJSON('viewmjcatjson.ctp', function(data){
var content = '<div id="majorcat">\n';
$.each(data, function(index,cat){
content += '<h2>' + cat.category + '</h2><div>\n';
content += cat.description + '</div>\n';
});
$("#majorcat").append(content);
});
</script>
The 'viewmjcatjson.ctp' is as such:
<?php
Configure::write('debug', 0);
echo json_encode($majorCategories);
?>
The json object returned is valid (checked with jsonlint)
[{
"MajorCategories":{
"category":"Corporate Governance",
"description":"description on Corporate Governance"
}
},
{
"MajorCategories":{
"category":"Earnings Report",
"description":"description on Earnings Report"
}
},
{
"MajorCategories":{
"category":"Equity",
"description":"Relating to stock"
}
},
{
"MajorCategories":{
"category":"Financial Issue",
"description":"The area of finance dealing with monetary decisions that business enterprises make and the tools and analysis used to make these decisions"
}
}
]
I am suspecting something is wrong in the each loop, but I am not sure.
EDIT
The entire php file containing the javascript.
<?php echo $html->script('jquery-1.5.1.min.js'); ?>
<?php echo $html->script('jquery-ui-1.8.13.custom.min.js'); ?>
<?php echo $html->css('ui-lightness/jquery-ui-1.8.13.custom.css'); ?>
<script type="text/javascript" src="development-bundle/jquery-1.3.2.js"></script>
<script type="text/javascript" src="development-bundle/ui/ui.core.js"></script>
<script type="text/javascript" src="development-bundle/ui/ui.accordion.js"></script>
<div class="users form">
<h1><?php echo $article['Article']['title']?></h1>
<p><small>Author: <?php echo $article['Article']['author_all']?></small></p>
<p><?php echo $article['Article']['full_text']?></p>
<br>
<hr>
<br>
<table>
<tr>
<td width="60%">
<div id="majorcat">
</div>
</td>
<td width="40%">
<div id="minorcat">
</div>
</td>
</tr>
</table>
</div>
<div class="actions">
<h3><?php __('Menu'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Logout', true),
array('controller' => 'users', 'action' => 'logout'));?></li>
</ul>
</div>
<script type="text/javascript">
$(function(){
$.getJSON('viewmjcatjson.ctp', function(data){
var content = '<div id="majorcat">\n';
$.each(data, function(index,cat){
content += '<h2>' + cat.category + '</h2><div>\n';
content += cat.description + '</div>\n';
});
$("#majorcat").append(content);
});
})
</script>
<script type="text/javascript">
$(function(){
$.getJSON('viewmjcatjson.ctp', function(data){
var content = '<div>';
$.each(data, function(index,cat){
content += '<h2>' + cat.MajorCategories.category + '</h2> <div>';
content += cat.MajorCategories.description + '</div>';
});
$("#majorcat").append(content);
});
})
</script>
You're missing the document.ready
I noticed Firebug console showing that 'viewmjcatjson' is responding not with json-encoded data but with a HTML file. The contents is actually exactly the same as the PHP file.
So I deduced it could be a routing problem.
Changing to...
$.getJSON('../viewmjcatjson', function(data){
...solves the problem.
Thanks Interstellar_Coder for the fixed code though.

Categories