Twitter $get help - php

Just wondering if someone can assist me with the following issue. I have come across the following code which pulls in latest Twitter posts and displays them on a site:
//Handle the scrolling of the tweets in the footer
$(function () {
var tweetVP = $("#footerTweetsViewport");
arrTweetNav = ECC.tweetArray();
thisTweetID = arrTweetNav[0];
$("ul#tweetControls > li").bind("click", function(e) {
e.preventDefault();
var thisPos = $.inArray(thisTweetID, arrTweetNav);
if ($(this).hasClass("tweetPrev")) {
nextPos = thisPos - 1;
} else {
nextPos = thisPos + 1;
}
nextID = arrTweetNav[nextPos];
//If that tweet exists in the DOM...
if ($("#listOfTweets > #" + nextID).length) {
//Reset the inactive buttons
$("ul#tweetControls > li").removeClass("inactive");
//Scroll to the destination
tweetVP.scrollTo("#" + nextID, 200);
//Set the thisID to the value of the nextID
thisTweetID = nextID;
}
//Disable the controls if we're on the first or last tweet
if (nextPos == arrTweetNav.length-1) {
$("ul#tweetControls > li.tweetNext").addClass("inactive");
} else if (nextPos == 0) {
$("ul#tweetControls > li.tweetPrev").addClass("inactive");
}
}).bind("mousedown", function() {
$(this).closest("li").addClass("click");
}).bind("mouseup", function() {
$(this).closest("li").removeClass("click")
});
});
//Search the dom for twitter containers that need tweets loaded for
$(function() {
$(".globalTweetWrapper").each(function() {
var thisUsername = $(this).attr("class").replace("globalTweetWrapper ", "");
var tweetContainer = $(this);
var loadTweets = tweetContainer.find(".loadTweets");
//Detect if we're going to flush the tweets
var flushTweets = $.getUrlVar("flushTweets");
if (flushTweets != 1) {
flushTweets = 0;
}
$.getJSON("get-tweets.cfm?username=" + thisUsername + "&flushTweets=" + flushTweets, function(data) {
if (data.length && loadTweets.length) {
loadTweets.remove();
$.each(data, function(i,item) {
if (tweetContainer.attr("id") == "listOfTweets") {
tweetContainer.append("<li class='tweetContainer' id='" + item.ID + "'>" + item.TWEET + "<small class='darkGray'>" + item.DATE + "</small></li>");
} else {
tweetContainer.append("<p class='tweetContainer'>" + item.TWEET + "</p><small class='darkGray'>" + item.DATE + "</small>");
if (i == 1) return false;
}
});
//Rebuild the tweet array
arrTweetNav = ECC.tweetArray();
thisTweetID = arrTweetNav[0];
}
});
});
});
This is the HTML
container for the Tweets on the site is as follows:
<div class="footerItem posRelative">
<h3>Follow us on Twitter</h3>
<ul id="tweetControls">
<li class="tweetPrev inactive">Previous Tweet</li>
<li class="tweetNext">Next Tweet</li>
</ul>
<div id="footerTweetsViewport">
<ul id="listOfTweets" class="globalTweetWrapper">
</ul>
My site is not coldfusion; therefore I simply want to modify the get-tweets.cfm and would like some assistance please. I have come across the following:
//initialize a new curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'twitter url goes here/statuses/user_timeline/twitterusername.json?count=10');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
if($content === FALSE) {
//Content couldn't be retrieved... Do something
} else {
//Content was retrieved do something with it.
}
So I would really like to rebuild the get-tweets.cfm to a PHP script get-tweets.php; however, I'm not sure what exactly I need this to do to get this to work as per the coldfusion script as everything else is fine?
Many thanks

A new get_tweets script to get tweets, filter to the columns you wanted, cache (in case of Twitter fail whale) and echo results.
<?php
$username = "danielgwood";
$num = 5;
$feed = "http://search.twitter.com/search.json?q=from:" . $username . "&rpp=" . $num;
$cachefile = dirname(__FILE__)."/twitter.json";
// Get new contents
$newTweets = #file_get_contents($feed);
// Filter columns
$tweets = array();
if($newTweets !== null) {
$newTweetsObj = json_decode($newTweets);
foreach($newTweetsObj->results as $tweet) {
$tweets[]['ID'] = $tweet->id;
$tweets[]['TWEET'] = $tweet->text;
$tweets[]['DATE'] = $tweet->created_at;
}
$newTweets = json_encode($tweets);
}
// Cache result
if($newTweets !== null) {
#file_put_contents($cachefile, $newTweets);
}
$tweets = #file_get_contents($cachefile);
echo $tweets;
?>

