Repeating and Changing php values for my Music Player - php

I would like to know how i can change or repeat certain elements in php.
Right now i am using a script to fetch what song is playing from a shout-cast info page.
And in JQuery i have a player with a playlist that switches stream.
Now the only thing it does right now is just switch to the stream and not display anything.
So how would i go about on calling an php part inside jQuery?
Gosh, i really hope im being clear enough in my explanation.
For those who are able to help me
What parts of my code do you want me to display?
i wil then go ahead and paste that for you Right away! :)
Greets,
Kus.
Code for Arjan:
JQUery
$(document).ready(function(){
var myPlaylist = new jPlayerPlaylist({
jPlayer: "#jquery_jplayer",
cssSelectorAncestor: "#jp_container"
}, [
{
title: "test",
mp3: "http://178.156.201.212:8018/;stream/1",
<?php
$host = "178.156.201.212"; // ip or url of shoutcast server
$port = "8018";
?>
},
{
title: "test2",
mp3: "http://stream1.slowradio.com/;stream/1",
<?php
$host = "http://stream1.slowradio.com"; // ip or url of shoutcast server
$port = "8008";
?>
},
{
title: "test3",
mp3: "http://108.61.73.119:8022/;stream/1",
<?php
$host = "108.61.73.119"; // ip or url of shoutcast server
$port = "8022";
?>
},
], {
swfPath: "js",
supplied: "oga, mp3",
wmode: "window"
});
$("#jquery_jplayer").bind($.jPlayer.event.play, function(event) {
//$('#fetch').html(jPlayerPlaylist.playlist[jPlayerPlaylist.current].title);
$('#fetch').empty();
$('#fetch').append(myPlaylist.playlist[myPlaylist.current].title);
});
});
PHP
<?php
$host = "178.156.201.212"; // ip or url of shoutcast server
$port = "8000"; // port of shoutcast server
$fp = #fsockopen("$host", $port, $errno, $errstr, 30);
if($fp)
{
fputs($fp,"GET /7.html HTTP/1.0\r\nUser-Agent: GET SEVEN (Mozilla Compatible)\r\n\r\n");
while(!feof($fp))
{
$data .= fgets($fp, 1000);
}
fclose($fp);
$data = ereg_replace(".*<body>", "", $data);
$data = ereg_replace("</body>.*", ",", $data);
$data_array = explode(",",$data);
$listeners = $data_array[0];
$status = $data_array[1];
$peak_listeners = $data_array[2];
$maximum_listeners = $data_array[3];
$unique_listeners = $data_array[4];
$bitrate = $data_array[5];
$track = $data_array[6];
}
$title = chop($track);
$select = explode(" - ",$title);
$artist = chop($select[0]);
$title = chop($select[1]);
?>
<?php
if($status == 1)
{
echo $artist. " - " .$title;
}
else
{
print 'document.getElementById("title").innerHTML = "Offline";';
}
?>

Calling PHP inside jquery is done by this code:
$.ajax({
type: "GET",
url: 'this_file.php',
success: function(html) {
var data = html.split(' ');
var host = data[0];
var port = data[1];
}
});
Your PHP would be:
if ( isset($_GET['update']) ) {
die($host.' '.$port);
}
This code loads html from the php file and puts it in the HTML body tag. Ofcourse you can change body to any element.
For more specific help, post some of your PHP and jQuery code please.
Edit: Full documentation on: http://api.jquery.com/jQuery.ajax/

Maybe this works:
<?php
$host = "http://stream1.slowradio.com"; // ip or url of shoutcast server
$port = "8008";
?>
Has to be
<?php
$host = "http://stream1.slowradio.com"; // ip or url of shoutcast server
$port = "8008";
echo 'host: '.$host;
echo 'port: '.$port;
?>
Next time, make sure you give your code right away. That saves a lot of time and downvotes I guess.

Related

Simple example to populate database using JSON, XMLHttpRequest, and PHP file_get_contents("php://input") not working

