php/ajax vote up down - php

and sry in advance because i'm new here and i'm completly new in php/ajax coding.
I use a free script (Ajax vote up/down) from this site
I have a simple php page for my shoutcast server to show the song played
<?php
require_once "inc.php";
$array = array(); // Let's store our shoutcast variables into an array.
$array['host'] = "xxx.xxx.xx.xxx"; // Your Shoutcast Host
$array['port'] = "xxxx"; // Your Shoutcast Port
$array['extra'] = "/admin.cgi?sid=1&mode=viewxml&page=1"; // The bit that follows in the url to access the xml of the stats
$array['user'] = "xxxxx"; // Admin username (Default is usually "admin")
$array['password'] = "xxxxxxx"; // Admin Password
$radioStats = new radioStats( $array['host'], $array['port'], $array['extra'], $array['user'], $array['password']);
$returnStats = $radioStats->returnStats();
$song = $returnStats['currentSong'];
?>
<div align="center">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<link href="votingfiles/voting.css" rel="stylesheet" type="text/css" />
<script src="votingfiles/voting.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
setInterval(function(){cache_clear()},54000);
});
function cache_clear()
{
window.location.reload(true);
}
</script>
<div id="radio_stats">
<?php
if( $returnStats['serverStatus'] != 0 ) {
?>
<?php
if( $returnStats['currentSong'] != "" ) {
echo $returnStats['currentSong'];
} else {
echo "Undefined";
}
?></div>
<br /><br />
<div class="vot_updown1" id="vt_$song"></div>
<?php
}
else {
?>
This radio server appears to be offline.
<?php
}
?>
My problem is :
All request Php/ajax/mysql works but actually when i make a vote, it's registered in the db like :
vt_$song 1 0
How can i do to get the real name of the song like the original php request do :
echo $returnStats['currentSong']; or echo $song;
To register in the db like :
vt_Kidd Guti-Step Everything 1 0 (or any other song played)
Example : [HERE]
Thanks in advance for any help.

In this line the $song is not parsed as PHP so the literal text $song is showing:
<div class="vot_updown1" id="vt_$song"></div>
Try:
<div class="vot_updown1" id="vt_<?php echo $song; ?>"></div>

Related

Data from PHP-include not shown in parent when using variable variable

I experience the following problem. By clicking the button in start.php the file fakten02.php is called with the parameter DE2 . This parameter is used as a variable variable to convert the array $DE2 into a string and display it in start.php. Unfortunately, this does not happen. If fakten02.php is directly called with the parameter, it works. If the parameter is hard-coded in fakten02.php the content of $land is shown in start.php. However, if $land is filled from $text2, $land is empty in start.php.
start.php
<!DOCTYPE HTML>
<html>
<head>
<title>Start</title>
</head>
<body>
<div id="spalten">
<button type="submit" id="land1">Klicken</button>
</div>
<?php
include("fakten02.php");
print_r($land);
?>
</body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#spalten > button").click(function() {
$.get("fakten02.php", {sland:'DE2'});
<?php echo $land; ?>;
})
})
</script>
</html>
fakten02.php
<?php
$parameter = $_GET['sland'];
//$parameter=$_REQUEST['sland'];
//print_r($_REQUEST);
$DE2 = array("ich", "bin", "groß");
//echo "Text $text";
//$text2 = "$".$parameter;
$param2 = $parameter;
$text2 =$$param2;
for ($i=0; $i < count($text2); $i++) {
$land.="$text2[$i] "; //Does not work
$land.= "daten[$i] = '$DE2[$i]';"; //Returns expected data
}
//print( "aus 2 $land, $param2");
?>
I don't understand this behaviour. I did a lot of searching here and on Google, but I could not find a similar problem. How can I resolve this issue?

Instagram Fetch Amount of Images API

