Alternative to AJAX setTimeout? - javascript

I have a script that uses ajax to retrieve PHP data for video files on my server (godaddy shared hosting), and then play the video file on my php page if it is the highest ranked video, like so:
<script id="source" language="javascript" type="text/javascript">
$(function refreshscreen ()
{
$.ajax({
url: 'screen.php',
data: "",
pass to api.php
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
var votes = data[2];
var video = data[3];
var image = data[4];
$('.screen').hide(); $("#video"+id+"").show();
var whichvideo = "thevideo" + id;
var videoplay = document.getElementById(whichvideo);
var killvideo = document.getElementsByClassName('videobg');
var allvideos = document.getElementsByClassName("videobg");
for(var x=0; x < allvideos.length; x++)
{
var allvideosid = document.getElementById(allvideos[x]);
if ($(allvideos[x]).attr("id") == whichvideo) {
allvideos[x].play();
} else {
allvideos[x].pause();
}
}
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(refreshscreen, 5000);
}
});
});
And then the screen.php referenced above:
<?php
$host = "localhost";
$user = "myuserhere";
$pass = "mypasshere";
$databaseName = "mydbnamehere";
$tableName = "mytablenamehere";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName ORDER BY votes DESC");
$array = mysql_fetch_row($result);
echo json_encode($array);
?>
This all works fine, and the video switches as it should when a new higher ranked video is voted in, however, periodically, the video will freeze when playing, completely at random. My guess is that we are overloading the server with the setTimeout function of the ajax script, so I am wondering if there is a way I can clean up this script to avoid the freezing, or an alternative method.
Thanks in advance.

I've cleaned up the code:
var currentID = -1;
function refreshscreen() {
$.getJSON('screen.php', data => {
var topID = data[0];
// Schedule the next request
setTimeout(refreshscreen, 5000);
if (topID === currentID) return; // top rated video hasn't changed
$('.screen').hide();
$("#video" + topID).show();
var pauseID = "thevideo" + currentID;
var playID = "thevideo" + topID;
$(".videobg").each(function() {
if (this.id === pauseID) this.pause();
if (this.id === playID) this.play();
});
currentID = topID;
});
}
$(document).ready(function () {
refreshscreen();
});
The biggest change is keeping track of the currently playing video and exiting right away if it hasn't changed. Other than that I got rid of all the unused variables and used jQuery throughout. This should be much easier to debug at the least and might fix the error to boot.

Related

When I'm trying to retrieve a value from php file to javascript

I am trying to get a value from php file ,php file retrieve data from ORACLE DATABASE, to a script js this is the php file :
<?php
include("../../config.php");
if(isset($_POST['songId'])) {
$songId = $_POST['songId'];
$query = oci_parse($con, "SELECT s.song_path, s.song_id, s.TITLE, r.Artist_Name, a.artworkpath FROM songs s, artists r, albums a WHERE s.artist_id = r.artist_id AND a.album_id = s.album_id AND song_id='$songId'");
oci_execute($query);
$resultArray = oci_fetch_array($query);
echo json_encode($resultArray,JSON_FORCE_OBJECT);
}
?>
it works and successfully retrieve data from the tables.
The script that uses data:
<?php
$songQuery = oci_parse($con, "SELECT song_id from songs order by dbms_random.value");
oci_execute($songQuery);
$resultArray = array();
while(($row = oci_fetch_array($songQuery, OCI_BOTH)) != false) {
array_push($resultArray, $row['SONG_ID']);
}
$jsonArray = json_encode($resultArray, JSON_FORCE_OBJECT);
?>
<script>
$(document).ready(function() {
currentPlaylist = <?php echo $jsonArray; ?>;
audioElement = new Audio();
setTrack(currentPlaylist[0], currentPlaylist, false);
});
function setTrack(trackId, newPlaylist, play) {
$.post("includes/handlers/ajax/getSongJson.php", { songId: trackId }, function(data) {
var track = JSON.parse(data);
$(".trackName span").text(track.TITLE);
$(".artistName span").text(track.ARTIST_NAME);
$(".albumLink img").attr("src", track.ARTWORKPATH);
audioElement.setTrack(track.SONG_PATH);
audioElement.audio.play();
});
if(play == true) {
audioElement.audio.play();
}
}
function playSong() {
if(audioElement.audio.currentTime == 0) {
$.post("includes/handlers/ajax/updatePlays.php", { songId: audioElement.audio.currentlyPlaying.SONG_ID});
}
$(".controlButton.play").hide();
$(".controlButton.pause").show();
audioElement.audio.play();}
function pauseSong() {
$(".controlButton.play").show();
$(".controlButton.pause").hide();
audioElement.audio.pause();
}
</script>
All the functions work well except
(songId: audioElement.audio.currentlyPlaying.SONG_ID)
It don't recognize SONG_ID which is a column from database retrieved in the php file (ajax/getSongJson.php)
PS: the (ajax/updatePlays.php) file is a php file that is for Updating DATA (PLAYS) when the user use playSong function when the current time = 0 so it increment the PLAY colomn in the database by 1
The update php file
<?php
include("../../config.php");
if(isset($_POST['songId'])) {
$songId = $_POST['songId'];
$query = OCI_parse($con, "UPDATE songs SET plays = plays + 1 WHERE song_id='$songId'");
oci_execute($query);
}
?>
This is the script file when I created a Audio Class, used in the script:
var currentPlaylist = [];
var audioElement;
function Audio() {
this.currentlyPlaying;
this.audio = document.createElement('audio');
this.setTrack = function(track) {
this.currentlyPlaying = track;
this.audio.src = track.SONG_PATH;
}
this.play = function() {
this.play();
}
this.pause = function() {
this.pause();
}
}
The error says :
Uncaught TypeError: Cannot read property 'SONG_ID' of undefined
at playSong ((index):140)
at HTMLButtonElement.onclick

