Post dynamic twitter updates - javascript

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.

Related

If image url not exist on server replace url with other (multiple time)

I made lastposter avatar for my forum system.
What i want : when user avatar img not exist change file type multiple time. Such example; if user_{userid}_avatar.png not exist change url to user_{user_id}_avatar.jpg and again it's not exist change to user_{userid}_avatar.gif and etc.({user_id} coming as php variable that's no matter).
<div class="lpavatar"><img src="/avatar/user_{user_id}.png"/></div>
<div class="lpavatar"><img src="/avatar/user_{user_id}.png"/></div>
<div class="lpavatar"><img src="/avatar/user_{user_id}.png"/></div>
You can do something like this:
Javascript:
var img_types = ['jpeg', 'gif', 'png'];
var avatar = '';
for(var i=0;i<img_types.length();i++) {
avatar = new File("/path/to/avtar." + img_types[i]);
// See if the file exists
if(avatar.exists()){
break;
}
}
PHP:
<?php
// put allowed image types in this array
$img_types = ['jpeg', 'gif', 'png'];
// avatar URL will be stored in here
$avatar = '';
// loop over the image_types array
foreach($img_types as $img_type) {
$avatar = '/path/to/user_{userid}_avatar.' . $img_type;
// check if the files exists
if(file_exists($avatar)) {
// exit the foreach loop, because we found the image
break;
}
}
?>
You can use a function like this.
function image_exists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}

Alternative to AJAX setTimeout?

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.

JSON error when trying to parse request length in loop