Twitter provides tweets in JSON format via the API. You need to retrieve these, cache them on your server (write out to a file outside of the web tree) in case Twitter goes down as it regularly does, then echo the JSON out for the Javascript to pick up.
I haven't tested this, but its definitely along the right lines. See bavotasan.com
$username = "your-user-name";
$num = 5;
$feed = "http://search.twitter.com/search.json?q=from:" . $username . "&rpp=" . $num;
$newfile = dirname(__FILE__)."/twitternew.json";
$file = dirname(__FILE__)."/twitter.json";
copy($feed, $newfile);
$oldcontent = #file_get_contents($file);
$newcontent = #file_get_contents($newfile);
if($oldcontent != $newcontent) {
copy($newfile, $file);
}
$tweets = #file_get_contents($file);
echo $tweets;
I should note the above solution is designed to replace the coldfusion script entirely. To use the PHP excerpt you already have, just add the caching to file, and echo parts. That should get you most if not all of the way there.

Related

Make am auto scroll load more data when user reaches bottom from api

okay i have an api from which i get data and the data is put into an array that data is then put on an html page for the users to scroll through.all that is working.
i would like to know how i can now put only the first 10 results on to a page and then the rest auto reload from the array.
i have seen those with mysql but getting data from an array is still bothering me.
any help is welcome.
$url = 'API';
$ch = curl_init();
curl_setopt($ch, CURLOPT_U`enter code here`RL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$echo_array = $array['jobs'];
usort($echo_array, function($a, $b) {
return strtotime($a['einsatzstartdatum']) - strtotime($b['einsatzstartdatum']);
});
// print_r($echo_array);
foreach ($echo_array as $job)
{
//echo "Id:". $job['ID'] ."\n";
echo "Town:". $job['einsatzort'] ."\n";
echo "stellentitel:". $job['stellentitel'] ."\n";
echo "einsatzstartdatum:". $job['einsatzstartdatum'] ."\n";
echo "bewerbunganlagenbenoetigt:". $job['bewerbunganlagenbenoetigt'] ."\n"."\n"."\n";
};
If it's just about the display i would put the content in a javascript array with all your php rows in it.
Than update the content with a scroll event when it reaches the bottom.
here's a little example i made to get an idea of how i would go about it:
(keep in mind this is based on the idea that you load all the data at once)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
//fill a javascript arr with all your content
var dummyContentArr = new Array();
var limit = 10;
//just for the example some dummy data
for(var i = 0; i < 100; i++) {
var dummyContent = 'town: yada ' + i + '"\n"' +
'stellentitel: test ' + i + '"\n"' +
'einsatzstartdatum: test ' + i + '"\n" ' +
'bewerbunganlagenbenoetigt: test ' + i + '"\n"';
dummyContentArr.push(dummyContent);
}
$(document).ready(function() {
displayContent(10);
//this scroll event will will update the limit when the scroll bar hits the bottom
$('#content').on('scroll', function() {
if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
displayContent(limit);
limit += 10;
}
});
});
//just a simple function thingy to update the content
function displayContent(limit) {
content = '';
for(i = 0; i < limit; i++) {
content += dummyContentArr[i];
}
$('#content').html(content);
}
</script>
<style>
#content {
background-color: red;
height: 200px;
width: 200px;
overflow-y: scroll;
}
</style>
<div id="content"></div>

Load more instead of going to next page using pagination/API

