Real time database changes with Ajax - php

I'm building a website that prints the content in it's Mysql database to the page for the user to see. The database's content is going to be constantly added to, and I want to show those changes in real time on the page without the user having to reload. I'm using PHP to echo the contents of the database to the page right now and it works great, it's just that to see any new changes, the page has to be reloaded. So my question is, how do I make the page update itself in real time? I'm guessing this is going to involve Ajax but I'm rather new to javascript...
Would you guys mind pointing me in the right direction?
Here's what my database looks like:
id author body
----------------------------------------
1 jim sample content
2 bob more content
3 fred some more!
I'm using the following PHP code to print the above data to the web page:
$query = mysql_query("SELECT * FROM log order by id desc") or die(mysql_error());
while($row = mysql_fetch_array($query)) :
echo $row['author'];
echo $row['body'];
endwhile;
Thanks!

If you want to use the jQuery library, you can use this example I wrote.
Its pretty daunting at first, but ill explain the best I can.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var shownIds = new Array();
setInterval(function(){
$.get("test2.php", function(data){
data = $.parseJSON(data);
for(i = 0; i < data.length; i++){
if($.inArray(data[i]["id"], shownIds) == -1){
$("#log").append("id: " + data[i]["id"] + "<br />");
shownIds.push(data[i]["id"]);
}
}
});
}, 2000);
});
</script>
</head>
<body>
<div id="log">
</div>
</body>
</html>
test2.php
<?php
$result[0]["id"] = "id1";
$result[1]["id"] = "id2";
echo json_encode($result);
?>
So basically, it checks if the document is ready and everything is loaded.
After that is makes a new array called shownIds. This variable will keep the id (primary index from your sql table) to make sure it doesn't show the same data twice.
SetInterval just makes it call that function every two seconds.
$.get this function gets the page source of test2.php which has the json data.
It parses it with $.parseJSON and then loops through each.
To make sure that no two rows are shown twice, it checks with $.inArray to see if the id is already in the shownIds array.
If it isnt, it appends the data (just id for now) onto the only div.
Then it pushes the id into the shownIds array so that it doesnt get shown again.
test2.php makes an array. Sets the ids, and echos the data in the json format (not needed but keeps it organized)

Use jquery ajax http://api.jquery.com/jQuery.ajax/ its simple and easy and call ajax method after every second...so that after every second u will get new data.

Related

Auto refresh with jquery gets echo "test" but it does not get data from mysql query.. How can i fix it?

i will try to explain this as clear as possible.. I have a auto refresh script. This script auto refresh a div. I want to call a php file in this div which has mysql in it.. When i try to call that php file only the manual echos display. It does not display anything from database.. If i check the php file i see that it works on its own.. How can i fix this? Thanks.
My script:
<script>
$(document).ready(function() {
$("#feeds").load("sagmenu.php");
var refreshId = setInterval(function() {
$("#feeds").load("sagmenu.php");
}, 2000);
$.ajaxSetup({ cache: false });
});
</script>
<div id='feeds'></div>
My PHP:
<?php
$feeddatagetsq = mysql_query("SELECT * FROM feed ORDER BY id DESC");
$feeddataget = mysql_fetch_array($feeddatagetsq);
echo $feeddataget['id']; //this does not display.. I want this to display..
echo "test"; //this displays..
?>
load() function loads only the html part of the file. So if you want datas from database just echo it
My friend, the $feeddataget['id'] is not a single record. It is returning more than 1 rows (Obviously only with ID column). So according to me, you cannot send this simply by echoing into PHP file.
Use this instead:
echo json_encode($feeddataget['id']);
and in JS File, use this:
var foo = $.parseJSON(responseText); (If you wanna implement it through JQuery)
and, var foo = JSON.parse(responseText); (If you want to do it without JQuery)
Now, foo is a array containing all the IDs that you've returned from PHP File.

How can I re-parse an XML document at set intervals?