Cannot get value from PHP variable

I am using JQuery Ajax (and I am sure that things have changed since the last time I used it) but I am having trouble pulling the information from the PHP variable. Basically I am getting the IP address and logging how long it took that IP to load the page fully and then display it.
Here is my code...
getIP.php
<?php
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip = $_SERVER['REMOTE_ADDR'];
}
echo json_encode(array('ip' => $ip));
?>
Event listener that calls it
var IPAddresses = [];
//Anonymous functions - used for quality control and logging
(function() { //Used to test how long it took for a user to connect - uses a php script with it
window.addEventListener("load", function() {
$.ajax({
url: '../php/getIP.php',
type: 'POST',
success: function(result)
{
setTimeout(function alertUser(){IPAddresses.push(result.ip);}, 40);
}
});
}, false);
})();
(function() {
window.addEventListener("load", function() {
setTimeout(function() {
for (var i = 0; i < IPAddresses.length; i++)
{
var timing = performance.timing;
console.log(IPAddresses[i] + " " + timing.loadEventEnd - timing.responseEnd);
}
}, 0);
}, false);
})();
EDIT
Now I don't get errors but it does not seem to print the IP address or push it into the array at all. I am basically trying to get it to [ip] [loadtime] It gives a NaN error
Your output is a string:
echo $ip; //Just to check if it worked - it shows the IP
^---e.g. 127.0.0.1
and then you try to treat it as an array:
setTimeout(function alertUser(){alert(result['ip']);}, 40);
^^^^^^
Since it's not an array, this won't work. try just alert(result).
try to use "json_encode"
echo json_encode(array('ip' => $ip));
and in ajax
success: function(result)
{
setTimeout(function alertUser(){alert(result.ip);}, 40);
}

AJAX - reload page if JSON has changed