I am working on a project to display select Instagram photos in an album by hashtag, since the Instagram API limits 35 images per API call I figured out I either had to use AJAX (which I am very poor at) or a mixture of PHP and AJAX. I decided on the latter because I didn't want my access token and user ID made available in the code on my gallery.
<?PHP
function jsongram($next=null){
$userid = "xxx";
$accessToken = "xxx";
$url = ("https://api.instagram.com/v1/users/{$userid}/media/recent/?access_token={$accessToken}");
if($url !== null) {
$url .= '&max_id=' . $next;
}
//Also Perhaps you should cache the results as the instagram API is slow
$cache = './'.sha1($url).'.json';
//unlink($cache); // Clear the cache file if needed
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache));
}else{
$jsonData = json_decode((file_get_contents($url)));
file_put_contents($cache,json_encode($jsonData));
}
?>
<html>
<head>
</head>
<body>
<?php
$data_array = array();
foreach ($jsonData->data as $data){
if (stripos($data->caption->text,'egypt') === false) {
}
else{
$data_array[] = $data;
$data = (str_split($data->caption->text));
$data = (array_filter($data));
}
}
foreach ($data_array as $data):{
$igimglow = $data->images->low_resolution->url;
$igimgstd = $data->images->standard_resolution->url;
$igimgthumb = $data->images->thumbnail->url;
$igcaption = str_replace('#', '', (preg_replace('/(?:#[\w-]+\s*)+$/', '', $data->caption->text)));
$igtime = date("F j, Y", $data->caption->created_time);
$iglikes = $data->likes->count;
$igcomments = $data->comments->count;
$iglong = $data->location->longitude;
$iglat = $data->location->latitude ;
$igusername = $data->user->username;
$igfullname = $data->user->full_name;
$iglink = $data->link;
$igfilter = $data->filter;
$igtags = implode(',',$data->tags);
?>
<img src="<?php echo ($igimglow);}?>">
<?php endforeach ?>
<?php
if(isset($jsonData->pagination->next_max_id)) {
$result .= '<div>Next</div>';
}
return $result;
}
?>
<div id="container">
<?=jsongram(#$_GET['next']);?>
<div id="result"></div>
</div>
</body>
</html>
Here's a live example of the above code:
http://johnricedesign.com/examples/pn.php
As shown above on the 2nd page photos tagged with "egypt" are displayed. I would like to replace the "Next" link to automatically load on the same page with a "Load More" button - to the best of my knowledge using AJAX is the only way of doing so. However I do not know how to do so, or even where to start. The second obvious problem I have is that even though I am removing the photos that don't contain the caption of "egypt" I am still getting a lot of blank spaces, I presume that will be rather simple to fix once AJAX is being used.
I have been pulling my hair out for the last 5 days trying to do this. You help, advice, wisdom, are much appreciated in advance.
I changed the the api to work with client_id rather than access_token. You can change it back it will have no effect.
Demo: https://tjay.co/l/instagrampagination
ajax.php
<?php
function jsongram($next = null)
{
$userid = "xxx";
$accessToken = "xxx";
$url = ("https://api.instagram.com/v1/users/{$userid}/media/recent/?client_id={$accessToken}");
if ( !empty($next) ) {
$url.= '&max_id=' . $next;
}
// Also Perhaps you should cache the results as the instagram API is slow
$cache = './' . sha1($url) . '.json';
// unlink($cache); // Clear the cache file if needed
// If a cache file exists, and it is newer than 1 hour, use it
if (file_exists($cache) && filemtime($cache) > time() - 60 * 60) {
$jsonData = json_decode(file_get_contents($cache));
} else {
$jsonData = json_decode(file_get_contents($url));
file_put_contents($cache, json_encode($jsonData));
}
return $jsonData;
}
function instaFormat($jsonData)
{
$data_array = array();
$response = array();
foreach($jsonData->data as $data) {
if ( !empty($data->caption->text) && stripos($data->caption->text, 'egypt') !== false ) {
$data_array[] = $data;
$data = (str_split($data->caption->text));
$data = (array_filter($data));
}
}
$response['next'] = $jsonData->pagination->next_max_id;
foreach($data_array as $data) {
$igimglow = $data->images->low_resolution->url;
// $igimgstd = $data->images->standard_resolution->url;
// $igimgthumb = $data->images->thumbnail->url;
// $igcaption = str_replace('#', '', (preg_replace('/(?:#[\w-]+\s*)+$/', '', $data->caption->text)));
// $igtime = date("F j, Y", $data->caption->created_time);
// $iglikes = $data->likes->count;
// $igcomments = $data->comments->count;
// $iglong = $data->location->longitude;
// $iglat = $data->location->latitude;
// $igusername = $data->user->username;
// $igfullname = $data->user->full_name;
// $iglink = $data->link;
// $igfilter = $data->filter;
// $igtags = implode(',', $data->tags);
$response['data'][] = '<img src="'.$igimglow.'">';
}
return $response;
}
if ( isset($_POST['next']) ) {
echo json_encode(instaFormat(jsongram($_POST['next'])));
die();
}
index.php
<!doctype html>
<html>
<body>
<div data-pictures></div>
<div><button type="button" data-get-next>Next</button></div>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
jQuery(function($) {
$(document).on('get-feed', function(e, next_id) {
var data = {
next: next_id
};
$.post('ajax.php', data, function(response) {
var container = $('[data-pictures]');
response = $.parseJSON(response);
container.html('');
$('[data-get-next]').attr('data-get-next', response.next);
$.each(response.data, function(i, val) {
$(val).appendTo(container);
});
});
});
$('[data-get-next]').click(function() {
var next_id = $(this).attr('data-get-next');
$.event.trigger('get-feed', next_id);
});
$.event.trigger('get-feed', 0);
});
</script>
</body>
</html>

JSONP and GET with callbacks - help needed correcting errors

This is my JSONP file:
<?php
header('Content-type: application/javascript;');
header("access-control-allow-origin: *");
header("Access-Control-Allow-Methods: GET");
//db connection detils
$host = "localhost";
$user = "test";
$password = "test";
$database = "myradiostation1";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//query the database
$query = mysql_query("SELECT *, DATE_FORMAT(start, '%d/%m/%Y %H:%i:%s') AS start,
DATE_FORMAT(end, '%d/%m/%Y %H:%i:%s') AS end FROM radiostation1");
//loop through and return results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
$shows[$x] = array("id" => $row["id"], "startminutes" => $row["startminutes"], "start" => $row["start"], "endminutes" => $row["endminutes"],"end" => $row["end"],"mediumname" => $row["mediumname"], "longname" => $row["longname"], "description" => $row["description"],"short_id" => $row["short_id"],"promomessage" => $row["promomessage"],"email" => $row["email"],"phonenumber" => $row["phonenumber"],"textnumber" => $row["textnumber"],"textprefix" => $row["textprefix"],"showimage" => $row["showimage"],"longdescription" => $row["longdescription"],"facebooklink" => $row["facebooklink"],"otherlink" => $row["otherlink"],"websitelink" => $row["websitelink"],"keywords" => $row["keywords"] );
}
//echo JSON to page
$response = $_GET["callback"] . "(" . json_encode($shows) . ");";
echo $response;
?>
It does work, up to a point, but getting the {"success":true,"error":"","data":{"schedule": as seen at this site before my json_encode is where I am.
However, I cannot get it to display any data in my table, although it DOES produce code on-screen when I view it at http://www.myradio1.localhost/onairschedule.php.
The actual code is stored at http://www.myradiostations.localhost/schedule.php
and the callback function works OK, one example being http://www.myradiostations.localhost/schedule.php?callback=?&name=Northern+FM and http://www.myradiostations.localhost/schedule.php?callback=?&name=Southern+FM but what do I need to do to make it change like in these examples:
this example and this example, and to generate an error message like this if no such file exists.
I'm halfway there, just need some advice on fixing my code!
Basically, what I'm trying to do... get a JSONP to work in my HTML table which will vary the content depending on the URL in my javascript file on my page, which is:
var doFades = true;
var LocalhostRadioStations = {
Schedule : {}
};
$(document).ready(function(){
LocalhostRadioStations.Schedule.days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
LocalhostRadioStations.Schedule.Show = function () {
_s = null;
_startDate = null;
_endDate = null;
this.days = LocalhostRadioStations.Schedule.days;
_selector = '';
this.setShow = function(s) {
this._s = s;
this._startDate = new Date( parseInt(s.startminutes, 10) * 1000);
this._endDate = new Date(parseInt(s.endminutes, 10) * 1000 );
};
this.getEndDate = function(){
return this._endDate;
}
this.getStartDate = function(){
return this._startDate;
}
this._getShowDay = function (){
return this.days[this.getStartDate().getDay()];
};
this._getShowUnitsTaken = function(){
// if it's the same day
return this._getEndUnits() - this._getStartUnits();
};
this._getEndUnits = function(){
if(this.getEndDate().getHours() == 0)
{
//console.log(this._s.longname +' ends at midnight');
return 48;
}
return this.getEndDate().getMinutes() !== 0 ? (this.getEndDate().getHours() * 2) : (this.getEndDate().getHours() * 2);
};
this._getStartUnits = function(){
if(this.getStartDate().getHours() == 0)
{
return 0;
}
return this.getStartDate().getMinutes() !== 0 ? (this.getStartDate().getHours() * 2) : (this.getStartDate().getHours() * 2);
};
this.getCellPositions = function() {
return {
'start' : this.getStartDate(),
'end' : this.getEndDate(),
'colIndex' : this.getStartDate().getDay() + 2,
'startUnits' : this._getStartUnits(),
'endUnits' : this._getEndUnits(),
'unitsTaken' : this._getShowUnitsTaken()
}
};
this.pad = function(number){
return number < 10 ? '0'+number : number;
};
// return the table cell html.
this.toHtml = function () {
var d = new Date();
var units = this._getStartUnits();
var rowspan = this._getShowUnitsTaken();
var desc = this._s.description;
var name = this._s.longname;
var starttime = this.pad(this.getStartDate().getHours()) + ':' + this.pad(this.getStartDate().getMinutes());
var endtime = this.pad(this.getEndDate().getHours()) + ':' + this.pad(this.getEndDate().getMinutes());
var site = this._s.websitelink;
var cls = this.isActive() ? 'current-program' : '';
var isToday = this.getStartDate().getDay() === d.getDay() ? 'active-program' : '';
var html = '<td class="schedule-show ' + isToday + ' ' + cls + '" rowspan="' + rowspan + '" data-start="' + this.getStartDate() + '" data-end="' + this.getEndDate() + '">';
html += '<div>';
html += '' + name + '';
html += '</div>';
if(doFades)
{
html += '<div class="schedule_details clearfix" style="display:none;">';
html += '<img width="105px" height="105px" alt="' + desc + '" src="' + this._s.showimage + '">';
html += '<strong>' + name + '</strong>';
html += '<p>' + desc + '</p>';
html += '<span>' + starttime + ' - ' + endtime +'</span>';
html += '</div>';
}
html += '</td>';
return html;
};
this.setTableSelector = function(sel){
this._selector = sel;
};
// check if we should add the active class.
this.isActive = function(){
var t = new Date();
return t >= this.getStartDate() && t <= this.getEndDate();
};
};
LocalhostRadioStations.Schedule.ScheduleGen = function(){
return {
insertShow : function(show) {
var p = show.getCellPositions();
$('tr#units-' + p.startUnits).append(show.toHtml());
},
init : function (stationName){
var self = this;
// load the schedule.
$.getJSON('http://www.myradiostations.localhost/schedule.php?callback=?&name=', {
name: 'Northern FM'
}, function(json){
// loop each show and append to our giant table.
// this is well sick.
if(json.success === false)
{
$('.content-inner table').remove();
$('<div>errors</div>').appendTo('.content-inner');
}
else
{
var currentDay = '';
var day = 0;
// highlight the current time..
var d = new Date();
var weekStart = new Date();
weekStart.setDate(d.getDate()-6-(d.getDay()||7));
$.each(json.data.schedule, function(i, broadcast){
var dStart = new Date( parseInt(broadcast.startminutes, 10) * 1000);
var dEnd = new Date(parseInt(broadcast.endminutes, 10) * 1000 );
/*// transform to a show object defined above, if the show spans 2 days we create two show objects.
// IF THE SHOW STARTS/ENDS AT MIDNIGHT, DON'T SPLIT IT.
if(dStart.getHours() !== 0 && dEnd.getHours() !== 0 && dStart.getDate() != dEnd.getDate())
{
var showOne = new LocalhostRadioStations.Schedule.Show();
showOne.setShow(broadcast);
// set to midnight
showOne.getEndDate().setHours(0);
showOne.getEndDate().setMinutes(dStart.getMinutes());
// append first half of show.
self.insertShow(showOne);
// handle second half.
var showTwo = new LocalhostRadioStations.Schedule.Show();
showTwo.setShow(broadcast);
showTwo.getStartDate().setDate(showTwo.getStartDate().getDate() + 1);
showTwo.getStartDate().setHours(0);
showTwo.getStartDate().setMinutes(dEnd.getMinutes());
//console.log('2nd Half Start: ' + showTwo.getStartDate());
//console.log('2nd Half End: ' + showTwo.getEndDate());
self.insertShow(showTwo);
}
else
{*/
var show = new LocalhostRadioStations.Schedule.Show();
show.setShow(broadcast);
show.setTableSelector('table#schedule');
// add the show to the table. Thankfully the order these come out the API means they get added
// in the right place. So don't change the schedule builder code!
self.insertShow(show);
//}
});
var days = LocalhostRadioStations.Schedule.days;
// apply the current day / time classes
$('th:contains('+ days[d.getDay()]+')').addClass('active');
$('td.time').each(function(i, cell){
// get the value, convert to int.
var hours = $(cell).html().split(':')[0];
// compare the hours with now, add class if matched.
if(parseInt(hours, 10) === d.getHours())
{
$(cell).addClass('current_time');
}
});
}
if(doFades)
{
// apply events to show info fade in / out.
$('td.schedule-show').hover(function(){
$(this).find('.schedule_details').fadeIn('fast');
}, function(){
$(this).find('.schedule_details').fadeOut('fast');
});
}
});
}
};
}();
LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);
});
It should change the schedule according to the JSONP, but what do I do to fix it?
Basically, I am trying to make my own localhost version of http://radioplayer.bauerradio.com/schedule.php?callback=&name=Rock+FM and its JSON / JSONP (I am not sure exactly what type the original is, but then again the site is experimental and on a .localhost domain) for testing purposes where the content is taken from the database, and changes according to station name, e.g. http://radioplayer.bauerradio.com/schedule.php?callback=&name=Metro+Radio and http://radioplayer.bauerradio.com/schedule.php?callback=&name=Forth+One etc.
Edit: The full code for my page can be seen at http://pastebin.com/ENhR6Q9j
I'm not sure exactly what's missing, but from the code you gave so far, I made a jsfiddle:
Demo
I modified some things to make it work (mostly appending stuff), because I don't know your original HTML file. But I also made some changes based on what you say you wanted. First of all I modified your $.getJSON call to be something like:
$.getJSON('http://radioplayer.bauerradio.com/schedule.php?callback=?', {
name: stationName //stationName is from the argument passed
}, function(json){...})
Which should give back the station based on what is passed to
LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);
To make it more interesting, I also added a bit of code that reads from the url. In this case if you go to the page with a domain.htm/page?Northern FM it will read the text after the ? and put it in twittiName.
var twittiName="Rock FM"; //default station
if(window.location.search){
twittiName=window.location.search.substring(1) //or window.location.hash
}
Tried to look for other stations that might be on your publics site, but so far I could only test with "?Rock+FM". But does mean you can show the errors, which your code can handle as it is.
?Rock+FM
?Random Name
So it seems that your code mostly works but do comment if I have missed anything.

JSON/PHP script and callbacks [duplicate]

This is my JSONP file:
<?php
header('Content-type: application/javascript;');
header("access-control-allow-origin: *");
header("Access-Control-Allow-Methods: GET");
//db connection detils
$host = "localhost";
$user = "test";
$password = "test";
$database = "myradiostation1";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//query the database
$query = mysql_query("SELECT *, DATE_FORMAT(start, '%d/%m/%Y %H:%i:%s') AS start,
DATE_FORMAT(end, '%d/%m/%Y %H:%i:%s') AS end FROM radiostation1");
//loop through and return results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
$shows[$x] = array("id" => $row["id"], "startminutes" => $row["startminutes"], "start" => $row["start"], "endminutes" => $row["endminutes"],"end" => $row["end"],"mediumname" => $row["mediumname"], "longname" => $row["longname"], "description" => $row["description"],"short_id" => $row["short_id"],"promomessage" => $row["promomessage"],"email" => $row["email"],"phonenumber" => $row["phonenumber"],"textnumber" => $row["textnumber"],"textprefix" => $row["textprefix"],"showimage" => $row["showimage"],"longdescription" => $row["longdescription"],"facebooklink" => $row["facebooklink"],"otherlink" => $row["otherlink"],"websitelink" => $row["websitelink"],"keywords" => $row["keywords"] );
}
//echo JSON to page
$response = $_GET["callback"] . "(" . json_encode($shows) . ");";
echo $response;
?>
It does work, up to a point, but getting the {"success":true,"error":"","data":{"schedule": as seen at this site before my json_encode is where I am.
However, I cannot get it to display any data in my table, although it DOES produce code on-screen when I view it at http://www.myradio1.localhost/onairschedule.php.
The actual code is stored at http://www.myradiostations.localhost/schedule.php
and the callback function works OK, one example being http://www.myradiostations.localhost/schedule.php?callback=?&name=Northern+FM and http://www.myradiostations.localhost/schedule.php?callback=?&name=Southern+FM but what do I need to do to make it change like in these examples:
this example and this example, and to generate an error message like this if no such file exists.
I'm halfway there, just need some advice on fixing my code!
Basically, what I'm trying to do... get a JSONP to work in my HTML table which will vary the content depending on the URL in my javascript file on my page, which is:
var doFades = true;
var LocalhostRadioStations = {
Schedule : {}
};
$(document).ready(function(){
LocalhostRadioStations.Schedule.days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
LocalhostRadioStations.Schedule.Show = function () {
_s = null;
_startDate = null;
_endDate = null;
this.days = LocalhostRadioStations.Schedule.days;
_selector = '';
this.setShow = function(s) {
this._s = s;
this._startDate = new Date( parseInt(s.startminutes, 10) * 1000);
this._endDate = new Date(parseInt(s.endminutes, 10) * 1000 );
};
this.getEndDate = function(){
return this._endDate;
}
this.getStartDate = function(){
return this._startDate;
}
this._getShowDay = function (){
return this.days[this.getStartDate().getDay()];
};
this._getShowUnitsTaken = function(){
// if it's the same day
return this._getEndUnits() - this._getStartUnits();
};
this._getEndUnits = function(){
if(this.getEndDate().getHours() == 0)
{
//console.log(this._s.longname +' ends at midnight');
return 48;
}
return this.getEndDate().getMinutes() !== 0 ? (this.getEndDate().getHours() * 2) : (this.getEndDate().getHours() * 2);
};
this._getStartUnits = function(){
if(this.getStartDate().getHours() == 0)
{
return 0;
}
return this.getStartDate().getMinutes() !== 0 ? (this.getStartDate().getHours() * 2) : (this.getStartDate().getHours() * 2);
};
this.getCellPositions = function() {
return {
'start' : this.getStartDate(),
'end' : this.getEndDate(),
'colIndex' : this.getStartDate().getDay() + 2,
'startUnits' : this._getStartUnits(),
'endUnits' : this._getEndUnits(),
'unitsTaken' : this._getShowUnitsTaken()
}
};
this.pad = function(number){
return number < 10 ? '0'+number : number;
};
// return the table cell html.
this.toHtml = function () {
var d = new Date();
var units = this._getStartUnits();
var rowspan = this._getShowUnitsTaken();
var desc = this._s.description;
var name = this._s.longname;
var starttime = this.pad(this.getStartDate().getHours()) + ':' + this.pad(this.getStartDate().getMinutes());
var endtime = this.pad(this.getEndDate().getHours()) + ':' + this.pad(this.getEndDate().getMinutes());
var site = this._s.websitelink;
var cls = this.isActive() ? 'current-program' : '';
var isToday = this.getStartDate().getDay() === d.getDay() ? 'active-program' : '';
var html = '<td class="schedule-show ' + isToday + ' ' + cls + '" rowspan="' + rowspan + '" data-start="' + this.getStartDate() + '" data-end="' + this.getEndDate() + '">';
html += '<div>';
html += '' + name + '';
html += '</div>';
if(doFades)
{
html += '<div class="schedule_details clearfix" style="display:none;">';
html += '<img width="105px" height="105px" alt="' + desc + '" src="' + this._s.showimage + '">';
html += '<strong>' + name + '</strong>';
html += '<p>' + desc + '</p>';
html += '<span>' + starttime + ' - ' + endtime +'</span>';
html += '</div>';
}
html += '</td>';
return html;
};
this.setTableSelector = function(sel){
this._selector = sel;
};
// check if we should add the active class.
this.isActive = function(){
var t = new Date();
return t >= this.getStartDate() && t <= this.getEndDate();
};
};
LocalhostRadioStations.Schedule.ScheduleGen = function(){
return {
insertShow : function(show) {
var p = show.getCellPositions();
$('tr#units-' + p.startUnits).append(show.toHtml());
},
init : function (stationName){
var self = this;
// load the schedule.
$.getJSON('http://www.myradiostations.localhost/schedule.php?callback=?&name=', {
name: 'Northern FM'
}, function(json){
// loop each show and append to our giant table.
// this is well sick.
if(json.success === false)
{
$('.content-inner table').remove();
$('<div>errors</div>').appendTo('.content-inner');
}
else
{
var currentDay = '';
var day = 0;
// highlight the current time..
var d = new Date();
var weekStart = new Date();
weekStart.setDate(d.getDate()-6-(d.getDay()||7));
$.each(json.data.schedule, function(i, broadcast){
var dStart = new Date( parseInt(broadcast.startminutes, 10) * 1000);
var dEnd = new Date(parseInt(broadcast.endminutes, 10) * 1000 );
/*// transform to a show object defined above, if the show spans 2 days we create two show objects.
// IF THE SHOW STARTS/ENDS AT MIDNIGHT, DON'T SPLIT IT.
if(dStart.getHours() !== 0 && dEnd.getHours() !== 0 && dStart.getDate() != dEnd.getDate())
{
var showOne = new LocalhostRadioStations.Schedule.Show();
showOne.setShow(broadcast);
// set to midnight
showOne.getEndDate().setHours(0);
showOne.getEndDate().setMinutes(dStart.getMinutes());
// append first half of show.
self.insertShow(showOne);
// handle second half.
var showTwo = new LocalhostRadioStations.Schedule.Show();
showTwo.setShow(broadcast);
showTwo.getStartDate().setDate(showTwo.getStartDate().getDate() + 1);
showTwo.getStartDate().setHours(0);
showTwo.getStartDate().setMinutes(dEnd.getMinutes());
//console.log('2nd Half Start: ' + showTwo.getStartDate());
//console.log('2nd Half End: ' + showTwo.getEndDate());
self.insertShow(showTwo);
}
else
{*/
var show = new LocalhostRadioStations.Schedule.Show();
show.setShow(broadcast);
show.setTableSelector('table#schedule');
// add the show to the table. Thankfully the order these come out the API means they get added
// in the right place. So don't change the schedule builder code!
self.insertShow(show);
//}
});
var days = LocalhostRadioStations.Schedule.days;
// apply the current day / time classes
$('th:contains('+ days[d.getDay()]+')').addClass('active');
$('td.time').each(function(i, cell){
// get the value, convert to int.
var hours = $(cell).html().split(':')[0];
// compare the hours with now, add class if matched.
if(parseInt(hours, 10) === d.getHours())
{
$(cell).addClass('current_time');
}
});
}
if(doFades)
{
// apply events to show info fade in / out.
$('td.schedule-show').hover(function(){
$(this).find('.schedule_details').fadeIn('fast');
}, function(){
$(this).find('.schedule_details').fadeOut('fast');
});
}
});
}
};
}();
LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);
});
It should change the schedule according to the JSONP, but what do I do to fix it?
Basically, I am trying to make my own localhost version of http://radioplayer.bauerradio.com/schedule.php?callback=&name=Rock+FM and its JSON / JSONP (I am not sure exactly what type the original is, but then again the site is experimental and on a .localhost domain) for testing purposes where the content is taken from the database, and changes according to station name, e.g. http://radioplayer.bauerradio.com/schedule.php?callback=&name=Metro+Radio and http://radioplayer.bauerradio.com/schedule.php?callback=&name=Forth+One etc.
Edit: The full code for my page can be seen at http://pastebin.com/ENhR6Q9j
I'm not sure exactly what's missing, but from the code you gave so far, I made a jsfiddle:
Demo
I modified some things to make it work (mostly appending stuff), because I don't know your original HTML file. But I also made some changes based on what you say you wanted. First of all I modified your $.getJSON call to be something like:
$.getJSON('http://radioplayer.bauerradio.com/schedule.php?callback=?', {
name: stationName //stationName is from the argument passed
}, function(json){...})
Which should give back the station based on what is passed to
LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);
To make it more interesting, I also added a bit of code that reads from the url. In this case if you go to the page with a domain.htm/page?Northern FM it will read the text after the ? and put it in twittiName.
var twittiName="Rock FM"; //default station
if(window.location.search){
twittiName=window.location.search.substring(1) //or window.location.hash
}
Tried to look for other stations that might be on your publics site, but so far I could only test with "?Rock+FM". But does mean you can show the errors, which your code can handle as it is.
?Rock+FM
?Random Name
So it seems that your code mostly works but do comment if I have missed anything.

sending php array to javascript function onclick

Little problem about sending PHP array to javascript function, i did homework looked everywhere and i know its not reliable to do this, but at this moment i do not know any other way , so try to just advice me how to finish it anyway.
I got php code executing first , idea is on page load i get some data from MySQL , i filled php array with IDs from that select statement.
<?php
include('config.php');
$TicketExist = "select BetSlipID,probatip1.betslips.MatchID as GameID,
TipID,tim1.Name AS HomeTeam ,tim2.Name AS AwayTeam, UserID
from probatip1.betslips
inner join probatip1.matches matches on probatip1.betslips.MatchID = matches.MatchID
inner join probatip1.teams tim1 on matches.HomeTeamID = tim1.TeamID
inner join probatip1.teams tim2 on matches.AwayTeamID = tim2.TeamID
where UserID = 1";
$TicketResult = mysql_query($TicketExist);
$TicketNum = mysql_numrows($TicketResult);
mysql_close();
if($TicketNum != 0)
{
$s=0;
while($s < $TicketNum)
{
$GameID = mysql_result($TicketResult,$s,"GameID");
$TipID = mysql_result($TicketResult,$s,"TipID");
$ArrayIDs[$s] = $GameID;
echo "<script>window.onload=GetInfo($GameID,$TipID); </script>";
$s++;
}
}
?>
So i got it everything i want filled and wrote on my page , idea now is on user click , to call javascript to take this '$ArrayIDs' and execute code from script
Here is code im calling script
<ul>
<li
id="ConfirmButton" name="Insert" method="post"
onclick="GetAllIDs(<?php $ArrayIDs ?>)"><a>POTVRDI</a></li>
</ul>
And my script code
function GetAllIDs(Ticket) {
$("td.ID").each(function () {
var MatchID = $(this).attr('id');
var lab = "Label";
var Label = lab + MatchID;
var Final = document.getElementById(Label);
var TipID;
if (Final.innerHTML == '1') {
TipID = 1;
}
else if (Final.innerHTML == 'X') {
TipID = 2;
}
else if (Final.innerHTML == '2') {
TipID = 3;
}
else {
return;
}
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var AlreadyPlayed = false;
if (Ticket != null) {
var TicketExists = Ticket;
for (var i = 0; i < TicketExists.length; i++) {
if (TicketExists[i] == MatchID) {
AlreadyPlayed = true;
break;
}
}
}
if (http != null) {
if (AlreadyPlayed == true) {
http.open('get', 'update.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
else {
http.open('get', 'insert.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
http.send(null);
}
});
if (Ticket == null) {
alert('Tiket je napravljen');
}
else {
alert('Tiket je promenjen');
}
}
With this posted code when i am debugging code with firebug in mozzila i get that my 'Ticket' parameter that suppose to be '$ArrayIDs' is undefined.
Reason why i want to make array and send it to javascript onclick event is to check if user already placed a bet on some game , if he did i want to send all data for update and if he did not yet placed bet on some game to send data for insert in database.
So i need array and before anything just to check MatchID with all IDs in my array, so i know what to do.
Thanks all in advance for helping out
Your script could do with a bit of cleanup, but in essence you need to change
onclick="GetAllIDs(<?php $ArrayIDs ?>)">
to
onclick="GetAllIDs(<?php echo json_encode($ArrayIDs) ?>)">
I'd also reccomend not outputting
"<script>window.onload=GetInfo($GameID,$TipID); </script>";
for each row in mysql, instead create a single array of the values and create one script after the loop. Using mysql_fetch_row instead of mysql_numrows and mysql_result is probably neater.
while ($row = mysql_fetch_row($result)) {
//...do things here...
}
You need to output the array as valid JavaScript, use json_encode
GetAllIDs(<?php echo json_encode($ArrayIDs); ?>)

Categories