I'm stuck on my project for college, I've been working on a small time microblog, this may seem silly but I have no idea on how to make the feed auto refresh without killing my monthly bandwidth, here is the code I'm using atm,
Data.php
<?php
// connect to the database
require_once 'script/login.php';
//show results
$query = "SELECT post, PID, fbpic, fbname, fblink, post_date, DATE_FORMAT(post_date, 'Posted on %D %M %Y at %H:%i') AS pd FROM `posts` WHERE 1\n"
. "ORDER BY `post_date` DESC LIMIT 0, 30 ";
$result = #mysql_query ($query);
if ($result) { //If it ran ok display the records
echo '<div id="feed">';
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
echo '<a name="' . $row['PID'] . '"></a><div id="postsint"><a target="_blank" href="http://www.facebook.com/' . $row['fblink'] . '"><img id="dp" title="' . $row['fbname'] . '" src="https://graph.facebook.com/' . $row['fbpic'] . '/picture"/></a><div id="posttext">' . base64_decode($row['post']) . '<blockquote>' . $row['pd'] . '</blockquote>Share</div></div><br />';
};
echo '</div>';
mysql_free_result ($result);
} else { //if it did not run ok
echo '<h2 id="error">Wisprs could not be retrieved. We apologise for any inconvienience.</h2>'; //public message
echo '<p id="error">' . mysql_error() . '<br /><br /> Query: ' . $query . '</p>'; //debugging message
}
mysql_close(); // Close database connection
?>
content.php
<div id="postlist"> FEED GOES HERE.</div>
All im trying to do is check for updates every 2 seconds and if there is updates then show them in #postlist
It's been a 3 week struggle and I don't know any JavaScript, it's annoying me and I just want to finish this project so I can go to University and maybe learn to do this myself =/
Cheers in advance.
PS - I'm only guessing that it's Ajax but my tutor recommended this site for an answer if I get stuck
Hopefully you are allowed to use jQuery.
Add to content.php:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
function getFeed(){
$.post('Data.php',function(data){
$("#postlist").html(data);
});
setTimeout("getFeed();",2000);
}
window.onload = getFeed();
</script>
getFeed() is called on page load, then calls itself every 2000 milliseconds and appends the data received from Data.php into your postlist element.
This is brute forcing it, making it constantly delete the old html in the postlist div and create all new html every 2 seconds. If you have images that you are loading you will need a more complex solution.
If you use KnockoutJS and jQuery, this might be a good starting point:
http://jquery.com/
http://knockoutjs.com/
content.php
<script type="text/javascript">
$(function() {
// Define our view model that we will feed to KnockoutJS.
var viewModel = {
posts: []
};
// We'll use this variable to keep track of the last post we
// received. When we send our GET request, our php script will be
// able to see $_GET['last_post_date'] and only return the posts
// that come after that.
var last_post_date = null;
// This is the function that will get called every 2 seconds to
// load new data.
var getData = function() {
$.ajax({
url: "/data.php",
data: {
last_post_date: last_post_date
}
}).done( function( data ) {
// We'll assume data.php will give us a JSON object that looks
// like: { posts: [] }
// Append the new posts to the end of our 'posts' array in our
// view model.
viewModel.posts.concat( data.posts );
// Tell KnockoutJS to update the html.
ko.applyBindings( viewModel );
// Store the date of the last post to use in our next ajax call.
last_post_date = viewModel.posts[ viewModel.posts.length - 1 ].post_date;
});
// In 2 seconds, call this function again.
setTimeout( getData, 2000 );
};
// grab the first set of posts and start looping
getData();
});
</script>
<!-- We're telling KnockoutJS that for each 'row' in our 'posts' array, apply
the template named 'row-template'. -->
<div id="postlist"
data-bind="template: { name: 'row-template', foreach: posts }"></div>
<!-- This is the KnockoutJS template that we referenced earlier. Of course,
you don't have to use KnockoutJS to do this. There are plenty of other ways
to do this. Do keep in mind that you'll minimize your bandwidth usage if you
send JSON and use an HTML template rather than loading the same HTML over
and over again. -->
<script type="text/html" id="row-template">
<a data-bind="attr: {name: PID}"></a>
<div id="postsint">
<a target="_blank" data-bind="
attr: {
href: 'http://www.facebook.com/' + fblink
}
">
<img id="dp" data-bind="
attr: {
title: fbname,
src: 'https://graph.facebook.com/' + fbpic + '/picture'
}
" />
</a>
<div id="posttext">
<!--ko text: post--><!--/ko-->
<blockquote data-bind="text: pd"></blockquote>
<a data-bind="
attr: {
href: 'https://www.facebook.com/dialog/feed?' +
'app_id=505747259483458&' +
'link=http://www.wisp-r.com/share.php?' +
'id=' + PID + '&' +
'picture=http://www.wisp-r.com/images/app-icon.png&' +
'name=Wispr by ' + fbname + '&' +
'caption=' + pd + '&' +
'description=' + post + '&' +
'redirect_uri=http://www.wisp-r.com/share.php?id=' + PID
}
">
Share
</a>
</div>
</div>
<br />
</script>
data.php
<?php
// ... do sql stuff ...
// Remember to add a WHERE statement to filter out posts that are earlier than
// or equal to $_GET['last_post_date'].
$posts = array();
if ( $result ) {
while ( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
array_push( $posts, $row );
}
}
echo json_encode( array( 'posts' => $posts ) );
Related
I have a form that posts to a script via ajax, the script inserts the form data into a database and using ajax i the refresh the div on the original page which then shows the form as well as a list of records in the database (from the form input)
I hope that makes sense.
My issue is that sometimes, maybe 1 time in 20, the div refreshes too quickly and doesn't pick up on the new data if i refresh the page its there and if i submit a new record both records are then in the list.
I guess i just need to delay the refreshing but i don't know how.
thanks,
php
echo '<div id="cuttingListDiv">';
$sql = "SELECT * FROM `cuttingList` WHERE jobRef = '".$_SESSION["jobRef"]."' ORDER BY pieceMaterialName, pieceThickness ASC";
$results = $dbconn->query($sql);
if ($results->num_rows > 0) {
echo '<h3>Cutting List:</h3>';
echo '<div align="center">';
while($row = $results->fetch_assoc()) {
echo '<br />';
echo '<div class="row">';
echo '<div class="col" align="center">';
echo '<h5>'.$row["pieceMaterialName"] . ' - ' . $row["pieceLength"] . ' x ' . $row["pieceWidth"] . ' x ' . $row["pieceThickness"] . 'mm</h5>';
echo '<br />';
echo '</div>';
echo '</div>';
}
echo '</div>';
}
echo '</div>';
ajax script
session_start();
include '_script_sqlConnection.php';
$pieceLength = strip_tags($_POST['pieceLength']);
$pieceWidth = strip_tags($_POST['pieceWidth']);
$thickness = strip_tags($_POST['thickness']);
$material = strip_tags($_POST['material']);
$materialName = strip_tags($_POST['materialName']);
$sheetID = strip_tags($_POST['sheetID']);
// Swap width & length id width bigger
if ($pieceWidth > $pieceLength) {
$tmpDimm = $pieceLength;
$pieceLength = $pieceWidth;
$pieceWidth = $tmpDimm;
}
$sql = "INSERT INTO `cuttingList`(`orderRef`, `pieceMaterialName`, `pieceThickness`, `pieceLength`, `pieceWidth`, `sheetID`, `pieceWeight`, `qty`) VALUES ('".$_SESSION["quoteRef"]."', '".$materialName."', '".$thickness."', '".$pieceLength."', '".$pieceWidth."', '".$sheetID."', '".$pieceWeight."', '1')";
if ($dbconn->query($sql) === FALSE) {
echo "Error Adding Pieces To Cut List.<br />";
}
javascript
$("#cuttingListForm").submit(function(){
$.ajax({
type: "POST",
url: "_script_ajax_addToCuttingList.php",
data: $('form.cuttingListForm').serialize(),
success: function() {
$("#cuttingListDiv").load(location.href + " #cuttingListDiv");
}
});
});
Use the JS function setTimeout
// example of usage for setTimeout:
setTimeout( function(){
$("#cuttingListDiv").load(location.href + " #cuttingListDiv");
}, 2000 );
In the example you have 2000 milliseconds for 2 second wait before fired the call.
Thanks for you help but i went a different way as i was still having trouble with both of these methods.
At the very top of the div that refreshes I used the php sleep command to wait 1 second, now it works perfectly.
Thanks,
I have created a drop down menu in php that is displayed however, when a value has been clicked, I don't know how to collect this information.
<html>
<body>
<?php
$mydb = new mysqli('localhost','root','','TestTimeTableSolution');
$rows = $mydb->query("SELECT DISTINCT TeacherID FROM Teacher;")->fetch_all(MYSQLI_ASSOC);
$teachers = array();
foreach ($rows as $row) {
array_push($teachers, $row["TeacherID"]);
}
$dropdownMenu = "<select name='TeacherID' form='Teacher'><option value='Null' selected>All</option>";
foreach ($teachers as $topic) {
$dropdownMenu .= "<option value='" . $topic . "'>" . $topic . "</option>";
}
$dropdownMenu .= "</select>";
echo $dropdownMenu;
?>
</body>
</html>
Based on your last comment, "i want it to be dynamic so as soon as the user clicks on something the relevant information will pop up", it sounds like you will probably want to use Ajax/JavaScript (I will demonstrate a simple jQuery example, notating for clarity):
<?php
$mydb = new mysqli('localhost','root','','TestTimeTableSolution');
?>
<html>
<!-- Add the jQuery library -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// Act when the document is ready
$(function(){
// listen for the select to change
$('select[name=TeacherID]').on('change',function(){
// Run the ajax – you can also use the shortcut $.post method found at:
// https://api.jquery.com/jquery.post/
$.ajax({
// This is the page that is going to do the data lookup/display action
url: '/lookup.php',
// This is how it's sending the data to that page
type: 'post',
// This is what is being sent ($_POST['submit'] in this case)
data: {
// Use $(this) to isolate the current selected element and get value (.val())
// The value is represented as $topic in your php
'submit': $(this).val()
},
// If all goes well and the page (lookup.php) returns a response
success: function(response) {
// Place the response into the div (see html snippet)
$('#loadspot').text(response);
}
});
});
});
</script>
<body>
<?php
$rows = $mydb->query("SELECT DISTINCT TeacherID FROM Teacher;")->fetch_all(MYSQLI_ASSOC);
$teachers = array();
foreach ($rows as $row) {
array_push($teachers, $row["TeacherID"]);
}
$dropdownMenu = "<select name='TeacherID' form='Teacher'><option value='Null' selected>All</option>";
foreach ($teachers as $topic) {
$dropdownMenu .= "<option value='" . $topic . "'>" . $topic . "</option>";
}
$dropdownMenu .= "</select>";
echo $dropdownMenu;
?>
<!---------------------------------------------->
<!-- THIS IS WHERE THE CONTENT WILL LOAD INTO -->
<!---------------------------------------------->
<div id="loadspot"></div>
</body>
</html>
In order for this to work, you need the page lookup.php in the domain root (you can make it whatever/where ever you want, but you need to match in the javascript url):
/lookup.php
<?php
# This is what will get placed into the parent page <div id="loadspot"></div>
# Do you your php here in place of this line and return whatever "relative information" you want
print_r($_POST);
You should review the jQuery page I have linked to to get more information and direction for that library and make sure you use your browser's developer tools to monitor javascript errors in the console. Ideally, you want to understand all this via the documentation instead of just copy and paste and move on...
To begin with, I think this is a longshot but hopefully there is someone out there that can help.
To explain the current situation, at the moment I have a custom plugin that grabs various bits of information about a user and their 4 most recent posts.
I am also using the WPBook plugin (so this is on facebook and just just a typical wordpress site)
Ok, so here is my code that is grabbing the 4 most recent posts for a user:
// The Query
query_posts('posts_per_page=4&author='.$blogger_id);
// set $more to 0 in order to only get the first part of the post
global $more;
$more = 0;
// the Loop
while (have_posts()) : the_post();
?>
<div class="oe-grid-box">
<a href="<?php the_permalink() ?>" <?php the_title()?></a>
<div class="oe-grid-box-content">
<?php echo the_content( '...' ); ?>
</div>
<div class="oe-grid-pic">
<a href="<?php the_permalink() ?>">
<span class="<?php echo strtolower($category); ?>"></span>
</a>
<?php echo $image; ?>
</div>
</div>
<?php
endwhile;
// Reset Query
wp_reset_query();
?>
<div id="load-more">Load More</div>
I tried following this tutorial but instead of a separate plugin, placing the code in my existing plugin but now my page won't load:
http://www.problogdesign.com/wordpress/load-next-wordpress-posts-with-ajax/
Ideally, want I want to is when the load more button is clicked, fetch 4 more posts and show them.
If anybody could help I'd really appreciate it.
UPDATE
Ok,
so far I've added in my jQuery to call the php file which should hopefully return posts but it doesn't work.
I am thinking that it's because it doesn't know what the WordPress functions are?
If I put a simple echo in my load more script, the jQuery success function shows an alert to say it worked, but if I start doing WordPress stuff I get an internal server error, this is the code in the load-more.php file:
// load wordpress into template
$path = $_SERVER['DOCUMENT_ROOT'];
define('WP_USE_THEMES', false);
require($path .'/wp-load.php');
$blogger_id = $_GET['id'];
$firstname = $_GET['firstname'];
$surname = $_GET['surname'];
$posts = $_GET['posts'] + 4;
$category = $_GET['category'];
$image = $_GET['image'];
// The Query
query_posts('paged='.get_query_var('paged').'&posts_per_page=' . $posts . '&author='.$blogger_id);
// set $more to 0 in order to only get the first part of the post
global $more;
$more = 0;
// then the same loop as in my page that is making the ajax call.
After a lot of effort, I found the answer, here is a solution for those stuck in the same position.
This goes in your plugin page where you are getting posts for a user etc.
<script type="text/javascript">
$(document).ready(function() {
posts = 8;
author_posts = parseInt(<?php echo $author_posts; ?>);
$("#link_selector").click(function() {
// alert('posts - ' + posts + 'author posts - ' + author_posts);
if ((posts - author_posts) > 3) {
$("#link_selector").text('No more posts!');
}
else {
var category = '<?php echo strtolower($category); ?>';
var id = '<?php echo $blogger_id; ?>';
var firstname = '<?php echo $firstname; ?>';
var surname = '<?php echo $surname; ?>';
// alert(posts + category + id + firstname + surname);
$.ajax({
type: "GET",
url: "/wordpress/wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'loadMore', id: id, firstname: firstname, surname: surname, posts: posts, category: category}),
success: function(data){
$('#ajax_results_container').hide().fadeIn('slow').html(data);
posts = posts + 4;
if ((posts - author_posts) > 3) {
$("#link_selector").text('No more posts!');
}
}
});
}
});
});
</script>
Then in your theme's functions.php, put your function to do your ajax request:
function loadMore() {
$blogger_id = $_GET['id'];
// get your $_GET variables sorted out
// setup your query to get what you want
query_posts('posts_per_page=' . $posts . '&author='.$blogger_id);
// initialsise your output
$output = '';
// the Loop
while (have_posts()) : the_post();
// define the structure of your posts markup
endwhile;
// Reset Query
wp_reset_query();
die($output);
}
Then, just after the closing of your function, put in the action hooks
add_action('wp_ajax_loadMore', 'loadMore');
add_action('wp_ajax_nopriv_loadMore', 'loadMore'); // not really needed
That's it!
To begin with, I think this is a longshot but hopefully there is someone out there that can help.
To explain the current situation, at the moment I have a custom plugin that grabs various bits of information about a user and their 4 most recent posts.
I am also using the WPBook plugin (so this is on facebook and just just a typical wordpress site)
Ok, so here is my code that is grabbing the 4 most recent posts for a user:
// The Query
query_posts('posts_per_page=4&author='.$blogger_id);
// set $more to 0 in order to only get the first part of the post
global $more;
$more = 0;
// the Loop
while (have_posts()) : the_post();
?>
<div class="oe-grid-box">
<a href="<?php the_permalink() ?>" <?php the_title()?></a>
<div class="oe-grid-box-content">
<?php echo the_content( '...' ); ?>
</div>
<div class="oe-grid-pic">
<a href="<?php the_permalink() ?>">
<span class="<?php echo strtolower($category); ?>"></span>
</a>
<?php echo $image; ?>
</div>
</div>
<?php
endwhile;
// Reset Query
wp_reset_query();
?>
<div id="load-more">Load More</div>
I tried following this tutorial but instead of a separate plugin, placing the code in my existing plugin but now my page won't load:
http://www.problogdesign.com/wordpress/load-next-wordpress-posts-with-ajax/
Ideally, want I want to is when the load more button is clicked, fetch 4 more posts and show them.
If anybody could help I'd really appreciate it.
UPDATE
Ok,
so far I've added in my jQuery to call the php file which should hopefully return posts but it doesn't work.
I am thinking that it's because it doesn't know what the WordPress functions are?
If I put a simple echo in my load more script, the jQuery success function shows an alert to say it worked, but if I start doing WordPress stuff I get an internal server error, this is the code in the load-more.php file:
// load wordpress into template
$path = $_SERVER['DOCUMENT_ROOT'];
define('WP_USE_THEMES', false);
require($path .'/wp-load.php');
$blogger_id = $_GET['id'];
$firstname = $_GET['firstname'];
$surname = $_GET['surname'];
$posts = $_GET['posts'] + 4;
$category = $_GET['category'];
$image = $_GET['image'];
// The Query
query_posts('paged='.get_query_var('paged').'&posts_per_page=' . $posts . '&author='.$blogger_id);
// set $more to 0 in order to only get the first part of the post
global $more;
$more = 0;
// then the same loop as in my page that is making the ajax call.
After a lot of effort, I found the answer, here is a solution for those stuck in the same position.
This goes in your plugin page where you are getting posts for a user etc.
<script type="text/javascript">
$(document).ready(function() {
posts = 8;
author_posts = parseInt(<?php echo $author_posts; ?>);
$("#link_selector").click(function() {
// alert('posts - ' + posts + 'author posts - ' + author_posts);
if ((posts - author_posts) > 3) {
$("#link_selector").text('No more posts!');
}
else {
var category = '<?php echo strtolower($category); ?>';
var id = '<?php echo $blogger_id; ?>';
var firstname = '<?php echo $firstname; ?>';
var surname = '<?php echo $surname; ?>';
// alert(posts + category + id + firstname + surname);
$.ajax({
type: "GET",
url: "/wordpress/wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'loadMore', id: id, firstname: firstname, surname: surname, posts: posts, category: category}),
success: function(data){
$('#ajax_results_container').hide().fadeIn('slow').html(data);
posts = posts + 4;
if ((posts - author_posts) > 3) {
$("#link_selector").text('No more posts!');
}
}
});
}
});
});
</script>
Then in your theme's functions.php, put your function to do your ajax request:
function loadMore() {
$blogger_id = $_GET['id'];
// get your $_GET variables sorted out
// setup your query to get what you want
query_posts('posts_per_page=' . $posts . '&author='.$blogger_id);
// initialsise your output
$output = '';
// the Loop
while (have_posts()) : the_post();
// define the structure of your posts markup
endwhile;
// Reset Query
wp_reset_query();
die($output);
}
Then, just after the closing of your function, put in the action hooks
add_action('wp_ajax_loadMore', 'loadMore');
add_action('wp_ajax_nopriv_loadMore', 'loadMore'); // not really needed
That's it!
I have a page that has a list of items. On the bottom of the page is a "view more" button. When someone clicks this button, the page needs to add more items. The var is $displayedquestions, and the page is coded right now to refresh when the "view more" button is clicked, but we'd like to have it do it live. How can this be done?
Here is code:
<?php
include "db_connect.php";
db_connect();
function tags($tags)
{
$tagarray=explode(",",$tags);
$i=0;
$finished='false';
while($finished=='false') {
if (empty($tagarray[$i])=='true') {
$finished='true';
} else {
$taglist = $taglist . '<a class="commonTagNames" href="">' . $tagarray[$i] . '</a> ';
$i++;
}
}
return $taglist;
}
function formattime($timesince)
{
$strsince=number_format($timesince,0,'','');
$nodecimals=intval($strsince);
if ($nodecimals<1){
return "Less than a minute ago";
} elseif ($nodecimals>=1&&$nodecimals<60) {
return $nodecimals . " min ago";
} elseif ($nodecimals>60&&$nodecimals<1440){
$hourssince=$nodecimals/60;
$hoursnodecimals=number_format($hourssince,0);
return $hoursnodecimals . " hours ago";
} elseif ($nodecimals>1440){
$dayssince=$nodecimals/1440;
$daysnodecimals=number_format($dayssince,0);
return $daysnodecimals . " days ago";
}
}
$submitbutton=$_REQUEST['viewmore'];
$numquestions=intval($_REQUEST['questions']);
if($numquestions!=0) {
$displayedquestions=$numquestions;
} else {
$displayedquestions=10;
}
$sql="SELECT * FROM `Questions` ORDER BY `Questions`.`ID` DESC LIMIT 0, " . $displayedquestions;
$questions=mysql_query($sql);
while($row = mysql_fetch_array($questions))
{
$id = $row['ID'];
$user = $row['userAsking'];
$question = $row['question'];
$tags = $row['tags'];
$timestamp = $row['timestamp'];
$time=strtotime($timestamp);
$secondssince=(date(U)-$time)/60;
$timesince=formattime($secondssince);
$responses=mysql_query("SELECT * FROM `answersToQuestions` WHERE `idOfQuestion`= '$id'");
$comments=mysql_num_rows($responses);
$likes=mysql_query("SELECT * FROM `likesOfQuestions` WHERE `idOfQuestion`= '$id'");
$numlikes=mysql_num_rows($likes);
$userprofileq = mysql_query("SELECT `ID`,`avatar` FROM `Users` WHERE `username` = '$user'");
$userprofileresult = mysql_fetch_row($userprofileq);
$linktoprofile = $userprofileresult[0];
$avatar = $userprofileresult[1];
$taglist=tags($tags);
echo "</li>";
echo '<li class="questionsList" onclick="showUser(' . $id . ')">
<div id="questionPadding">
<img class="askerImage" width=50 height=50 src="../Images/userimages/' . $avatar . '.png"/>
<div class="questionFirstRow"><h1 class="questionTitle">' . $question . '</h1></div>
<span class="midRow">
<span class="askerSpan"><a class="askerName" href="">'. $user .'</a></span>
</span>
<span class="bottomRow">
<img src="../Images/comment.png"/>
<span class="comments">' . $comments . '</span>
<img src="../Images/likes.png"/>
<span class="likes">' . $numlikes . '</span>
' . $timesince . '
</span>
</div>
</li>';
}
?>
<center><img class="moreQuestions" src="../Images/viewMoreBar.png" alt="More" /></center>
Without doing a lot of work you can add ajax to this. Use this function:
First, (I am assuming you are including the code above into another file) create a container around it. Ex:
<div id='container'>...</div>
Second, add this javascript to the page that includes the code you have above:
<script type="text/javascript">
$(function(){
$("#container img.moreQuestions").parent().live('click', (function (e) {
e.preventDefault();
$("#container").load($(this).attr("href"));
});
});
});
</script>
This will load into #container the script you already have without refreshing the rest of the page.
Note the selector for the More link (slash button) in my example is $("#container img.moreQuestions").parent() because you don't have a class or id on it. You should give a class or id to the More link and use that for the selector.
like #diEcho mentioned, jQuery would be a great help: You could easily refresh your list of items by ajax (retrieving the complete list from a php file for example) as well as update your DOM elements with newly added values. Give it a try.
In addition you should think about getting you initial items by ajax as well. Data logic /display /UI functionality were seperated cleanly this way.