Showing a 'Now Playing' in HTML and PHP - javascript

I have been trying to use some PHP and HTML code (with a bit of js) to create a 'now playing' spotify viewer for my website. I just cannot get it working. I have tried all the possibilities such as renaming files, changing the HTML and PHP and JS versions but nothing seems to work. Below is my HTML code (js) and PHP code.
<script src="jquery-1.11.0.min.js"></script>
<!--Begin Spotify Scrobble-->
<SCRIPT TYPE="text/javascript">function get_spotify() {
$.ajax({
type: 'POST',
url: '/public_html/Spotify.php',
data: { request: 'true' },
success: function(reply) {
$('.now-playing').html("<p>" + reply + "</p>");
}
});
}
</script>
<!--End Spotify Scrobble-->
PHP
?php
// Account & API Account Information
$user = "USERNAME"; // <---- Your username goes here
$key = "KEY"; //<-- Your API key goes here
+
// The URL of the request to API Service
$url = "http://ws.audioscrobbler.com/2.0/? method=user.getrecenttracks&user=USERNAME&api_key=APIKEY&forma t=json";
+
// Enable Shortening
$short_titles = false;
+
// Setup cURL for request
$ch = curl_init( $url );
-// Options for cURL
$options = array(
CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $options);
-// Execute cURL and save return to $json
+
+// Execute cURL
$json = curl_exec($ch);
-// Close the connection
curl_close($ch);
-// Decode JSON response to array.
$data = json_decode($json,true);
+
// Get only the latest track information
$last = $data['recenttracks']['track'][0];
+
// Is now playing attribute present?
if (isset($last['#attr']['nowplaying'])) {
- // Echo now playing information.
+
$output = "I am currently listening to " . $last['name'] . ' by ' . $last['artist']['#text'] . " on Spotify.";
+
if ($short_titles) {
$output = sTrim($output);
}
+
echo trim($output);
} else {
- // Collect info on when this was last played and get the current UNIX time.
$played = $last['date']['uts']; $now = time();
- // Get the difference
$diff = abs($now - $played);
- // format hours
+
+ // Time formatting
$hours = intval(intval($diff) / 3600);
- // format minutes
$minutes = intval(($diff / 60) % 60);
- // IF hours is empty(equal to zero)
+
+ // String formatting based on time
if (!empty($hours)) {
- if ($hours > 24) // Is it more than 1 day?
+ if ($hours > 24)
$time = "over a day ago";
else
$time = $hours . " hours and " . $minutes . " minutes ago";
} else
$time = $minutes . " minutes ago";
+
$output = "I last listened to " . $last['name'] . ' by ' . $last['artist'] ['#text'] . " $time on Spotify";
+
if ($short_titles) {
$output = sTrim($output);
}
+
echo trim($output);
}
+
exit();
function sTrim($output) {

Related

PHP and jquery countdown

I just got a tutorial that integrate PHP date function and jQuery.
i want to customize the script so on specific time reach its redirect to another page.
i tried to do my self but its not working correctly. I have included the tutorial link here.
Tutorial LInk
PHP code to fetch date from server
<?php
date_default_timezone_set('GMT');
$currentTime = date('H:i:s');
$currentDay = date('w');
$delTimeStart = '00:00:00';
$delTimeEnd = '14:30:00';
if ($currentTime >= $delTimeStart && $currentTime < $delTimeEnd && $currentDay > 0 && $currentDay < 6){
$css = 'display: block;';
} else {
$css = 'display: none;';
}
?>
JS script
<script type="text/javascript">
$('#countdowntimer').countdown('<?php $date = strtotime("+1 day"); echo date('Y/m/d', $date); ?> 14:30:00').on('update.countdown', function(event) {
var $this = $(this).html(event.strftime(''
+ '%H Hours '
+ '%M Minutes '
+ '%S Seconds'
));
});
</script>
Try this - gleaned from the source:
FIDDLE
$('#countdowntimer').countdown('<?php $date = strtotime("+1 day"); echo date('Y/m/d', $date); ?> 14:30:00')
.on('update.countdown', function(event) {
$(this).html(event.strftime(''
+ '%H Hours '
+ '%M Minutes '
+ '%S Seconds'
));
})
.on('finish.countdown', function(event) {
location.replace("someurl");
});

Javascript clock with server time PHP [duplicate]

This question already has answers here:
javascript clock with server time [duplicate]
(4 answers)
Closed 8 years ago.
I struggling with server time. I need timer on my website (count every second) but not client side time but server. But my script operating only with client time:
<script>
setInterval(function() {
var d = new Date();
$('#timer').text((d.getHours() +':' + d.getMinutes() + ':' + d.getSeconds() ));
}, 1000);
</script>
<label id="timer"></label>
Script above work fine.
How I can integrate server time and update very one second?
Get the date from the server, convert it to a javascript date, then increment it yourself.
<?php $today = getdate(); ?>
<script>
var d = new Date(Date.UTC(<?php echo $today['year'].",".$today['mon'].",".$today['mday'].",".$today['hours'].",".$today['minutes'].",".$today['seconds']; ?>));
setInterval(function() {
d.setSeconds(d.getSeconds() + 1);
$('#timer').text((d.getHours() +':' + d.getMinutes() + ':' + d.getSeconds() ));
}, 1000);
</script>
<label id="timer"></label>
EDIT: JSFiddle with example PHP echoed in.
I worked on a code for count down using the server time . You can use something similar to this for your code
<?php
$now = date('d-m-Y');
$end= "01-01-2013"
$date = strtotime($end) - strtotime($now);
$days = date('d', $date);
$monthes= date('m', $date);
$years= date('Y', $date);
?>
<script>
var days = "<?= $days ?>";
var monthes= "<?= $monthes?>";
var years= "<?= $years?>";
document.getElementById('countdown').innerHTML = days+ ' days';
document.getElementById('countdown').innerHTML += monthes+ ' monthes';
document.getElementById('countdown').innerHTML += years+ ' years';
</script>

$.getJSON always failing

Apologies if this has been answered before but I couldn't find what I was looking for. So, I use $.getJSON to send some variables to a php file. The file returns success as true but for some reason always triggers the .fail function.
The weird thing is, it all works fine on my laptop, just not on the computer at university. Connection to the database is fine, like I said everything works and it returns all the correct data but doesn't trigger the success function.
JQuery:
function request_user_review() {
$.getJSON("user_review_list.php", success_user_review).fail(fail_user_review);
}
function success_user_review(response) {
if (response.success) {
var user_review_list = "";
$("#user_reviews .review_cafe").remove();
$("#user_reviews .review").remove();
$("#user_reviews .rating").remove();
$("#user_reviews .review_choice").remove();
for (var i = 0; i < response.rows.length; i++) {
var review_cafe = '<tr id="row_' + response.rows[i].id + '"><td class="review_cafe">'
+ response.rows[i].cafe + '</td>';
var review = '<td class="review">'
+ response.rows[i].review + '</br>Review left: ' + response.rows[i].date + '</td>';
var rating = '<td class="rating">'
+ response.rows[i].rating + '/5</td>';
var review_choice = '<input type="hidden" class="cafe_id" value="' + response.rows[i].cafe_id + '" /><td class="review_choice"><button onclick="request_edit(this.id)" id="edit_' + response.rows[i].id + '" class="btn_edit">Edit</button><button onclick="request_delete_review(this.id)" id="delete_' + response.rows[i].id + '" class="btn_delete">Delete</button></td></tr>';
user_review_list += review_cafe + review + rating + review_choice;
}
$("#user_reviews").html(user_review_list).trigger("create").trigger("refresh");
} else {
$("#review_message").html("Review failed to be loaded!").trigger("create").trigger("refresh");
}
}
function fail_user_review() {
$("#review_message").html("Connection down?").trigger("create").trigger("refresh");
}
PHP:
<?php //user_review_list.php
require_once "sql.php"; //connection to database and query is handled here
require_once "logged_in.php";
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors','On');
$session_id = $_SESSION['userid'][0];
$result = array();
$result['success'] = false;
$query = "SELECT * FROM reviews WHERE user = $session_id;";
if ($result_set = Sql::query($query)) {
$result['success'] = true;
$result['message'] = "Your Reviews" ;
$rows = mysqli_num_rows($result_set);
$result['rows'] = array();
for ($i = 0; $i<$rows; $i++) {
$tmpRow = mysqli_fetch_assoc($result_set);
$php_date = strtotime($tmpRow['date']);
$formatted_php_date = date('M d, Y', $php_date );
$tmpRow['date'] = $formatted_php_date;
$result['rows'][$i] = $tmpRow;
}
} else {
$result['message'] = "Failed to read Reviews" ;
}
print(json_encode($result));
Thanks
James
The messages you get mean you're trying to parse something that's already JSON. My earlier statement about parsing JSON is not going to be of much help here because you're not just getting back a string that needs to be converted to JSON -- which you really shouldn't be with $.getJSON().
You're getting back a JSON with an invalid encoding somewhere along the line, so trying to parse it won't help you. Validate your JSON first and foremost (the error could be due to your differing server settings between machines) using jsonlint, and continue from there.

Retrieving a JSON result

Hi I have used a code snippet from a tutorial for a chat application all of its scripts are working fine but after I tweak it to make the code work based on my requirements almost all of the scripts are working except for retrieving the conversation
The error I'm having is it doesn't retrieve the conversation from my database
here is the modified script
//Create the JSON response.
$json = '{"messages": {';
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$json .= '"message":[ {';
$json .= '"id": "0",
"user": "Admin",
"text": "You are not currently in a chat session. <a href="">Enter a chat session here</a>",
"time": "' . date('h:i') . '"
}]';
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$json .= '"message":[ ';
while($message_array = $stmt7->fetch(PDO::FETCH_ASSOC)) {
$json .= '{';
$json .= '"id": "' . $message_array['msgid'] . '",
"user": "' . htmlspecialchars($message_array['username']) . '",
"text": "' . htmlspecialchars($message_array['message_content']) . '",
"time": "' . $message_array['message_time'] . '"
},';
}
$json .= ']';
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$json .= '"message":[]';
}
}
//Close our response
$json .= '}}';
echo $json;
Here is the code for calling this script
//Gets the current messages from the server
function getChatText() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", 'includes/getChat.php?chat='+uid+'&last=' + lastMessage, true);
receiveReq.onreadystatechange = handleReceiveChat;
receiveReq.send(null);
}
}
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
//When our message has been sent, update our page.
function handleSendChat() {
//Clear out the existing timer so we don't have
//multiple timer instances running.
clearInterval(mTimer);
getChatText();
}
function handleReceiveChat() {
if (receiveReq.readyState == 4) {
//Get a reference to our chat container div for easy access
var chat_div = document.getElementById('clog');
var response = eval("(" + receiveReq.responseText + ")");
for(i=0;i < response.messages.message.length; i++) {
chat_div.innerHTML += response.messages.message[i].user;
chat_div.innerHTML += ' <font class="chat_time">' + response.messages.message[i].time + '</font><br />';
chat_div.innerHTML += response.messages.message[i].text + '<br />';
chat_div.scrollTop = chat_div.scrollHeight;
lastMessage = response.messages.message[i].id;
}
mTimer = setTimeout('getChatText();',20000); //Refresh our chat in 2 seconds
}
}
Am I missing something here or doing something wrong?
You should rewrite using json_encode:
$messages = array();
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$message_object = (object) array(
"id"=>"0",
"user"=>"Admin",
"text"=>"You are not currently in a chat session. <a href=\"\">Enter a chat session here</a>",
"time"=>date('h:i')
);
$messages[] = (object) array("message"=>$message_object);
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$message_object = (object) array(
"id"=>$message_array['msgid'],
"user"=>htmlspecialchars($message_array['username']),
"text"=>htmlspecialchars($message_array['message_content']),
"time"=>$message_array['message_time'
);
$messages[] = (object) array("message"=>$message_object);
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$messages[] = (object) array("message"=>array());
}
}
//Close our response
$result = (object) array('messages'=>$messages);
$json = json_encode($result);
echo $json;