I have built an area on my client's website that displays a song that is currently playing, as parsed from an XML file via PHP. However, my client wants the song to auto-refresh itself instead of him having to manually refresh the page.
I played around with parsing the file using jQuery.get() and also .ajax(), but because of the way the XML file is structured, it seems as though I can only get the artist and the name squashed into one string, or when I try to be specific it only returns [object Object].
I haven't even tried to tackle having the song's length be calculated and then refresh the feed based on that length. I may not seeing as this is apparently such an issue for me.
Any help or general guidance would be greatly appreciated.
Example working PHP code (obviously, non-AJAX):
<?php
$recentlyPlayed = simplexml_load_file('http://publicapi.streamtheworld.com/public/nowplaying?mountName=ABCDFM&numberToFetch=1&eventType=track');
$trackTitle = $recentlyPlayed->{'nowplaying-info'}[0]->property[1];
$trackArtist = $recentlyPlayed->{'nowplaying-info'}[0]->property[0];
echo "<h6>" . $trackArtist . "<span class=\"song-title\">" . $trackTitle . "</span></h6>";
?>
I've tried several different things to get this to work, but it seems the initial obstacle is trying to reference the data in the XML file using the attributes, rather than the node-names. The nodes are all named the same, and it's the attributes that differentiate them. So, as such this code will render correctly, unless the artist/song title are blank, then it renders the third field which is sort of cryptically-named "cue_time_start".
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval("songPull()",1000);
});
function songPull() {
$.get(
"http://publicapi.streamtheworld.com/public/nowplaying?mountName=ABCDFM&numberToFetch=1&eventType=track",
"xml",
function(data) {
$(data).find("nowplaying-info").each(function(){
var artist = $(this).find("property").eq(0).text();
var title = $(this).find("property").eq(1).text();
$('body').html("<h1>" + artist + "<small class=\"song-title\">" + title + "</small></h1>");
console.log (artist);
console.log (title);
});
}
);
}
</script>
<body>
</body>
Any guidance, advice or examples of best practices when trying to do this sort of thing would be so very greatly appreciated.
I'm not exactly sure if this is what you want, but you could simply use attribute selectors to extract the data you want out of your XML document.
http://jsfiddle.net/P8dc6/
$.get("http://publicapi.streamtheworld.com/public/nowplaying?mountName=KROXFM&numberToFetch=1&eventType=track",
"xml",
function(data) {
var $nowPlaying = $(data).find('nowplaying-info');
console.log($nowPlaying.find('[name=track_artist_name]').text());
console.log($nowPlaying.find('[name=cue_title]').text());
}
);
Also, never pass a string to setInterval or setTimeout, you can just pass the function reference directly:
setInterval(songPull ,1000);

How to use ajax to load a row of youtube videos, then go onto the next row

I know it is a bit vague of a question, but I have a webpage that is just a wall of youtube videos. I have the videos separated into divs called rows and there are about 3, maybe 4 videos per row. In my script I am using a jQuery function to create SWFobjects for each video and I have some simple php creating each row of videos inside a wordpress loop.
My question is; is there a way to load a row, 3 or 4 videos, and after that completes to continue the wordpress loop to the next row and so on. I believe my answer lies with ajax but I have no experience with it. I know jquery has some great tools and methods to use to help with ajax, but I dont know where to start and what I am even looking for.
Literally all that webpage does is loop through this bit of code below, this is reduced by a bit. But it runs this function 3 times then goes to the next row and does it 3 more times until wordpress says there are no more posts in that category. How can i get ajax to do one row at a time and not 'all at once'.
<script type="text/javascript">
var youtubeID = '<?php echo $urlYoutube; //pass the php var to js var?>';
var divID = '<?php echo $divName;?>';
getVideoSML(youtubeID, divID);
</script>
A nice and generous 'push' in the right direction would be greatly appreciated, if not an answer.
<script type="text/javascript">
var youtubeID = '<?php echo $urlYoutube; //pass the php var to js var?>';
var divID = '<?php echo $divName;?>';
getVideoSML(youtubeID, divID);
</script>
This is not how you pass data from PHP to Javascript. You should read something about JSON and Ajax. There are a lot of tutorials on the internet, and everything is made even too easy by jQuery (take a look at that too).
I don't think I got the question but I think you are having a problem understanding loops. AJAX is just a way of load a page dinamically and asynchronous. If I got it right you should use 2 loops:
$vps = 4; // number of videos per row
while (/* there are rows to be printed */) {
for ($i = 0; $i < $vpr; $i++) {
/* print the video */
}
}

pass variable from input box to php