A friend of mine wrote this script, displaying the 20 most recent instagram images, and I was wondering, how can I change the amount of images it grabs to maybe, 6?
<?PHP
$token = 'token';
$username = 'username';
$userInfo = json_decode(file_get_contents('https://api.instagram.com/v1/users/search?q='.$username.'&access_token='.$token));
if($userInfo->meta->code==200){
$photoData = json_decode(file_get_contents('https://api.instagram.com/v1/users/'.$userInfo->data[0]->id.'/media/recent/?access_token='.$token));
if($photoData->meta->code==200){ ?>
<?PHP foreach($photoData->data as $img){
echo '<img src="'.$img->images->thumbnail->url.'">';
} ?>
<?PHP } // If
} // If
?>
Now, the script is functional now because I've been working on it all day, but I'm not sure how to change how many it sends out.
Also, would any of you know how to style this? I already have the CSS done for it, but whenever I try it, it doesn't work correctly.
And, would you know how to get the description of the photo using the API?
Thank you in advance :-)
You need to use Instagram's count= url parameter when requesting data from their endpoints.
For example: https://api.instagram.com/v1/users/search?count=6
Or in your code:
<?PHP
$token = 'token';
$username = 'username';
$userInfo = json_decode(file_get_contents('https://api.instagram.com/v1/users/search?count=6&q='.$username.'&access_token='.$token));
if($userInfo->meta->code==200){
$photoData = json_decode(file_get_contents('https://api.instagram.com/v1/users/'.$userInfo->data[0]->id.'/media/recent/?count=6&access_token='.$token));
if($photoData->meta->code==200){ ?>
<?PHP foreach($photoData->data as $img){
echo '<img src="'.$img->images->thumbnail->url.'">';
} ?>
<?PHP } // If
} // If
?>
Pseudo example for styling. You'll need to figure out the css styles for that, but shouldn't be to difficult.
<div class='myBorder'>
<img url=$img->link />
<div class='myCaption'>$img->caption->text</div>
</div>
To get the description
if (isset($img->caption)) {
if (get_magic_quotes_gpc()) {
$title = stripslashes($img->caption->text);
} else {
$title = $img->caption->text;
}
}

reading Json from PHP with javaScript

My PHP code is:
<?php
class Sample{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) ){
echo "Starting to read ";
$req = $_GET[ 'request' ];
$result = json_decode($req);
if( $result->request == "Sample" ){
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}else{
echo "Not Supported";
}
}
?>
Is there anything wrong
I want to send a JSON to this php and read the JSON that it returns using java script , I can't figure out how to use JavaScript in this , because php creates an html file how Can I use $_getJson and functions like that to make this happen ?!
I tried using
$.getJSON('server.php',request={'request': 'Sample'}) )
but php can't read this input or it's wrong somehow
thank you
try this out. It uses jQuery to load contents output from a server URL
<!DOCTYPE html>
<html>
<head>
<title>AJAX Load Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(event) {
$('#responce').load('php_code.php?request={"request":"Sample"}');
});
});
</script>
</head>
<body>
<p>Click on the button to load results from php_code.php:</p>
<div id="responce" style="background-color:yellow;padding:5px 15px">
Waiting...
</div>
<input type="button" id="button" value="Load Data" />
</body>
</html>
Code below is an amended version of your code. Store in a file called php_code.php, store in the same directory as the above and test away.
<?php
class Sample
{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) )
{
echo "Starting to read ";
$req = $_GET['request'];
$result = json_decode($req);
if( isset($result->request) && $result->request == "Sample" )
{
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}
else
{
echo "Not Supported";
}
}
Let me know how you get on
It would be as simple as:
$.getJSON('/path/to/php/server.php',
{request: JSON.stringify({request: 'Sample'})}).done(function (data) {
console.log(data);
});
You can either include this in <script> tags or in an included JavaScript file to use whenever you need it.
You're on the right path; PHP outputs a result and you use AJAX to get that result. When you view it in a browser, it'll naturally show you an HTML result due to your browser's interpretation of the JSON data.
To get that data into JavaScript, use jQuery.get():
$.get('output.html', function(data) {
var importedData = data;
console.log('Shiny daya: ' + importedData);
});

I want to create several static html pages from my PHP content using a wwwcopy script