Javascript countdown only when page reload

i have opencart module daily deal, but the countdown timer is not working.
function code:
<?php
class ModelCatalogSpecialPriceCountDown extends Model {
public function getProductSpecialDates($product_id) {
(string) $display_output = null;
(string) $minute = 60;
(string) $hour = 60 * $minute;
(string) $day = 24 * $hour;
if ($this->customer->isLogged()) {
$customer_group_id = $this->customer->getCustomerGroupId();
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
$query = $this->db->query("SELECT date_start, date_end FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "' AND customer_group_id = '" . (int)$customer_group_id . "' AND ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) ORDER BY priority ASC, price ASC LIMIT 1");
if ($query->num_rows) {
$time_left = strtotime($query->row["date_end"]) - strtotime(date('Y-m-d'));
$days_left = floor($time_left/$day);
if ($time_left > 0)
{
$display_output = getdate();
$display_output["days_left"] = $days_left;
}
}
return $display_output;
}
}
?>
and the code using it:
<!-- Countdown start -->
<div id="defaultCountdown<?php echo $product['product_id'];?>" class="countdown_dashboard"></div>
<script type="text/javascript"><!--
$(document).ready(function() {
$('#defaultCountdown<?php echo $product["product_id"]; ?>').countdown({
until: new Date(<?php echo $product['yleft'];?>, <?php echo $product['mleft'];?> - 1, <?php echo $product['dleft'];?>)
});
});
//-->
</script>
My countdown doesn't work, the numbers change only when I refresh the page.

Categories

Resources