AJAX Div Refresh with PHP - ajax

I am trying to refresh some elements on my page every so often. I know theres a million topics on here about that and I have tried to get mine working, but here is what I need to refresh..
This is the code that gets generated when the page loads:
<div id="galleria">
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
$totalImgs = count($a);
$imgUsed = array();
for ($j = 0; $j < 100; $j++)
{
do
{
$randIndex = mt_rand(0, $totalImgs);
}
while ($imgUsed[$randIndex] === TRUE);
$imgUsed[$randIndex] = TRUE;
echo "<img src='" . $dir . '/' . $a[$randIndex] . "' />";
}
?>
</div>
I would like to automatically refresh this every 10 seconds but not reload the page. I have read up on ajax and it seems this is possible but I cannot seem to get it to work.
All this is doing is showing the galleria div, and loading the 100 images inside the div. Then the galleria script takes over and displays it nicely. Will AJAX work better or JQuery?
Thank you for your help!

"Will AJAX work better or jQuery?" -- AJAX is a technique, jQuery is a library. As it turns out, jQuery has an excellent API for AJAX.
Let's call this bit of PHP "galleria.php". On original page load, it is inserted into the parent PHP page using good ol' <?php include('galleria.php')?>. Now the end user is seeing the full initialized page.
To update it, you have a number of AJAX options available, but the easiest is to include jQuery on your page and then you can use .load() in a script:
var updateGallery = setInterval(function() {
$('#someDiv').load('galleria.php');
}, 10000);
There's room for tweaking... maybe galleria.php doesn't include the <div id="galleria">, which is set on the page. In which case you would load right into #galleria instead of #someDiv and save yourself an unnecessary container. Maybe you cache the $('#someDiv') object by declaring it in a different scope so that it can be re-used. But this is the general gist.

Use setInterval function with ajax call.
http://jquery-howto.blogspot.com/2009/04/ajax-update-content-every-x-seconds.html