Edited on 7/16/2012
I need to revisit this problem. I have been using dynamic pages for some time with cached PHP on it for some time. Most of my page is cached, but the meta information is not. As i have explained in my post below, i need to reduce/remove requests going to my local MySQL database. I am getting 500 internal server errors because of the requests that are coming. I have been exploring Jquery/Ajax to pull data from the database into a xml page and have the site request data from that, which is working, but i am still running into the problem to move the content from the body, into the meta so facebook, and search engines can see the dynamic content. Here is what i need........
I need a solution that will either create about 1500 static pages by looking at
http://chennaichristianradio.com/PHP/web/songinfo.php?songID= and start with 0 and count up to 1500 (http://chennaichristianradio.com/PHP/web/songinfo.php?songID=0 to http://chennaichristianradio.com/PHP/web/songinfo.php?songID=1500). That would work for me but not preferred.
The second option would be to have a PHP cache option that will cache the entire page including the meta data that is created from PHP.
The third option (my preferred option) is to be able to create meta data from either ajax/Jquery created data in the body, or from the xml page itself.
Thank you for revisiting this request. Please read my original posts from earlier this year. here is some of my current code that i am using and links for examples.....
Current PHP used to create the dynamic pages...
<title>Chennai Christian Radio</title>
<meta property="og:title" content="<?php echo $song->title; ?> by <?php echo $song->artist; ?> - Found on Chennai Christian Radio"/>
<meta property="og:type" content="song"/>
<meta property="og:url" content="http://chennaichristianradio.com/PHP/web/songinfo.php?songID=<?php echo $song->ID; ?>"/>
<meta property="og:image" content="<?php echo $song->picture; ?>"/>
<meta property="og:site_name" content="Chennai Christian Radio"/>
<meta property="fb:admins" content="1013572426"/>
<?php
$cachefile = "cache/".$reqfilename.$cache_folder.md5($_SERVER['REQUEST_URI']);
$cachetime = 11000 * 60; // 110000 minutes
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && (time() - $cachetime
< filemtime($cachefile)))
{
include($cachefile);
echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))."
-->n";
exit;
}
ob_start(); // start the output buffer
?>
<div id="fbbutton">
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=170819122971839";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-send="false" data-layout="box_count" data-width="50" data-show-faces="false"></div>
</div>
<div id="songinfo">
<!-- BEGIN:AlbumArt -->
<?php if(SHOW_PICTURES && !empty($song->picture)) : ?> <img class="picture" id="picture" onload="showPicture(this, <?php echo SHOW_PICTURES; ?>)" src="<?php echo $song->picture; ?>" alt="" border=0 width="142" height="142" /></a><?php endif; ?>
</div>
<!-- Song Info -->
<div id="wrapper">
<div id="title"><?php echo $song->title; ?></div>
<div id="artist"><?php echo $song->artist; ?></div>
<div id="album"><?php echo $song->album; ?></div>
<div id="duration"><?php echo $song->durationDisplay; ?></div>
<div id="year"><?php echo $song->albumyear; ?></div>
</div>
<div id="lyrics"><pre><?php if (!empty($song->lyrics)) : ?><dd class="broad"><pre><?php echo $song->lyrics; ?><?php endif; ?></pre></div>
<?php
// open the cache file for writing
$fp = fopen($cachefile, 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
// close the file
fclose($fp);
// Send the output to the browser
ob_end_flush();
?>
Here is my new scripts to create the XML.......
<?php
// Change to your database user name
$username="*********";
//Change to your database password
$password="*********";
// Change to your database name
$database="********";
// Connect to the database
mysql_connect('*********',$username,$password);
// Handle an error
#mysql_select_db($database) or die( "Unable to select database");
// Build Sql that returns the data needed - change this as required.
$sql = "SELECT songlist.*, historylist.listeners as listeners, historylist.requestID as requestID, historylist.date_played as starttime FROM historylist,songlist WHERE (historylist.songID = songlist.ID) AND (songlist.songtype='S' OR songlist.songtype='C' OR songlist.songtype='N') ORDER BY historylist.date_played DESC LIMIT 1";
// Store results in result object
$result = mysql_query($sql);
//store values in vars for calculation for array creation
$curPlay = mysql_query("SELECT * FROM historylist ORDER BY date_played DESC LIMIT 1");
$curPlayRow = mysql_fetch_assoc($curPlay);
if (!$curPlay) { echo( mysql_error()); }
$dt_duration = mysql_result($result,$i,'duration');
$title= mysql_result($result,$i,'title');
$artist= mysql_result($result,$i,'artist');
$album= mysql_result($result,$i,'album');
$picture= rawurlencode(mysql_result($result,$i,'picture'));
$lyrics= mysql_result($result,$i,'lyrics');
$ID= mysql_result($result,$i,'ID');
$curtime = time();
$timeleft = $starttime+round($dt_duration/1000)-$curtime;
$secsRemain = (round($dt_duration / 1000)-($curtime-$starttime));
//build array to return via getXMLHTTPRequest object - you can include more vars but remeber to handle them
//correcty in the useHttpResponse function
$Aj_array = $dt_duration . '|' . $secsRemain . '|' . $title . '|' . $artist .'|' . $album .'|' . $picture .'|' . $lyrics .'|' . $ID;
//we are using the text response object - which i think is easier for small data return
//just echo the array - not so much AJAX rather AJA ??
echo $Aj_array
?>
And the script in my html to read the extracted content....
<script language="JavaScript">
var http = getXMLHTTPRequest();
var counter;
function getXMLHTTPRequest() {
try {
req = new XMLHttpRequest();
} catch(err1) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err2) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err3) {
req = false;
}
}
}
return req;
}
function getServerText() {
var myurl = 'http://bangalorechristianradio.com/PHP/web/aj.php';
myRand = parseInt(Math.random()*999999999999999);
var modurl = myurl+"?rand="+myRand;
http.open("GET", modurl, true);
http.onreadystatechange = useHttpResponse;
http.send(null);
}
function useHttpResponse() {
if (http.readyState == 4) {
if(http.status == 200) {
var aj_results = http.responseText.split("|");
var aj_duration = aj_results[0];
var aj_secsremaining = aj_results[1];
var aj_title = aj_results[2];
var aj_artist = aj_results[3];
var aj_album = aj_results[4];
var aj_picture = aj_results[5];
var aj_lyrics = aj_results[6];
var aj_ID = aj_results[7];
// update title and artist divs
document.getElementById('title').innerHTML = aj_title;
document.getElementById('artist').innerHTML = aj_artist;
document.getElementById('album').innerHTML = aj_album;
document.getElementById('picture').innerHTML = "<img src=http://chennaichristianradio.com/images/album_art/" + aj_results[5] +" width='142' height='142'>"
document.getElementById('lyrics').innerHTML = aj_lyrics;
countDownInterval = aj_secsremaining - 0;
countDownTime = countDownInterval + 1;
countDown()
}
} else {
//document. getElementById('actual').innerHTML = "";
}
}
function countDown() {
countDownTime--;
if (countDownTime == 0) {
countDownTime = countDownInterval;
getServerText()
}
else if (countDownTime < 0)
countDownTime = 30;
if (document.all)
document.all.countDownText.innerText = secsToMins(countDownTime);
else if (document.getElementById)
document.getElementById("countDownText").innerHTML = secsToMins(countDownTime);
stopCountDown();
counter = setTimeout("countDown()", 1000);
}
function secsToMins(theValue) {
var theMin = Math.floor(theValue / 60);
var theSec = (theValue % 60);
if (theSec < 10)
theSec = "0" + theSec;
return(theMin + ":" + theSec);
}
function stopCountDown()
{
clearTimeout(counter)
}
</script>
Some links
Dynamically created Page using PHP: http://chennaichristianradio.com/PHP/web/songinfo.php?songID=5351
XML Page that shows the data that i need in my pages: http://bangalorechristianradio.com/PHP/web/aj.php
Page that has been created using JQuery and Ajax: http://bangalorechristianradio.com/PHP/web/player.html
Thanks everyone for your help!!
-Bob Swaggerty
Original post Below
I am wanting to create several hundred static html pages using the following script:
<?php
function wwwcopy($link,$file)
{
$fp = #fopen($link,"r");
while(!feof($fp))
{
$cont.= fread($fp,1024);
}
fclose($fp);
$fp2 = #fopen($file,"w");
fwrite($fp2,$cont);
fclose($fp2);
}
wwwcopy("http://www.domain.com/list.php?member=sample", "sample.html");
I create my php page called create.php, which creates 1 file. How do I use this script and create 1200 pages?
My whole purpose to do this is to minimize requests going to my MySQL database, and make my pages come up faster. After creating these pages, I will use another script to point to these files.
(update on 3/24/2012)
Thank you for your responses. Here is what I am trying to accomplish in doing this. Maybe there is a better solution......
look at my page http://chennaichristianradio.com/PHP/web/songinfo.php?songID=5351
My software is dynamically creating this page from the ID 5351 (the song in my database)
I am using php to go grab the song info. To make this process a bit more efficient, I hace set up PHP caching. I am caching this now using....
<?php
$cachefile = "cache/".$reqfilename.$cache_folder.md5($_SERVER['REQUEST_URI']);
$cachetime = 11000 * 60; // 110000 minutes
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && (time() - $cachetime
< filemtime($cachefile)))
{
include($cachefile);
echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))."
-->n";
exit;
}
ob_start(); // start the output buffer
?>
The PHP Cache is being accomplished using this, but my problem is it only caches the PHP info from this code and below. The reason this is a problem, is because i use PHP in the meta info aslo for my Open Graphic tags. The OG is so people can "like" my music in Facebook. Here is what my OG tags look like.
<title>Chennai Christian Radio</title>
<meta property="og:title" content="<?php echo $song->title; ?> by <?php echo $song->artist; ?> - Found on Chennai Christian Radio"/>
<meta property="og:type" content="song"/>
<meta property="og:url" content="http://chennaichristianradio.com/PHP/web/songinfo.php?songID=<?php echo $song->ID; ?>"/>
<meta property="og:image" content="<?php echo $song->picture; ?>"/>
<meta property="og:site_name" content="Chennai Christian Radio"/>
<meta property="fb:admins" content="1013572426"/>
<meta property="og:description"
content="Chennai Christian Radio is your last stop for today's best Christian Music. http://chennaichristianradio.com"/>
So...... What is the solution for caching my dynamic page AND include the meta info. That is defiantly the best option, but with my current code, it still queries my MYSql server for the Meta info and the song info. I thought by creating static pages for this and telling my software to point to these pages instead of querying my database it would be more efficient, as well as help in reducing my PHP traffic back to my server. Hope this clarifies my need, and I thank everyone for their response and help.
I'm not sure what you are trying to achieve but to do this 1200 times simply use a for loop and change the filename and urls.
for ($i = 1; $i <= 1200; $i++)
{
wwwcopy("url", "file");
}
I think that you must go for cache option. If you are using any frame work there are default settings for enabling cache. This will really improve your speed.