Now I know this has been asked before, but none of the responses have offered up insight for me to date;
I have an HTML page with the script below (ultimately I shall use this script to suck data out of an app), basically testing to send some data in JSON format to a PHP page which is to populate a MYSQL database with the record.
My problem is that I get no table record update. Nada.
This has been messing me around for a few weeks now; the closest I have got is:
Send JSON data from Javascript to PHP?
My limited success to date has been to grab data from a .json file and update the database that way on a php page. So, the JSON is fine in the script, and the connection to the database is ok. I just don't seem to be able to pass it from an html page to php and populate the db. I cannot understand why this has to be that difficult.
Any suggestions/pointers would be appreciated (I need to keep this simple as I am a relative novice). Thank you in advance.
HTML page script
<script>
var jsonQuizData = {};
var qID = '9';
var learnersName = 'Bart Bundy';
var learnersEmail = 'bbundy#blue.com';
var quizName = 'SomeQuiz99';
var quizScore = '33%';
var result1 = 'Some blob data goes in here?';
var dbString, request;
jsonQuizData = '{ "id":qID, usersName":learnersName, "usersEmail":learnersEmail, "quizTitle":quizName, "qScore":quizScore, "Output1":result1 }';
dbString = JSON.stringify(jsonQuizData);
request = new XMLHttpRequest();
request.open("POST", "process.php", true);
request.setRequestHeader("Content-Type", "application/json");
request.send(dbString);
</script>
process.PHP page
<?php
header("Content-Type: application/json; charset=UTF-8");
//Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection etc. performed here
$data = json_decode(file_get_contents("php://input"));
$id = $data['id'];
$name = $data['usersName'];
$email = $data['usersEmail'];
$qtitle = $data['quizTitle'];
$result1 = $data['Output1'];
$qScore = $data['score'];
//insert into mysql table
$sql = "INSERT INTO quiz01(quiz_id, quiz_title, fName, eMail, quiz_score, q1_answer)
VALUES('$id', '$qtitle', '$name', '$email', '$qScore', '$result1')";
if(!mysqli_query($conn,$sql))
{
die('Error : ' . mysqli_error($conn));
}
else
{
echo "Data inserted successfully";
}
//Close connection
/?>
.... Brick wall time
Your stringify portion in your sample is not right, it's already a string, so I think you mean to do:
var jsonQuizData = {};
var qID = '9';
var learnersName = 'Bart Bundy';
var learnersEmail = 'bbundy#blue.com';
var quizName = 'SomeQuiz99';
var quizScore = '33%';
var result1 = 'Some blob data goes in here?';
var dbString, request;
// Here you have to stringify the data object, not a string of the data object.
jsonQuizData = JSON.stringify({"id":qID, "usersName":learnersName, "usersEmail":learnersEmail, "quizTitle":quizName, "qScore":quizScore, "Output1":result1});
request = new XMLHttpRequest();
request.open("POST", "process.php", true);
// Send the regular form header
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
// Now when it sends, it should send it properly as a post
request.send('json='+jsonQuizData);
Then in the PHP, you don't need to send the line:
header("Content-Type: application/json; charset=UTF-8");
and you can alter this line:
$data = json_decode(file_get_contents("php://input"));
to just:
$data = json_decode($_POST['json'],true);
It should now all be in the regular $_POST, then you need to bind parameters when you insert.
Update:
Right, got it working doing the following:
HTML page
<script>
var jsonQuizData = {};
var learnersName = 'Professor T';
var learnersEmail = 'prof.teerlink#pooh.com';
var quizName = 'TidlyWinks101w';
var quizScore = '100%';
var result1 = 'Balls said the crow';
var dbString, request;
jsonQuizData = JSON.stringify({"quizTitle":quizName, "usersName":learnersName, "usersEmail":learnersEmail, "qScore":quizScore, "Output1":result1 });
$(document).ready(function()
{
$("button").click(function()
{
$.post("working01.php", 'json='+jsonQuizData,
function(data,status)
{
//alert("Data: " + data + "\nStatus: " + status);
document.getElementById("AV1").innerHTML = data;
});
});
});
</script>
And PHP page...
<?php
//Set up connections to database etc...
if (isset($_POST['json']))
{
$str = $_POST['json'];
$contents = json_decode($str);
$qtitle = $contents->quizTitle;
$name = $contents->usersName;
$email = $contents->usersEmail;
$qScore = $contents->qScore;
$result1 = $contents->Output1;
}
$sql = "INSERT INTO quiz01(quiz_title, fName, eMail, quiz_score, q1_answer)
VALUES('$qtitle', '$name', '$email', '$qScore', '$result1')";
if(!mysqli_query($conn,$sql))
{
die('Error : ' . mysqli_error($conn));
}
else
{
echo "Data inserted successfully";
}
//Close connections
?>
But so want to do it utilising the XMLHttpRequest() object and send the json.
as per Rasclatt. Thanks

(F)write in a html file to the visitor's geo-coordinates using a post inside a get