As I wrote here you can fill a div with a jQuery ajax call.
<html>
<head>
<script type="text/javascript">
function refresh_gallery(){
$.ajax({
type: "POST",
url: "generate_gallery.php", // your PHP generating ONLY the inner DIV code
data: "showimages=100",
success: function(html){
$("#output").html(html);
}
});
}
$(function() {
refresh_gallery(); //first initialize
setTimeout(refresh_gallery(),10000); // refresh every 10 secs
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>

Related

Google style page loading , Bulk records not on onload, display some and fetch remain in back?

I'm developing a web application,after login the user is redirected to the inbox page,
where he will find many widgets, each with hundreds of records.
So it is taking too much time to open inbox page after login success.Very much performance issue.
So i want to display some(5-10) records in each widget
and after the page loads in the backend(user doesn't know) the request will be processing still and fetch the records and append them to the widget records.
Eg. If you open google images and search for cricket, it will display the page with images and if you scroll down only you will come to know the ajax request going and appending the response to the web page,
But it is not waiting till the entire page is loaded.
I must develop my application in the same way.
Any idea is Highly Appreciated and sample code too.
This should work for you, Mr.Chowdary.
You would need something to handle your requests in the backend. Since you did NOT specify whether you used Java or PHP or Python or whatever, I used PHP - its what I know best :D
PSEUDO CODE (loadmore.jsp)
Begin
widget = URL(widget) //the widget id or name
page = URL(page) //the page being retrieved
switch (widget)
{
case "widget1":
data_for_widget1 = paginated_query1(page)
print data_for_widget1
break
case "widget2":
data_for_widget2 = paginated_query2(page)
print data_for_widget2
break
default :
print "Invalid Widget"
break
}
End
PHP Version
<?php
if (isset($_GET['page'])) {
$widget = $_GET['page'];
$page = $_GET['page'];
switch ($widget) {
case "MyWidget1": //dynamic example
$manyManyItems; //A massive array of items
$pages = array_chunk($manyManyItems, 5); //break it up into chunks of 5 items
if( array_key_exists ($pages[$page]) )
for ($i = 0; $i < count($pages[$page]); $i++) { //load those chunks
echo '<div class="item">'.$pages[$page][$i].'</div>';
}
else {
echo "zero"; //code word that tells ajax that there is nothing more to load
}
break;
case "MyWidget2": //manual example
if($page==1) { //loads the first chunck manually
echo '<div class="item">dynamic content 1</div>';
echo '<div class="item">dynamic content 2</div>';
echo '<div class="item">dynamic content 3</div>';
}
elseif($page==2) { //loads the next batch
echo '<div class="item">dynamic content 1</div>';
echo '<div class="item">dynamic content 2</div>';
echo '<div class="item">dynamic content 3</div>';
}
else
echo "zero"; //code word that tells ajax that there is nothing more to load
break;
default:
echo "zero"; //code word that tells ajax that there is nothing more to load
}
}
?>
HTML
Each widget could look like this
<div id="MyWidget1" class="widget" data-widgetPage="0">
<div class="item">default content</div>
<div class="item">another default content</div>
...
<div class="loadmoreajaxloader" style="display:none;"><center>Loading...</center></div>
</div>
Javascript
<script type="text/javascript">
$(".widget").scroll(function()
{
if($(this).scrollTop() == $(this).height() - $(this).height())
{
var nextPage = eval($(this).attr("data-widgetPage") + 1);
$(this).find('.loadmoreajaxloader').show();
$.ajax({
url: "loadmore.php?widget="+$(this).attr("id")+"&page="+nextPage,
success: function(html)
{
if(html != "zero")
{
$(this).append(html);
$(this).('.loadmoreajaxloader').hide();
}else
{
$(this).find('.loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
});
$(this).attr("data-widgetPage", nextPage);
}
});
</script>
Success with the app.
I got to know the following answer suits my requirement from the following site.. Jquery endless scrolling

using AJAX to check for database updates and notify

I need an ajax script to ckeck if there is an entry of data in the database and show notification on the page for each entry .I want the notification to be shown to every user viewing that page .
I tried the following but it is not giving needed output:
main.html
<html>
<head>
<script type='text/javascript' src='ajx.js'></script>
</head>
</html>
pop.php
<?php
try{
$con=mysql_connect("localhost:3306", "root", "") or die(mysql_error()) ;
$q = mysql_query("SELECT `user`.`name`,`user`.`page` FROM `people`.`user` ORDER BY `user`.`index` DESC",$con);
if(!$q)
{
throw new Exception('Uncaught Exception occurred');
}
}
catch(Exception $e)
{
Echo "";
}
$results = mysql_fetch_assoc($q);
echo json_encode($results);
?>
ajx.js
$.ajax({
url: "pop.php",
dataType: "json",
success: function(json){
var dataArray = JSON.decode(json);
dataArray.each(function(entry){
alert(entry.name);
}
}
});
I am not getting result when i load main.html .I think some statement is needed to print the result.
which specific aspect of that script would you like clarification on writing? do you have a specific question in regards to where you might be having problems?
You could use something like this:
PHP File: (get_notifications.php)
$q = /*your query to database*/
$query = mysql_query($q, $dbConnect);
$results = mysql_fetch_assoc($query);
echo json_encode($results);
Javascript File:
$.ajax({
url: "get_notifications.php",
dataType: "json",
success: function(json){
var dataArray = JSON.decode(json);
dataArray.each(function(entry){
alert(entry.valueName);
}
}
});
In the javascript file "valueName" refers to the data key that you would like to output. For example if you "SELECT name FROM people", and you want to output their name it would be entry.name. You can also replace the alert with an append or something to put the data in a div or on the page.
Let me know if you need any further clarification on any of these parts. This should be able to give you a pretty good start. Hope it helps.
Clarification:
The file your page loads should only contain your layout and HTML as well as the script tag to include your js.
Then your php for the ajax call should be in a separate file that is called by the Ajax, not included on the page that is being loaded. Hope that makes sense.
I looked over your code and made a few modifications. This is the exact code I used that worked on my system with a test database that I used: (you will need to tweak it to your system environment)
main.html:
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type='text/javascript' src='ajx.js'></script>
</head>
<body>
Your body content in here...
</body>
</html>
pop.php:
<?php
include __DIR__.'/include/Configurations.php';
include __DIR__.'/include/DatabaseConnect.php';
global $databaseConnection;
try{
$q = mysql_query("SELECT name, page FROM users", $databaseConnection);
if(!$q)
{
throw new Exception('Uncaught Exception occurred');
}
}
catch(Exception $e)
{
Echo "";
}
$results = Array();
$i = 0;
while ($row = mysql_fetch_assoc($q))
{
$results[$i] = $row;
$i++;
}
echo json_encode($results);
?>
ajx.js:
$(document).ready(function(){
$.ajax({
url: "pop.php",
dataType: "json",
success: function(json){
var i;
for(i=0; i<json.length; i++)
{
alert(json[i].name);
}
}
});
});
When you integrate it into your actual project you can just replace the alert() function with whatever logic and output methods you want in order to get the content properly on the page. Let me know how this goes for you or if there is anything else I can help with.

jQuery Ajax Request - Lose Method

I have a page index.php that uses a modal to upload files. After those have uploaded I use the following to update my database and load in the new images to a list.
$('#sortableImages').load('../includes/sortImages.php?edit=' + edit);
Executes:
<script type="text/javascript">
$(document).ready(function(){
$(function() {
$("#sortableImages ul").sortable({
opacity: 0.6, cursor: 'move', update: function() {
var order = $(this).sortable("serialize") + '&action=updateRecordsListings';
$.post("../albumUploader/queries/sort.php", order);
}
});
});
});
</script>
echo "<ul class='revisionList'>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sortImageName = $row['OrgImageName'];
$sortPath = "../data/gallery/" . $getGalleryID . "/images/album/" . $sortImageName;
echo "<li class='sortPhotos' id='recordsArray_{$row['id']}' >";
echo '<img src="'. $sortPath .'"/>';
echo "</li>";
}
echo "</ul>";
The images populate in a div #sortableImages on the index page. However it seems that I lose my method of sortable() from the js file that was originally loaded in the index.php or after the ajax request it's not reading the js. What am I missing here?
Thanks a million.
When you load script from a remote page using ajax, it is important to realize that the ready event has already occured in page you are loading into.
This means that code wrapped in $(function(){}) will fire as soon as it is received. If that code preceeds the html it refers to, it will not find that html, as it doesn't exist yet.
If you move the same code below the html it refers to, it will fire after the html exists and therefore will find it.
EDIT: My answer presumes that all the code shown after "Executes:" in OP is contained in remote page
You have no handler for the result of the sort.php. Invoking this will only load the data into cache.
You need a complete handler function to refresh the data, not to mention add it to the dom. You should clarify your question and make it obvious that those are two different pages.
$.post("../albumUploader/queries/sort.php", order).complete = func...

Iframe or Ajax ?

at the moment I've got a simple bit of code to display messages on a site.
the page includes an iframe that self refreshes every 90 seconds, and the iframe displays the contents of a mysql table limited to the most recent (30) posts.
I've been reading up on ajax and it still confuses me, i've never got it working properly, and would like to know, for a small task like this, is it really worth it ?
<head>
<META HTTP-EQUIV="refresh" CONTENT="90; URL=">
</head>
<body>
<?
$newsarray = array();
$sql = "SELECT * FROM `news` ORDER BY `date` DESC LIMIT 30";
$result = mysql_query($sql);
if(mysql_error()) { print mysql_error(); } else {
while($stuff = mysql_fetch_assoc($result))
{ array_push($newsarray, $stuff); }
foreach($newsarray as $newsstory) { ?>
<div class="newsstory">
<h2><? echo $newsstory['headline']; ?></h2>
<div><? echo $newsstory['story']; ?></div>
<label>By <? echo $newsstory['user']; ?> on <? echo $newsstory['date']; ?></label>
</div>
<? } ?>
</body>
It would be as simple as adding the jQuery library to your exsiting page and adding the following code:
<div id="result"></div>
Manually Fetch Page
<script language="javascript">
function updatestuff() {
$.ajax({
url: 'mypage.php', // The source
cache: false, // Make sure results are not cached
success: function (data) {
$('#result').html(data); // Update data once retrieved
}
});
}
setInterval("updatestuff()",90000); // In Milliseconds
</script>
This would run the function updatestuff() every 90 seconds which would update the <div> with content fetched from mypage.php.
If you want something that automatically updates every 30seconds then definitely Ajax is the way to go.
Some say (myself include) that you'd be insane not to use jQuery to do this.

ajaxComplete/ajaxStop/ajaxSuccess not firing

I appreciate any and all help. I am a beginner with little jQuery/AJAX experience and I have been going crazy trying to figure out why I can't figure this out.
I'm writing a Facebook page application that has the user grant permissions and upload a video to the page. All of this works fine and dandy. This is not so much a Facebook API related issue as it is an ajax issue (at least I think).
Basically, I am trying to gain control of the page IN SOME WAY after the user uploads a video. I am using the [malsup jQuery Form Plugin][1] to have the resulting page (which is a page on Facebook displaying returned JSON values) load in a hidden iframe.
I am able to get ajaxStart to fire, and I've tested this by having it change the background color or print an alert message when I click "Upload". However, when the upload completes (and it does complete successfully), NOTHING ELSE HAPPENS. The returned JSON values load in the hidden iframe and the page sits there. I have tried getting ajaxComplete, ajaxStop and ajaxSuccess to fire, but none of them do for whatever reason.
So overall, here is what I am trying to accomplish:
- I want to redirect the user or make some hidden content appear after the file upload completes. I don't even care if there's errors. I just need SOMETHING to happen.
- I am using the jQuery Form Plugin because I am not unfortunately not advanced enough to figure out how to use that value and do something with it, but if anyone can steer me in the right direction, that would be appreciated.
And finally, here is my code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
iframeTarget: '#output2',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
// bind form using 'ajaxForm'
$('#theform').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);
}
</script>
<script type="text/javascript">
jQuery().ready(function(){
$('body').ajaxStart(function() {
$(this).css("background-color","red");
});
$('body').ajaxSend(function() {
$(this).css("background-color","blue");
});
$('body').ajaxComplete(function() {
$(this).css("background-color","green");
});
$('body').ajaxStop(function() {
$(this).css("background-color","purple");
});
});
</script>
</head>
<body>
<?php
$app_id = "xxxxxxx";
$app_secret = "xxxxx";
$my_url = "xxxxxx";
$video_title = "xxxxxxxxx";
$video_desc = "xxxxxxxxx";
$page_id = "xxxxxxxx";
$code = $_REQUEST["code"];
if(empty($code)) {
// Get permission from the user to publish to their page.
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&display=popup&scope=email,publish_stream,manage_pages";
$current_url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($current_url != $dialog_url)
{
echo('<script>window.location ="' . $dialog_url . '";</script>');
}
} else {
// Get access token for the user, so we can GET /me/accounts
$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$access_token = file_get_contents($token_url);
$accounts_url = "https://graph.facebook.com/me/accounts?" . $access_token;
$response = file_get_contents($accounts_url);
// Parse the return value and get the array of accounts we have
// access to. This is returned in the data[] array.
$resp_obj = json_decode($response,true);
$accounts = $resp_obj['data'];
// Find the access token for the page to which we want to post the video.
foreach($accounts as $account) {
if($account['id'] == $page_id) {
$access_token = $account['access_token'];
break;
}
}
// Using the page access token from above, create the POST action
// that our form will use to upload the video.
$post_url = "https://graph-video.facebook.com/" . $page_id . "/videos?"
. "title=" . $video_title. "&description=" . $video_desc
. "&access_token=". $access_token;
// Create a simple form
echo '<form action=" '.$post_url.' " method="POST" enctype="multipart/form-data" id="theform">';
echo 'Please choose a file:';
echo '<input name="file" type="file">';
echo '<input type="submit" value="Upload" id="button-upload" />';
echo '</form>';
}
?>
<iframe id="output2" name="output2"></iframe>
</body></html>
Thank you for your help!!
It seams you are getting an Ajax Error. I don't see any error handler in your code. Could you try to add an error handler as follows
<script>
$(document).ready(function(){
$(document).ajaxError(function(e, jqxhr, settings, exception) {
alert(exception);
})
})
</script>
I have played around with file uploads, and there are a complicated beast because of all the security that browsers have for protecting users file systems and whatnot.
On to your problem, I think that there is a good chance that your AjaxForm jQuery plugin doesn't connect properly to the global Ajax state for Jquery. Even if it did, I would say that tapping into the global Ajax state is a bad design. If you add any other ajax requests to this page, then your ajaxComplete, ajaxStop, etc. functions are going to start getting called.
Your better approach is to use the callbacks provided by the AjaxForm plugin. Lets focus on this first part of your code.
Does this work?
success: showResponse // post-submit callback
...
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);
}
If so, could you replace this:
$('body').ajaxComplete(function() {
$(this).css("background-color","green");
});
With this:
function showResponse(responseText, statusText, xhr, $form) {
$(this).css("background-color","green");
}
I believe that using the success: callback is the intended use of the AjaxForm plugin.
The jquery ajaxSend or ajaxStart throws some kind of an error and the document does not execute ajaxComplete. I tried to fix the bug for quite a while and was only able to find a workaround:
function hideAjaxIndicator() {
$('#ajax-indicator').hide();
}
$(document).ready(function () {
setTimeout(hideAjaxIndicator, 1000);
});
You can add this to .js file.

Resources