I am using a java script library that allows me to query information from a shoutcast server such as the current song playing, recent songs played, and etc which all works fine. This library places the data into a span element on the page based on it's defined ID.
Now, my issue is that I am trying to pass the contents of my span which is a string (current song title) to PHP so that I can use it for my Twitter library which uses PHP to post to Twitter.
<?php
// Insert your keys/tokens
$consumerKey = '';
$consumerSecret = '';
$accessToken = '';
$accessTokenSecret = '';
// Full path to twitterOAuth.php (change OAuth to your own path)
require_once('/home/soundcheck/public_html/app/twitter/auto/twitteroauth.php');
require_once('/home/soundcheck/public_html/app/twitter/auto/twitter.class');
// create new instance
$twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
$twitter->send('testing...'); // This will send testing to twitter status!
?>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="jquery.shoutcast.min.js"></script>
<!-- Current Song Played -->
<script>
// Get current song playing and load it into an element with an ID of songtitle
$.SHOUTcast({
host : 'live.soundcheck.xyz',
port : 8000,
interval : 5000,
}).stats(function(){
$('#songtitle').text(this.get('songtitle'));
$(document).ready(function() {
console.log("Document Ready!");
var content = $('#songtitle').text();
var nowplaying = ("#NowPlaying: " + content);
$.ajax({
url: 'receiver.php',
type: 'POST',
data: { data : nowplaying },
success: function (result) {
console.log(nowplaying);
}
});
});
});
</script>
<!-- Last 10 Songs Played -->
<script>
// Get last 10 songs playing and load it into an ul element
$.SHOUTcast({
host : 'live.soundcheck.xyz',
port : 8000
}).played(function(tracks){
$('ul').html('');
$.each(tracks,function(k,track){
$('ul').append('<li>'+track.title+'</li>');
});
});
</script>
</head>
<body>
This SPAN has the current song title within it upon page load which is good. I want to pass this data to my PHP above to post to twitter.
<span id="songtitle" name="songtitle"></span>
<ul></ul>
</body>
</html>
Any assistance with this will be very helpful.. I have looked at so many places with no luck and this is getting very frustrating.
Regards,
I have posted my updated code which successfully sends a jQuery variable to PHP using AJAX upon a page load.
Here is the HTML/JAVASCRIPT
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="jquery.shoutcast.min.js"></script>
<!-- Current Song Played -->
<script>
// Get current song playing and load it into an element with an ID of songtitle
$.SHOUTcast({
host : 'live.soundcheck.xyz',
port : 8000,
interval : 5000,
}).stats(function(){
$('#songtitle').text(this.get('songtitle'));
$(document).ready(function() {
console.log("Document Ready!");
var content = $('#songtitle').text();
var nowplaying = ("#NowPlaying: " + content);
console.log('TOP' + nowplaying);
$.post("receiver.php", //Required URL of the page on server
{ // Data Sending With Request To Server
name:nowplaying,
},
function(response){ // Required Callback Function
alert("Response: " + response); // "response" receives - whatever written in echo of above PHP script.
});
});
});
</script>
<!-- Last 10 Songs Played -->
<script>
// Get last 10 songs playing and load it into an ul element
$.SHOUTcast({
host : 'live.soundcheck.xyz',
port : 8000
}).played(function(tracks){
$('ul').html('');
$.each(tracks,function(k,track){
$('ul').append('<li>'+track.title+'</li>');
});
});
</script>
</head>
<body>
<span id="songtitle" name="songtitle"></span>
<ul></ul>
</body>
</html>
Here is the PHP code
<?php
// Insert your keys/tokens
$consumerKey = '';
$consumerSecret = '';
$accessToken = '';
$accessTokenSecret = '';
// Full path to twitterOAuth.php (change OAuth to your own path)
require_once('/home/soundcheck/public_html/app/twitter/auto/twitteroauth.php');
require_once('/home/soundcheck/public_html/app/twitter/auto/twitter.class');
// create new instance
$twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
if($_POST["name"])
{
$name = $_POST["name"];
// Here, you can also perform some database query operations with above values.
// echo "Welcome ". $name ."!"; // Success Message
echo $name; // Success Message
$tag = ('# http://soundcheck.xyz #radio - powered by: http://buzzzhost.com');
$twitter->send($name .= $tag); // This will send testing to twitter status!
}
?>
I hope this will help someone out there as I was searching for a long time for a good option.
Related
I have a div section. I want to reload this section every 5 seconds. How do I do this. Here is my code:
<script>
$("#send_parent_general_chat").submit(function()
{
var rec = $("#data").val();
var msg = $("#msg").val();
var dataString = 'rec='+ rec + '&msg='+ msg;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "Client/send_general_parent_chat_msg/<?php echo $per_job->id;?>",
data: dataString,
cache: false,
success: function(result){
$('#display_general_msg').html(result);
$('#send_parent_general_chat')[0].reset(); //form reset
}
});
return false;
});
</script>
<script>
$(document).ready(function(){
setInterval(function(){
// alert("===111==");
$("#display_general_msg").load('<?php echo base_url(); ?>" + "Client/refresh_general_parent_chat_msg/<?php echo $per_job->id;?>')
}, 5000);
});
</script>
I have created one more controller for refreshing the div I have used the time interval function but it is not loading, it shows this error:
Access forbidden!
You don't have permission to access the requested object. It is either read-protected or not readable by the server.
If you think this is a server error, please contact the webmaster.
Error 403
I need to refresh only the div content not the whole page.
How do I achieve this?
You can Use :
setTimeout(function()
{
Your_Function(); //this will send request again and again;
}, 5000);
Replace Your_Function with your Function Name.
Hope this will help !!
Below is an example which will update the contents in every 5 seconds using php websockets. This is a simple example, but you can use it to modify to fit for your application needs. You don't need the timeout functions on the client side here we use server sleep
Install the Workerman socket library
composer require workerman/workerman
The client side code
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
//alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:2346");
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send");
//alert("Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
//alert("Message is received..." + received_msg);
document.getElementById("demo").innerHTML = "Timestamp is updated every 5 sec " +received_msg;
};
ws.onclose = function() {
// websocket is closed.
alert("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id = "sse">
Run WebSocket
</div>
<div id="demo" style="font-size: 64px; color: red;"></div>
</body>
</html>
The Server side code
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
// Create a Websocket server
$ws_worker = new Worker("websocket://0.0.0.0:2346");
// 4 processes
$ws_worker->count = 4;
// Emitted when new connection come
$ws_worker->onConnect = function($connection)
{
echo "New connection\n";
};
// Emitted when data received
$ws_worker->onMessage = function($connection, $data)
{
// Send hello $data
while(true) {
$connection->send(time());
sleep(5); //Sleep for 5 seconds to send another message.
}
};
// Emitted when connection closed
$ws_worker->onClose = function($connection)
{
echo "Connection closed\n";
};
// Run worker
Worker::runAll();
The backend service can be started with the following command from the terminal or you can autostart on boot if you want.
$php index.php start
Here index.php is our backendnd file name.
Just start the service and load the page then you can see the timestamp is updated every 5 seconds which comes from the server side. This is a working example tested on my local machine. Try and let me know if you need any other help.
The output
you can also try below one:
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 5000);
setInterval approach will be more accurate than the setTimeout approach
// or
$(function(){ // document.ready function...
setTimeout(function(){
$('form').submit();
},5000);
});
I am trying to use AngularJS to access a PHP variable. Here is my HTML and Angular code:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="mainCtrl">
Your Link: <div> <span ng-bind="fetchLink.link"></span></div>
</div>
<script>
angular.module('myApp', [])
.controller('mainCtrl', ['$http', function($http) {
var self = this;
self.link = "";
self.newTodo = {}; //Keys (as in key: value pairs) are automatically created when declared in form
var fetchLink = function() {
return $http.get('link.php').then(
function(response) {
self.link = response.data;
}, function(errResponse) {
console.error('Error while fetching notes');
});
};
}]);
</script>
</body>
</html>
And here is my PHP:
<?php
{ $link = 0x00;
"link":[{$link}];
$link= ($link + 1);
}
?>
I am trying to use the Angular code to access the 'link' variable that has to be updated each time it is accessed by any user (a hexidecimal value that is increased by 1). This is so that each user gets a unique link which they can access and share with their friends. When i preview the html page it just says your link: without any value next to it. I also thought about using a JSON object which I believe plays nicely with Angular, but I don't know if JSON objects can be updated with each use (because they are a client-side object, not server side).
<?php
$link = "http://example.com/".time();
echo json_encode(array("link"=>$link));
?>
Use time() and something else like rand() for create unique link and return link in json using json_encode() function.
I'm getting new to "Pusher" (the websocket api) and I'm having hard time to understand how can I fetch information from the server after sending it to the channel.
For example, this is my code:
<?php
include "pusher/Pusher.php";
?>
<script src="http://js.pusher.com/2.1/pusher.min.js"></script>
<script type="text/javascript">
var pusher = new Pusher('c77c12b92e38f4156e9c');
var channel = pusher.subscribe('test-channel');
channel.bind('my-event', function(data) {
alert('An event was triggered with message: ' + data.message);
});
</script>
<?php
$pusher = new Pusher($config["pusher_key"], $config["pusher_secret"], $config["pusher_id"]);
$pusher->trigger(channel, 'my-event', array('message' => 'Test Message') );
Now, my information is sent to the server, but I don't know how to get it.
Thanks.
You can find the source for a very simple example here:
https://github.com/leggetter/pusher-examples/tree/master/php/hello-world/src
And this example working here:
http://www.leggetter.co.uk/pusher/pusher-examples/php/hello-world/src/
The problem you are seeing is that you are triggering the event on the server before the page has rendered in the browser. So, a connection has not been made by the browser to Pusher, nor has a subscription been made.
You can try something liked this,for php pusher library I used composer
<div class="notification">
</div>
<script>
var pusher = new Pusher('APP_KEY');
var notificationsChannel = pusher.subscribe('notification');
notificationsChannel.bind('new_notification', function(notification){
var message = notification.message;
toastr.success(message);
});
var sendNotification = function(){
var text = $('input.create-notification').val();
$.post('./notification/index.php', {message: text}).success(function(){
console.log('Notification sent!');
});
};
$('button.submit-notification').on('click', sendNotification);
</script>
HTML
<input class="create-notification" placeholder="Send a notification :)"/>
<button class="submit-notification">Go!</button>
Using PHP in this case
require(dirname(__FILE__).'/../vendor/autoload.php');
$app_id = 'APP_ID';
$app_key = 'APP_KEY';
$app_secret = 'APP_SECRET';
$pusher = new Pusher($app_key, $app_secret, $app_id,array( 'encrypted' => true ));
$data['message'] = $_POST['message'];
$pusher->trigger('notification', 'new_notification', $data);
For more follow this link
Recommended folder structure -
You can add following for more UX kind'a look -
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">
<script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<script src="http://js.pusher.com/2.2/pusher.min.js" type="text/javascript"></script>
I want to know if there is a way to display an external php file after clicking on a link, and then display another external file right below(not INSTEAD of) it after a different link was clicked. Here is my code.
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery- 1.2.6.pack.js"></script>
<script type="text/javascript" src="core.js"></script>
</head>
<body>
<div id="menu">
<ul>
<li id="home">DOWNLOADS</li>
<li id="tutorials">ERRORS</li>
</ul>
</div>
<div id="content">
</div>
</body>
</html>
core.js
//On load page, init the timer which check if the there are anchor changes each 300 ms
$().ready(function(){
setInterval("checkAnchor()", 100);
});
var currentAnchor = null;
//Function which chek if there are anchor changes, if there are, sends the ajax petition
function checkAnchor(){
//Check if it has changes
if(currentAnchor != document.location.hash){
currentAnchor = document.location.hash;
//if there is not anchor, the loads the default section
if(!currentAnchor)
query = "page=1";
else
{
//Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
//Create the params string
var params = splits.join('&');
var query = "page=" + page + params;
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").html(data);
$("#loading").hide();
});
}
}
downloads.php
<b>DOWNLOADS</b>
errors.php
<b>ERRORS</b>
callbacks.php
<?php
//used to simulate more waiting for load the content, remove on yor projects!
sleep(1);
//Captures the petition and load the suitable section
switch($_GET['page']){
case "errors": include 'errors.php'; break;
case "downloads": include 'downloads.php'; break;
default: include 'downloads.php'; break;
}
?>
This works perfectly except it uses a switch and I want to be able to see both errors.php and downloads.php at the same time, not only one or the other.
EDIT
Pseudo code to make it clearer:
If download is clicked show download.php only. If error is clicked show error.php only(right after downloads.php) and don't remove downloads.php or any other external file that may or may not be included on the main page already.
Any suggestions?
p.s. I've looked through many, many threads about this and that's why I can't post all the code I've tried (sorry I can't include links either, last time my question was downvoted for doing that...>:/) so I can promise I've done my homework.
p.s.s. If you think this deserves a down vote please be kind enough to explain why. I'm open to criticism but just thumbs down is not helpful at all.
EDIT:
Updated core.js to
$(document).ready(function(){
$('#menu li a').click(function() {
var currentAnchor = $(this).attr('href');
if(!currentAnchor)
var query = "page=1";
else
{
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
//Create the params string
var params = splits.join('&');
var query = "page=" + page + params;
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").html(data);
$("#loading").hide();
});
return false;
});
});
EDIT:
[The confusing parts removed here]
--
EDIT:
core.js (revised)
//On load page, init the timer which check if the there are anchor changes each 300 ms
$(document).ready(function(){
$('#menu li a').click(function() {
var currentAnchor = $(this).attr('href');
if(!currentAnchor)
var query = "page=1";
else
{
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
//Create the params string
var params = splits.join('&');
var query = "page=" + page + params;
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").html(data);
$("#loading").hide();
});
return false;
});
});
--
EDIT:
This one will "append" data [coming from either downloads or errors] to the existing content.
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
Hope this helps.
If you want to show both pages at once, in your callbacks.php page you should be able to do something like this (all I did was remove the switch statement):
include 'errors.php';
include 'downloads.php';
Any reason why you can't do this?
I have a flash player embedded on page page.php?user=john using swfobject. The player calls the xml file content.php to get the results. I'm trying to get the user name from the url id. and fetch results based on that. I can get the username on page.php by doing $_GET['user'], but how can i pass that to content.php. Having read allot of articles online, i did the following,
I'm embedding the flash on page.php using swfobject like this
<script type="text/javascript">
var flashvars = {user:"<?php $_GET[user] ?>"};
var so = new SWFObject("<?php echo $index->CFG['site']['url'];?>preview2.swf", "sotester", "1000", "400", "8", "#000000", flashvars);
so.addParam("allowFullScreen", "true");
so.addParam("scale", "noscale");
so.addParam("menu", "false");
so.write("flashcontent");
</script>
In my AS2 file end of the file looks like
var paramList:Object = this.root.loaderInfo.parameters;
trace(paramList["user"])
xmlData = new XML();
xmlData.ignoreWhite = true;
xmlData.onLoad = loadXML;
xmlData.load("contentp.php?user=" + user);
So basically, i'm trying to pass $_GET['user'] from page.php to my swf file which calls content.php. Then swf would pass that value to content.php. I believe i provided you with all the information needed. Any help would be appreciated.
PS: right now as i have it, looking at console, i see Request URL:http://www.domain.com/content.php?user=undefined. So it's coming as undefined.
Embed like so with SWFObject v2.2
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
function loaded( ){
var flashvars = { };
flashvars.user = "<?php $_GET[user] ?>";
var params = {};
params.menu = "false";
params.quality = "high";
params.bgcolor = "#869ca7";
params.allowFullScreen = "true";
params.scale = "noscale";
var attributes = {};
attributes.id = "myFlashObject";
attributes.name = "myFlashObject";
attributes.align = "middle";
attributes.allowFullScreen = "true";
attributes.scale = "noscale";
var tmp = "expressInstall.swf";
var version = "8.0.0";
var width = "1000";
var height = "400";
var container = "sotester"
// verify the URL is correct
var flashObj = "<?php echo $index->CFG['site']['url'];?>preview2.swf";
swfobject.embedSWF(flashObj, container, width, height, version, tmp, flashvars, params, attributes);
}
</script>
</head>
<body onLoad="loaded()">
<div id="sotester">Loading Content... put alt. content here</div>
</body>
</html>
// in actionscript 3
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
var user: String = String( paramObj[user] );
trace( user );
[EDIT]
// in actionscript 2
// _level0 will have the global flashvar on it
// trace(user);
REFERENCE
There are a few ways to go about this. If you want to insert flashvars into an embedded swf, you can simply use the flashvar property on the object or embed tags:
<param name="flashvars" value="uId=<?= $_GET['user'] ?>" />
Another way to do this is to have Flash retrieve the userId itself. Because flash can call javascript, you can actually do the same thing like this:
if( ExternalInterface.available ) {
ExternalInterface.call( "function() { return window.location.href; }" );
}
This will actually return the full URL string to flash itself, wherein you can do all the substring operations you desire.