Use php for Output Buffering and jQuery to send ob_get_contents

I am trying to capture the contents of my php page using output buffering:
<?php
function connect() {
$dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
session_start();
if(isset($_SESSION['username'])){
if(isset($_POST['entryId'])){
//do something
$dbh = connect();
$ide = $_POST['entryId'];
$usertab = $_POST['usertable'];
$answertable = $usertab . "Answers";
$entrytable = $usertab . "Entries";
$query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());
if($query){
//set variables
$sectionOne = array();
while($row=mysql_fetch_assoc($query)){
$date = $row['date'];
$sectionOne[] = $row;
}
}else{
//error - sql failed
}
}
?>
<?php
ob_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
$("#export").click(function(e){
//post to html2pdfconverter.php
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
$("#nm").val("Entry Report.pdf");
$("form#sendanswers").submit();
});
});
</script>
<title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
</head>
<body>
<h1>Entry Report - <?php echo($date); ?></h1>
<div id = "buttons">
<form id = "sendanswers" name = "sendanswers" action="html2pdfconverter.php" method="post">
<input type = "hidden" name = "link" id = "link" value = "">
<input type = "hidden" name = "nm" id = "nm" value = "">
<input type = "button" name = "export" id = "export" value = "Export As PDF"/>
</form>
</div>
<h3>Biological Information</h3>
<?php
echo('<p>');
$i = 0;
foreach($sectionOne as &$value){
if($i == 1 || $i == 3){
$image = "assets/urine".$i.".png";
echo("<br/>");
echo($value['question']." <br/> "."<img src = \"$image\"/>");
echo("<br/>");
}else{
echo($value['question'].' : '.$value['answer']);
}
echo("<br/>");
$i++;
}
echo('</p>');
?>
</body>
</html>
<?php
}
$contents = ob_get_contents(); //THIS WORKS
ob_end();
?>
I assign the contents of ob to $contents using ob_get_contents(); This works, and echoing $contents duplicates the html page.
However, in my jQuery, I am trying to assign this to a hidden text field ('link') using:
$("#link").val("<?php echo($contents); ?>");
This doesn't work however..And I have a feeling its because I am accessing $contents too eraly but not too sure...any ideas?
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
at the point you do that ob_get_contents call, you've only output about 10 lines of javascript and html. PHP will NOT reach back in time and magically fill in the rest of the document where you do this ob_get_contents().
You're basically ripping the page out of the laser printer the moment the page starts emerging, while the printer is still printing the bottom half of the page.
I fail to see why you want to embed the contents of your page into an input field. If you want to somehow cache the page's content in an input field, you can just use JS to grab the .innerHTML of $('body').
Well, you have two problems.
The first is what you suspect. You can't access that stuff until later. The second problem which you may not realize is that you will have quoting issues in JavaScript even if you manage to find a way to reorder this and make it work. It's recursive, in a bad way.
What you should do instead is change your $('#export').click handler to do an Ajax call, render the HTML you need to appear in the link on the server in a separate PHP script (no output buffering necessary) and then have your code inject the result of that call into the page the way you're trying to do in your click handler now.

Categories