Hi all i know this question has been posted but being a total noob i couldnt get what answers meant. Please help. I want to pass inputbox value dynamically to a php variable . i am using javascript here please suggest if there's another way without using form submission , _GET or _POST. i want it done dynamically without any submission.
function showHint(str)
{
document.getElementById('TK').innerHTML = str;
var str = str
}
</script>
<html>
<head>Inputbox</head>
<title>TEST PAGE </TITLE>
<body>
<input type='text' id='TK' name='TK' onkeyup='showHint(this.value)'/>
<?php
$str = var str ;
echo "<a href = 'newpage.php?S=$str'/>" ; ?>
</body>
</html>
No. You can't. PHP is NOT a dynamic language, and it does NOT run client side. PHP runs once, and only once, and that's when the page is loaded. It runs its script and it stops. What you can do is get javascript to do an AJAX call. AJAX is basically a way of passing information to another page and getting the data, all in JavaScript. Do some research on it, but in short, you can't make PHP run once it's already been run
<script type="text/javascript" >
function process(){
var field1 = 'whatever';
var field2 = 'more whatever';
$.post("go.php",{field:field1,bext_field:field2},function(result){
alert(result);
});
};
</script>
This will alert out whatever you ECHO from GO.PHP.
You will also need a handler like:
onClick="process();"
on a div, button, image, just about anything you want to "initiate" your post
I would imagine the other answers you found probably would have said the following:
PHP executes before the user has a chance to see the page.
JS let you control what happens after.
Therefore, your problem is that you are trying to use PHP to do something it simply cannot.
Use those points to help guide your decisions when developing your applications. In this case, if you're trying to build a link based on what a user types in a box, your solution to the problem isn't PHP at all (the page is already loaded, you're too late!) -- your solution is JS.
Think about it like this:
/*
assumes you already have an <a> on the page. if not, you'll
have to create a new <a> element dynamically. (google "mdn createElement"
for help)
*/
function showHint (str) {
document.getElementById('TK').innerHTML = str;
var link = document.getElementById('your-a-link');
link.setAttribute('href', 'newpage.php?S=' + str);
}

Load div from another page within an AJAX loaded page

I'm using jQuery address to enable loading specific content from other pages
and to change the URL in the address bar.
I'm working on a little Social Network alike website, so I'm reading out the IDs
of the posts table of my MySQL database via PHP. I want to use the possibilities of jQuery and AJAX to read everything out dynamically.
I found out, that I have to use live() (which turned out to be old), delegate() (which
also turned out to be old in 1.7.1) or on() (which turns out to be the best possibility
to make events work inside of dynamically loaded content via jQuery + AJAX).
I also read somewhere, that I can't use load() or get() to load new content from another
page inside of an already loaded content, because it doesn't "bubble" (I don't even know
what that means).
What do I have to do to load new content within an AJAX loaded page?
Here's a snippet I tried to work with (included on the loaded page):
<?php
if(exist('`posts`')) {
$load = mysql_query('SELECT `id` FROM `posts` ORDER BY `id` DESC LIMIT 10');
while($row = mysql_fetch_object($load)) {
?>
<script type="text/javascript">
$('body').on('body', 'load', function() {
$.get('getpost.php', { pid: <?= $row->id ?> }, function (data) {
$('#posts').html($('#post_<?= $row->id ?>', data).html()).show();
});
$('#posts').off('load');
});
</script>
<?php
}
}
else {
?>
<div align="center">No posts yet.</div>
<?php
}
?>
getpost.php is my file from which I can get the div_$row->id so that it appears on the start page.
PLUS (Just adding for your knowledge) I want the content to load the content without
a mouseover, click or blur event.
Thanks.
You want to use ".live()" if you want a particular event mapping to be applied dynamically to any new DOM elements which match its selector. Alternatively, you can attach the behavior to each chunk of content loaded.
Write and develop your ajax load independently of your DB lookup to make things simpler. The following snippet triggers another ajax call after each element loads.
<?php
$id = 'div'.mt_rand();
$counter = isset($_REQUEST['counter']) ? $_REQUEST['counter'] : 0;
$next = $counter + 1;
echo <<<END
<div id="{$id}">{$counter}
<script>
$(function() {
$.ajax('/url?counter={$next}', function(html) {
$(html).appendTo($('#{$id}').parent()); // or whatever your favorite method is for adding a sibling
});
});
</script>
</div>
END;
?>
Am I the only one who thinks that this approach is completely wrong? You're making an ajax request for each post, this could end up in making way too much requests, heavily slowing down the loading time. I can't see any reason why you don't want to directly write the posts' HTML inside the PHP while loop.

Categories