I cannot find a suitable way to achieve this:
I have this script
<script type="text/javascript">
function updateSpots() {
$.ajax({
url : '/epark/api/spots/last',
dataType : 'text',
success : function(data) {
var json = $.parseJSON(data);
var currentMessage = json.dateTime;
var idPosto = json.idPosto;
console.log('current '+currentMessage);
console.log('old '+oldMessage);
if(currentMessage != oldMessage){
setTimeout(function(){location.reload();}, 5000);
$('#idPosto').toggle("higlight");
}
oldMessage = currentMessage;
}
});
}
var intervalId = 0;
intervalId = setInterval(updateSpots, 3000);
var oldMessage ="";
</script>
This should check every 3 seconds if the dateTimehas changed on the JSON.
The problem is that I cannot get to go further first step. I mean, when the page loads, oldMessageempty so the if condition is not satisfied. If I could "jump" this first iteration, then everything would go well...
var oldMessage = false;
//...
if (oldMessage && oldMessage !== currentMessage) {
//...

Getting data from MySql table with no refresh

I have a code that counts down and when the countdown reaches 0 I want it to grab data from a MySql table and present it on the page without reloading.
I know my countdown works, but it is when I add the code to get the data from the PHP page it stops working. I know my PHP page works and grabs the correct data and presents it.
Here is the code I am currently using.
Any ideas?
<div id="countmesg"></div>
<div id="checking"></div>
<div id="name-data"></div>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var delay = 10;
function countdown() {
setTimeout(countdown, 1000);
$('#countmesg').html("Auction ends in " + delay + " seconds.");
delay--;
if (delay < 0) {
$('#countmesg').html("Auction ended.");
delay = 0;
}
}
countdown();
});
</script>
<script type="text/javascript">
$(document).ready(function () {
var delay = 2;
function countdown() {
setTimeout(countdown, 100);
$('#checking').html("Checking in " + delay + " seconds.");
delay--;
if (delay < 0) {
$('#checking').html("Checking again....");
var name = 'tom';
$.post('cdown.php', {
name: name
}, function (data) {
$('div#name-data').text(data);
};
delay = 2;
}
}
countdown();
});
</script>
The 3 lines that are supposed to be grabbing the PHP file are:
var name = 'tom';
$.post('cdown.php', {name: name}, function(data) {
$('div#name-data').text(data);
PHP Code:
<?php
require 'connect.php';
$name = 'tom';
$query = mysql_query("
SELECT `users`.`age`
FROM `users`
WHERE `users`.`name` = '" . mysql_real_escape_string(trim($name)) . "'"
);
echo (mysql_num_rows($query) !== 0) ? mysql_result($query, 0, 'age') : 'Name not found';
?>
use $.ajax instead of $.post
$.ajax(//url to php//).done(
function (data) { //data is from the php
//do stuff
}
)
Code you provided (3 lines):
var name = 'tom';
$.post('cdown.php', {name: name}, function(data) {
$('div#name-data').text(data);
It seems like you have an incomplete $.post(...) statement. If you check your Console you should see some Exceptions. What are they?
Update your 3 lines to this:
var name = 'tom';
$.post('cdown.php', {name: name}, function(data) {
$('div#name-data').html(data);
});

Post dynamic twitter updates

I currently have some script on my page that parses title/artist information from my online radio station. I am displaying it as plain text in html by using
<span id="song_title"></span>
How can I take this dynamic information that is going into the span id and use it for a "post to twitter" link so listeners can share the current song title on Twitter?
I did some research and found a few variations on posting to twitter, but I had no luck with posting this dynamic text.
Here's the script code:
<!-- Begin Now Playing Script -->
<script>
(function () {
// we need a JSON parser, if it does not exist, load it
if (typeof JSON == "undefined") {
var s = document.createElement("script");
// json2.js retrieved from https://github.com/douglascrockford/JSON-js
s.src = "json2.js";
document.getElementsByTagName("head").appendChild(s);
}
})();
var song_ends = 0;
function update_song () {
if ((new Date).getTime() < song_ends) {
// use cached result as the song has not ended yet
return;
}
var req = new XMLHttpRequest();
// IE compatbility:
var textContent = 'textContent' in document ? 'textContent' : 'innerText';
req.onreadystatechange = function () {
if (req.readyState == 4) {
var song = JSON.parse(req.responseText);
if (song.title) {
var img = document.getElementById("song_image");
if(song.image.src){
img.alt = song.image.alt;
img.src = song.image.src;
img.width = 100;
img.height = 100;
}else{
img.src="images/default_art.png";
img.width = 100;
img.height = 100;
}
document.getElementById("song_title")[textContent] = song.title ;
document.getElementById("song_artist")[textContent] = song.artist;
document.getElementById("song_next")[textContent] = song.next ;
// store the end date in javascript date format
song_ends = (new Date).getTime() + song.wait_ms;
}
}
};
req.open('get', 'php/PlayingNow.php', true);
req.send(null);
}
// poll for changes every 20 seconds
setInterval(update_song, 20000);
// and update the song information
update_song();
</script>
<!-- End Now Playing Script -->
I want to be able to post it to Twitter like this: Currently listening to (song_title) by (song_artist)
Here is the code for the PHP file referenced in the script above:
<?php // filename: PlayingNow.php
$json = null;
$cache = 'song.json';
// if there is no usuable cache
if (!$json) {
// retrieve the contents of the URL
$ch = curl_init('http://bigcountry.streamon.fm/card');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
curl_close($ch);
$json = json_decode($res);
// if the title exists, assume the result to be valid
if ($json && $json->title) {
// cache it
$fp = fopen('song.json', 'w');
fwrite($fp, $res);
fclose($fp);
} else {
$json = null;
}
}
if ($json) {
$info = array();
// contains the time in milliseconds
$info['wait_ms'] = $json->interval->ends_at - 1000 * microtime(true);
$info['title'] = $json->title ;
$info['artist'] = $json->artist;
$info['album'] = $json->album ;
$info['next'] = $json->next_song;
$info['image'] = $json->album_art;
// display a JSON response for the HTML page
echo json_encode($info);
}
?>
The "right" way to do this is to use Twitter's Web Intents, which is designed specifically for this scenario. Take a look at the "Tweet or Reply to a Tweet" section. In practice you'll just include the Web Intents script (http://platform.twitter.com/widgets.js) on your page, create a link, and set its href, e.g.:
var link = document.createElement('a');
link.innerHTML = "Link Text";
link.href = 'http://twitter.com/intent/tweet?text=Currently listening to "' + songTitle + '" by ' + songArtist;
var parentElement = document.getElementById('SOME_ELEMENTS_ID');
parentElement.appendChild(link);
You can add the url parameter if you also want the tweet to include your site's URL.

Categories

Resources