I'm working with the coordinates. I don't want to use a GeoIP database. So I tried first to get the coordinates, then send them with a post to a php file which write them in an html file.
This is the index.html code:
<p> Hello. </p>
<script type="text/javascript">
$.get("http://ipinfo.io", function (response) {
var ip = response.ip;
var city = response.city;
var region = response.region;
var details = JSON.stringify(response, null, 4);
$.ajax({
type: "POST",
url: 'write.php',
data: '&ip='+ ip + '&city=' + city + '&region=' + region + '&details=' + details,
success: function (data) {
alert("Sent!");
},
error: function(jqXHR, text, error){
alert("Error: not sent.");
}
});
}, "jsonp");
this is the write.php code:
<?php
$ip = $_POST['ip'];
$city = $_POST['city'];
$region = $_POST['region'];
$details = $_POST['details'];
$fh = fopen('lol.html', 'a') or die("can't open file");
fwrite($fh,'IP: $ip ;');
fwrite($fh,'Details: $details');
fclose($fh);
echo "Created";
?>
If I host and open index.html it alert "Sent!". But then, when I open lol.html I see the string: IP: $ip ;Details: $details
Why? What am I doing wrong?
This is because you are trying to use variables inside single quotes ' when writing data; so the variables aren't getting evaluated but instead being treated as literals.
So, try this instead:
<?php
// Parse input
$ip = isset($_POST['ip']) ? $_POST['ip'] : '';
$city = isset($_POST['city']) ? $_POST['city'] : '';
$region = isset($_POST['region']) ? $_POST['region'] : '';
$details = isset($_POST['details']) ? $_POST['details'] : '';
// Open file for writing
$fh = #fopen('lol.html', 'a');
if (!$fh) exit('Failed to open file for writing')
// Write data
fwrite($fh, "IP: $ip\r\n");
fwrite($fh, "Details: $details");
// Finished
fclose($fh);
echo "Created";
?>
Update
Based on your comment, I have optimised this script into the following, try this out:
index.html (or what ever .html file)
<p> Hello. </p>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$.getJSON('http://ipinfo.io', function(response) {
$.post('write.php', { response: JSON.stringify(response) })
.done(function(result) {
alert(result);
});
});
</script>
write.php
<?php
// Parse input
$response = isset($_POST['response']) ? $_POST['response'] : '';
// Decode input
$response = #json_decode($response, true);
if (!$response) {
exit('Invalid input.');
}
// Open file for writing
$fh = #fopen('lol.html', 'a');
if (!$fh) {
exit('Failed to open file for writing.');
}
// Write data
$result = '<pre>';
foreach ($response as $key => $value) {
$result .= "$key = $value\r\n";
}
$result .= '</pre>';
fwrite($fh, $result);
// Finished
fclose($fh);
echo "Created";
?>
The resulting lol.html file will now look like this (when index.html is executed):
<pre>ip = 90.152.2.38
hostname = host90-152-2-38.ipv4.regusnet.com
city = St Albans
region = England
country = GB
loc = 51.8379,-0.4399
org = AS8220 COLT Technology Services Group Limited
postal = AL3
</pre>
And if you were to open this lol.html file in browser, it will render like this:
Is this what you are after?

AngularJS $http.get() not working

I am using ZF2 and AngularJS to create a Quiz Application. When I am running the code, No error occurs, and no result.
(function(angular) {
function MainController($scope,$http) {
$scope.question = function(id)
{
var site = "http://localhost/zf/public/interviewer";
var page = "/jsonquestion/"+id;
alert(site + page);
var reqQuestion = $http.get(site + page);
reqQuestion.success(function(data, status, headers, config) {$scope.question.questions = data;});
reqQuestion.error(function(data, status, headers, config){alert("AJAX failed!");});
alert(data);
}
};
angular.module("app", []).controller("MainController", ["$scope", MainController]);
})(angular);
My zend part is
public function jsonquestionAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
$questions = $this->getQuestionsTable()->getQuestions($id);
$result = json_encode($questions);
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, $result);
fclose($myfile);
echo $result;
return $result;
}
When I m calling http://localhost/zf/public/interviewer/jsonquestion/1 from browser its working and returning Json
You aren't injecting $http to your controller
Try changing to this.
angular.module("app", []).controller("MainController", ["$scope", "$http", MainController]);
Shot in the dark. Your zend function is called jsonquestionAction, but your page call is made to jsonquestion.
Maybe changing this:
var page = "/jsonquestion/"+id;
To this:
var page = "/jsonquestionAction/"+id;
Will help.