So I am trying to make a simple autocomplete form but keep getting a error when I try to test the program.
When I try to test the program my console spits out [11:25:26.267] SyntaxError: JSON.parse: unexpected character # /search.php:22 which is this line. I am pretty sure my syntax is fine but I could be mistaken. Any and all help would be most gratefully appreciated. Thank you to anyone who takes the time to read and/or answer even if you cannot help!
for (var i = 0; i < response.length; i++)
My Full code is as follows.
Edit: Now with page that echos the json. When I do console.log(req.responsetext) i get [11:38:04.967] ReferenceError: req is not defined. But i define req as a new xml request on window load so I am kind of stumped.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Auto Complete</title>
</head>
<body>
<script>
window.onload = function () {
var req = new XMLHttpRequest(); //the HTTP request which will invoke the query
var input = document.getElementById('search'); //where to grab the search from
var output = document.getElementById('results'); //where to display the sugestions
input.oninput = getSuggestions;
function getSuggestions() {
req.onreadystatechange = function () {
output.innerHTML = ""; //CLEAR the previous results!! only once the server can process new ones though
if (this.readyState == 4 && input.value != "") {
var response = JSON.parse('(' + req.responseText + ')');
for (var i = 0; i < response.length; i++)
addSuggestion(response[i].terms);
}
}
req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
req.send(null);
}
addSuggestion = function (suggestion) {
var div = document.createElement('div');
var p = document.createElement('p');
div.classList.add('suggestion'); //suggestion[x]...
p.textContent = suggestion;
div.appendChild(p);
output.appendChild(div);
div.onclick = function() {
input.value = p.innerHTML; //set the search box
getSuggestions(); //GET new suggesions
}
}
}
</script>
<input type='text' id='search' name='search' autofocus='autofocus'>
<div id='results'></div>
</body>
</html>
edit this is my php page that echos the json.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (!isset($_GET['query']) || empty($_GET['query']))
header('HTTP/1.0 400 Bad Request', true, 400);
else {
$db = new PDO(
my database
);
$search_query = $db->prepare("
SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
");
$params = array(
':keywords' => $_GET['query'] . '%',
);
$search_query->execute($params);
$results = $search_query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
?>
Get rid of the ( and ) in the JSON.parse!
JSON.parse('(' + req.responseText + ')')
should be
JSON.parse( req.responseText );
hopefully the responseText is valid JSON

POSTing data serverside AND execute javascript code on submitting a form

My goal is to upload some images to a server and provide them with a description.
On clicking an upload button, this is what I want to happen:
1) a javascript function dynamically adds a form to get a description
of the images.
2) on submitting the form:
a) the description entered in the form must be available $_POST['description'] at server side.
b) the images are sent to the server using an XMLHttpRequest
In the code I wrote the description is not available $_POST['description'].
When i remove the check if(!isset($_POST['description'])), the imagefiles are perfectly uploaded.
This is my code:
javascript code
upload.onclick = uploadPrompt;
// dynamically add a form
function uploadPrompt () {
// fileQueue is an array containing all images that need to be uploaded
if (fileQueue.length < 1) {
alert("There are no images available for uploading.");
} else {
var inputDescription = document.createElement("input");
inputDescription.className = "promptInput";
inputDescription.type = "text";
inputDescription.name = "description";
var inputButton = document.createElement("button");
inputButton.id = "promptInputButton";
inputButton.type = "submit";
inputButton.innerHTML = "Start uploading";
var promptForm = document.createElement("form");
promptForm.method = "post";
promptForm.action = "upload.php";
promptForm.onsubmit = uploadQueue;
promptForm.id = "promptForm";
promptForm.appendChild(inputDescription);
promptForm.appendChild(inputButton);
document.body.appendChild(promptForm);
}
}
function uploadQueue(ev) {
ev.preventDefault();
elementToBeRemoved = document.getElementById("promptForm");
elementToBeRemoved.parentElement.removeChild(elementToBeRemoved);
while (fileQueue.length > 0) {
var item = fileQueue.pop();
// item.file is the actual image data
uploadFile(item.file);
}
}
function uploadFile (file) {
if (file) {
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append('image',file);
xhr.upload.addEventListener("error", function (ev) {
console.log(ev);
}, false);
xhr.open("POST", "upload.php");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.send(fd);
}
}
php code upload.php
<?php
session_start();
if (!isset($_POST['description'])) {
echo "upload:fail\n";
echo "message:No scene was specified";
exit();
}
if (isset($_FILES['image'])) {
if(!move_uploaded_file($_FILES['image']['tmp_name'], "uploads/" . $_POST['description'] . "/" . $_FILES['image']['name'])) {
echo "upload:fail\n";
}
else {
echo "upload:succes\n";
}
exit();
}
exit();
?>
I'd really advise against creating your own asynchronous file upload functionality when there is a plethora of developers who have already programmed the same thing better. Check out these options:
Blueimp's jQuery file uploader
Uploadifive (Uploadify's HTML5 implementation)
I've used these two before and they work very well. For BlueImp, you can use this option to send additional form data:
$('#fileupload').fileupload({
formData: $('.some_form').serialize()
});
The above captures a form and serializes its inputs. Alternatively, you can populate an array or object using specific values (i.e. from specific elements in your DOM):
var array = new Array();
$('.description').each(function() {
array[this.id] = this.value;
});
You'd use IDs to link your files and descriptions.

How to download multiple files in one shot in IE

I want to download multiple files on click of a button in jsp.
I am using the following code in the js to call one servlet twice.
var iframe = document.createElement("iframe");
iframe.width = iframe.height = iframe.frameBorder = 0;
iframe.scrolling = "no";
iframe.src = "/xyz.jsp?prodId=p10245";
document.getElementById("iframe_holder").appendChild(iframe);
var iframe2 = document.createElement("iframe");
iframe2.width = iframe2.height = iframe2.frameBorder = 0;
iframe2.scrolling = "no";
iframe2.src = "/xyz.jsp?prodId=p10243";
document.getElementById("iframe_holder").appendChild(iframe2);
In xyz.jsp i am calling the servlet which downloads the file from a path and send it on the browser.
Issue is that it is working safari,firefox but not in IE.
We cannot download multiple files with IE?
By design, non-user-initiated file downloads are blocked in IE. That inherently means that it should not be possible to download more than one file as the result of a single user-click.
I've used the following code to download multiple files in IE and Chrome
function downloadFile(url)
{
var iframe = document.createElement("iframe");
iframe.src = url;
iframe.style.display = "none";
document.body.appendChild(iframe);
}
function downloadFiles(urls)
{
downloadFile(urls[0]);
if (urls.length > 1)
window.setTimeout(function () { downloadFiles(urls.slice(1)) }, 1000);
}
You pass an array of URLs to the downloadFiles() function, which will call downloadFile() for each with a short delay between. The delay seems to be the key to getting it to work!
I had a similar need but also wanted the downloads to occur in a new window.
I created a js to download a list of files, and a php to do the actual file saving. I used the above as a starting point, and the PHP start from (okay, can't find the original source). I encode the passed URI so spaces in the file names don't cause troubles.
(function () {
"use strict";
var files = [], // Array of filename strings to download
newWindow, // New window to handle the download request
secondsBetweenDownloads; // Wait time beteen downloads in seconds
//
// Download a file using a new window given a URI
//
function downloadFile(uri) {
if (!newWindow) {
newWindow = window.open('',
'',
'width=1500 height=100');
}
if (newWindow) {
newWindow.location =
'saveAs.php?' +
'file_source=' + encodeURI(uri);
newWindow.document.title = "Download File: " + uri;
} else {
console.log("Unable to open new window. Popups blocked?");
}
}
//
// Download all files specified in the files[] array from siteName.
// Download the file at array position zero, then set a timeout for
// secondsBetweenDownloads seconds
//
function downloadFiles(siteName) {
var showTime = new Date();
console.log(
showTime.toTimeString().substring(0,8) +
" Starting download for: " + files[0]
);
// Skip any empty entries, download this file
if (files[0].length > 0) downloadFile(siteName + files.splice(0, 1));
if (files.length > 0) { // If more files in array
window.setTimeout(function () { // Then setup for another iteration
downloadFiles(siteName );
}, secondsBetweenDownloads * 1000); // Delay for n seconds between requests
} else {
newWindow.close(); // Finished, close the download window
}
}
//
// Set the web site name and fill the files[] array with the files to download
// then kick off the download of the files.
//
$(document).ready(function () {
var
siteName** = "http://www.mysteryshows.com/thank-you/";
secondsBetweenDownloads** = 35; // N seconds delay between requests
files = [
"show1.mp3",
"show2.mp3"
];
downloadFiles(siteName, files);
});
}());
The HTML for the page is simple. Basically any syntax-compliant page will do.
The saveAs.php page which the js file uses in the newWindow.location line is php only.
<?php
if (isset($_GET['file_source'])) {
$fullPath = $_GET['file_source'];
if($fullPath) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-Disposition: attachment;
filename=\"".$path_parts["basename"]."\""); // use 'attachment' to
// force a download
header("Content-type: application/pdf"); // add here more headers for
// diff. extensions
break;
default;
header("Content-type: **application/octet-stream**");
header("Content-Disposition:
filename=\"".$path_parts["basename"]."\"");
}
if($fsize) {//checking if file size exist
header("Content-length: $fsize");
}
$request = $path_parts["dirname"] . '/' .
rawurlencode($path_parts["basename"]);
readfile($request);
exit;
}
}
?>
I used rawurlencode on just the 'basename' portion of the URI to ensure it was a valid, encoded request.
It can be done by creating a blob using the file source URL. I have tested this with image and PDF files in IE 11.
if (navigator.msSaveBlob) {
var xhr = new XMLHttpRequest();
xhr.open('GET', file_url, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
navigator.msSaveBlob(blob, file_name);
}
}
xhr.onerror = function(e) {
alert("Error " + e.target.status + " occurred while receiving the document.");
}
xhr.send();
}
I got this idea when I came across this: Getting BLOB data from XHR request

Categories

Resources