ajax image if port open, alternate image if not open

So I'm trying to create a custom script for a website of mine, and I'm looking at doing a status script. now I've done some research however I have scrapped what I have until I can find something that works better.
I am currently using fopen to check if a port is open, however it slows the page load time down considerably, I was wondering if there is a way to do this is jquery and ajax. allow the page to load first, then present an image if the port was open, and an alternate image if it was closed or inaccessible.
I've seen it done before, I just can't seem to find any documentation on this.
Load the page, send an ajax request to your page to check if it's open or not.
$.getJSON('checkstatus.php', {
port: 8070
}, function (data) {
if (data.status === 'on') {
$('#img').attr('src', 'on.png');
} else {
$('#img').attr('src', 'off.png');
}
});
<?php
......code.....
header('content-type: application/json');
echo json_encode(array('status'=>get_port_status($_GET['port'])));
edit :
//checkstatus.php
<?php
$host = $_GET['host'];
$ports = array(PORT 1, PORT 2, PORT 3, PORT 4, PORT 5, PORT 6, PORT 7, PORT 8, PORT 9);
$status = array();
foreach($ports as $port) {
$connection = #fsockopen($host, $port);
if (is_resource($connection)) {
$[$port] = 'on';
fclose($connection);
} else {
$[$port] = 'off';
}
}
header('content-type: application/json');
echo json_encode($status);
?>
///status.html
<table id="portStatus">
<tbody></tbody>
</table>
<script>
$(function () {
var table = $('#portStatus tbody');
var hosts = ['host1.com', 'host2.com'];
for (var i = 0; i < hosts.length; ++i) {
var host = hosts[i];
$.getJSON('checkstatus.php', {
host: host
}, function (data) {
var tr = $('<tr/>');
tr.append($('td').html(host)); //this appends the hostname to the td;
for (var port in data) {
tr.append($('<td><img src="' + (data[port] === 'on' ? 'accept.png' : 'error.png') + '"></td>');
}
table.append(tr);
});
}
});
</script>
This should give you a basic idea, try it and modify it.
Note, the javascript part uses jQuery.

Is there any reason why this cron job wouldn't be working

EDIT: Cron line: /usr/bin/php /usr/local/yy/yy/yy/webspace/httpdocs/test.mysite.ie/test.php > /dev/null 2>&1
I have written a script that functions as it should when i navigate to it in the browser. This is my first time trying to use a cron job so i'm not overly familiar with how they work. The script is below. As i said, the script works as it should if i navigate to the url in a web browser.
test.php
<script src="jquery.min.js"></script>
<script>
//SET UP JS VARIABLES
var allMatchedNumbers = new Array();
var matchedthingyNumbers;
var matchedthingyPlus1Numbers;
var matchedthingyPlus2Numbers;
var winningthingyNumbers = new Array();
var winningBonusNumber;
var winningthingyPlus1Numbers = new Array();
var winningPlus1BonusNumber;
var winningthingyPlus2Numbers = new Array();
var winningPlus2BonusNumber;
var thingyList;
var thingyListItems;
var thingyPlus1List;
var thingyPlus1ListItems;
var thingyPlus2List;
var thingyPlus2ListItems;
var userNumbers = new Array();
var displayCounter = 1;
var drawDate;
var thingyNumbers;
var thingyBonus;
var thingyPlus1;
var thingyPlus1Bonus;
var thingyPlus2;
var thingyPlus2Bonus;
//GET RESULTS & DATE FOR thingy, PLUS1, PLUS2 FROM THE DOM OBJECT ONLY
$(document).ready(function fetchResults(){
$.ajax({
url: "scrape_page.php",
success: function(data) {
}
});
$.ajax({
url: "latest_results.txt",
success: function(data) {
var dom = $(data);
//GET thingy DATE
drawDate = dom.find('.date-heading.fooRegular').contents().first().text();
//GET thingy NUMBERS
thingyNumbers = dom.find('.result-block').eq(0).find('.thingy-winning-numbers');
thingyBonus = dom.find('.result-block').eq(0).find('.thingy-bonus');
thingyPlus1 = dom.find('.result-block').eq(1).find('.thingy-winning-numbers');
thingyPlus1Bonus = dom.find('.result-block').eq(1).find('.thingy-bonus');
thingyPlus2 = dom.find('.result-block').eq(2).find('.thingy-winning-numbers');
thingyPlus2Bonus = dom.find('.result-block').eq(2).find('.thingy-bonus');
populateWinningNumbers();
}
});
});
//PUT WINNING NUMBERS IN ARRAY
function populateWinningNumbers() {
//MAIN thingy NUMBERS
thingyList = thingyNumbers;
thingyListItems = thingyList.find('li');
thingyPlus1List = thingyPlus1;
thingyPlus1ListItems = thingyPlus1List.find('li');
thingyPlus2List = thingyPlus2;
thingyPlus2ListItems = thingyPlus2List.find('li');
thingyListItems.each(function(index) {
winningthingyNumbers[index] = parseInt($(this).text());
});
//winningBonusNumber = parseInt($('#mainthingyBonus').find('li').text());
winningBonusNumber = parseInt($(thingyBonus).find('li').text());
winningthingyNumbers.push(winningBonusNumber);
//thingy PLUS NUMBERS
thingyPlus1ListItems.each(function(index) {
winningthingyPlus1Numbers[index] = parseInt($(this).text());
});
winningPlus1BonusNumber = parseInt($(thingyPlus1Bonus).find('li').text());
winningthingyPlus1Numbers.push(winningPlus1BonusNumber);
//PLUS 2
thingyPlus2ListItems.each(function(index) {
winningthingyPlus2Numbers[index] = parseInt($(this).text());
});
winningPlus2BonusNumber = parseInt($(thingyPlus1Bonus).find('li').text());
winningthingyPlus2Numbers.push(winningPlus2BonusNumber);
postDataToDB();
}
//POST OFFICIAL thingy NUMBERS TO DATABASE
function postDataToDB() {
$.ajax({
url: "postToDB.php",
type: "post",
data: {thingyNums:winningthingyNumbers, thingyPlus1Nums: winningthingyPlus1Numbers, thingyPlus2Nums: winningthingyPlus2Numbers, drawDate:drawDate},
// callback handler that will be called on success
success: function (data) {
}
});
}
</script>
scrape_page.php
<?php
include 'simple_html_dom.php';
$html = file_get_html('http://www.site.com');
$file = 'latest_results.txt';
file_put_contents($file, $html);
?>
postToDB.php
<?php
$winningNums = $_POST['thingyNums'];
$winningPlus1Nums = $_POST['thingyPlus1Nums'];
$winningPlus2Nums = $_POST['thingyPlus2Nums'];
$drawDate = $_POST['drawDate'];
$thingyToSave = implode(',', $winningNums);
$plus1ToSave = implode(',', $winningPlus1Nums);
$plus2ToSave = implode(',', $winningPlus2Nums);
//CONNECT TO REMOTE
$con = mysql_connect("172.xx.xx.xx","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//SELECT thingy DB
mysql_select_db("App", $con);
//CHECK IF DATE ALREADY EXISTS IN DB
$date_check = mysql_query("SELECT drawDate FROM thingy WHERE drawDate='$drawDate'");
$do_date_check = mysql_num_rows($date_check);
if($do_date_check > 0){
//DATE ALREADY IN DB
die("Entries already exist");
} else {
mysql_query("INSERT INTO thingy (drawDate) VALUES ('$drawDate')");
mysql_query("UPDATE thingy SET thingyRes = '$thingyToSave' WHERE drawDate = '$drawDate'");
mysql_query("UPDATE thingy SET thingyPlus1Res = '$plus1ToSave' WHERE drawDate = '$drawDate'");
mysql_query("UPDATE thingy SET thingyPlus2Res = '$plus2ToSave' WHERE drawDate = '$drawDate'");
echo "Success";
}
mysql_close($con);
?>
The script you're trying to run contains Javascript - which is executed in a browser. Cron will execute the PHP script on the server, and send the output nowhere (as you're directing it to /dev/null).
There's nothing in that scenario that will interpret and execute the Javascript.
You need to essentially port the logic in your Javascript (which makes requests to the two related PHP scripts) to PHP. (You could possibly run some server side javascript interpreter/php extension, but in this case that would seem a bit crazy.)
If you're calling test.php via wget or similar, that tool php doesn't have a JavaScript engine in it. So naturally any JavaScript-dependent features of the page won't run.
There are tools that will load the page and execute the JavaScript therein. They're called "headless" browsers. For example, PhantomJS, which is a headless browser based on WebKit with a JavaScript engine in it. There are also headless versions of Firefox and such.
You'd have your web server running as normal and point the headless browser at the URL for the page, which would both trigger the PHP (just as though the page had been requested by a browser) and process the client-side JavaScript in the page.

Categories