Include whole page in variable (PHP) - php

I'm trying to create a page where I can force updates to the client without a page refresh. So I Googled and Googled and Googled and ended up here: http://www.developerdrive.com/2012/03/pushing-updates-to-the-web-page-with-html5-server-sent-events/ - it was almost a success!
I managed to adapt the code enough so that I can include a page instead of using the example rand() and thus, whenever I modify that page and upload it to my FTP, the page updates. However, I cannot figure out how to output a whole file - only the first line of that file (maindiv.php). I've come to understand that it has to do with using "file_get_contents". How can I achieve a full output of "maindiv.php" here?
My pages codes are:
index.php:
<html>
<head>
<style type="text/css">
#serverData
{
position:fixed;
padding:0;
margin:0;
top:0;
left:0;
width: 100%;
height: 100%;
background:green;
}
</style>
</head>
<body>
<div id="serverData">Here is where the server sent data will appear
</body>
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("send_sse.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
};
}
else {
document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events.";
}
</script>
</html>
send_sse.php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$maindiv = file_get_contents("maindiv.php"); //this does not read more than one line
echo "data: $maindiv\n\n";
ob_flush();
?>
maindiv.php:
<div style="background:blue; display:inline-block; width:300px; height:500px;color:white;">Line 1<br>
Line 2<br>
Line 3<br>
Line 4<br>
Line 5<br>
Line 6<br>
Line 7<br>
</div>

Related

Showing PHP database content within a div

I'm setting up a website containing a page that will contain many buttons. I want to be able to click on the button to populate a div with information from a database.
I've adapted some code that I previously had, but it isn't working.
The source javascript and HTML are shown here:
<script>
function showBiog(key) {
//alert(key);
// Get the search value
var search_value = key
// This time we're going to grab data from a file to display
var filename = "functions/biography.php";
// Send these values
var posting = $.post(filename, { search_term: search_value });
// Display this value in our results container
posting.done(function (data) {
$("#test_results").empty().append(data);
});
}
</script>
<style type="text/css">
.test {
background-color: #B32D2F;
border: thin solid #DBB2B3;
height: 50px;
width: 250px;
}
.testresults {
background-color: #88B32D;
border: thin solid #DBB2B3;
height: 50px;
width: 250px;
}
</style>
</head>
<body>
<div class="test" onClick="showBiog(1)"><p>1</p></div>
<div class="test" onClick="showBiog(2)"><p>2</p></div>
<div class="test" onClick="showBiog(3)"><p>3</p></div>
<div class="test" onClick="showBiog(4)"><p>4</p></div>
Results
<div class="testresults" id="test_results"></div>
The HTML of biography.php is
<body>
<?php if (! $_POST["search_term"]) { ?>
<div class="err">
<?php echo $row_Recordset1['firstname']; ?>
</div>
<?php } else { ?>
<?php echo $row_results['firstname']; }?>
</body>
The SQL for results in Dreamweaver is
SELECT *
FROM pilots
WHERE key LIKE colname
with colname $_POST['search_term']
Few things...
You may not need "var search_value = key" if you are not making any change or addition to it. Simply use "key" in the $.post (keep code simple).
What is expected to be in "key"? Depending on what you are sending, the statement var posting = $.post(filename, { search_term: search_value }); may break due to JSON structure requirements.
To assure you are sending out the right information to the PHP, you should try something like $.post(filename, JSON.stringify({ 'search_term': key }) );
On the PHP side, you can use unserialize() to decode JSON data, then process your query.
Just a small personal note and advice: If JSON is not well formed on the POST side, PHP will get nothing, thus it will return nothing. You should always try to log or display the data received by PHP when writing AJAX calls to assure it was correctly received. Otherwise you may be chasing a bug in the wrong spot. ;)

Wordpress unique background in posts that are in specific category

i have a code:
<body <?php if( in_category( 11446 ) ) { echo "style=\"background-image: url('my-background-url-of-image');background-repeat:repeat;\" onclick=\"window.open('http://www.domain.com');\""; } ?> >
This code works only until page loads fully than something happens and it doesn't work i assume from inspect element that onclick function changes and i'm failing to find what part tricks that.
What this code does is it sets unique body background that are in specific category and background is clickable.
But because of some javascript error it doesn't work when page loads full so maybe somebody could explain me how to remove attr on Javascript and than add my with domain i want. Or maybe give example how to do alternative code just with href.
Thank you.
I'm assuming you are building a Wordpress template and the background image to be used is based upon the category of a Wordpress post.
This uses no Javascript. Instead, what it does is create the CSS declaration block inside the head tag of the HTML5 document on the fly. It does no inline CSS for the body tag.
<?php
// ====================================================
// Solution #1
// Background Image Only
// ====================================================
function GetThisWordpressPostCategory() {
// Do post category to filename mapping here
return("cars");
}
function in_category() {
// Just a dummy to simulate Wordpress in_category call
return(true);
}
function BodyBackground($category) {
$bodyCss = "";
if (in_category($category)) {
$bodyCss =<<<CSS
<style type="text/css">
body {
background-image: url('{$category}.jpg');
}
</style>
CSS;
}
return($bodyCss);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Category background</title>
<?php
$category = GetThisWordpressPostCategory();
echo BodyBackground($category);
?>
</head>
<body>
</body>
</html>
<?php
// ====================================================
// Solution: 2
// Clickable div spanning viewport
// ====================================================
function GetThisWordpressPostCategory() {
// Do post category to filename mapping here
return("cars");
}
function in_category() {
// Just a dummy to simulate Wordpress in_category call
return(true);
}
function PageCss($category) {
$pageCss = "";
if (in_category($category)) {
$pageCss =<<<CSS
<style type="text/css">
html, body, #page {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-image: url('{$category}.jpg');
}
#page-anchor {
display: block;
width: 100%;
height: 100%;
}
</style>
CSS;
}
return($pageCss);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Category background</title>
<?php echo PageCss(GetThisWordpressPostCategory()); ?>
</head>
<body>
<div id="page">
<a id="page-anchor" href="http://www.google.com"></a>
</div>
</body>
</html>

$.get in jquery not executing while on html page through javascript

I've been trying to create a simple download counter for my site, in the following way: To use jquery to retrieve the value of a txt which indicates download times, then to use jquery to call ajax to execute a PHP file, which would in turn overwrite such txt file (incrementing it on the php file) then store it, then reading back the value with jquery. Before I forget, and to avoid any misinformation, here is the whole HTML code for the page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>GreenDream: SMS Sender</title>
<link rel=StyleSheet type="text/css" href="http://www.gfcf14greendream.com/CSS/greendream.css" />
<link rel="SHORTCUT ICON" href="http://www.gfcf14greendream.com/images/dreamicon.ico">
<script type="text/javascript" src="http://www.gfcf14greendream.com/JS/greendream.js"></script>
</head>
<body onload="startTime(); handleTextFile()">
<div id="background">
<img src="http://www.gfcf14greendream.com/images/greentwi.png" class="stretch" alt="" />
</div>
<br />
<table align="center">
<tr>
<td>
<img src="http://www.gfcf14greendream.com/images/dream.png" align="middle">
</td>
<td>
<div id='pbutton' style="width:113px; height:41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://www.gfcf14greendream.com/programs.html">Programs</a></div>
</td>
<td>
<div id='gbutton' style="width:93px; height: 41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://www.gfcf14greendream.com/games.html">Games</a></div>
</td>
<td>
<div id='tbutton' style="width:108px; height: 41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://www.gfcf14greendream.com/tutorials.html">Tutorials</a></div>
</td>
<td>
<div id='bbutton' style="width:74px; height: 41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://blog.gfcf14greendream.com/">Blog</a></div>
</td>
<td>
<div id='mbutton' style="width:114px; height: 41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://www.gfcf14greendream.com/aboutme.html">About Me</a></div>
</td>
<td style="padding-left:50px">
<div id='daytitle'></div>
<div id='clock'></div>
</td>
</tr>
</table>
<br />
<div style="text-align: center; color:#00FF00; font-size: 20px">The following is a Visual C++ program that was designed specifically to send text messages to a phone... Free of charge!!</div>
<br />
<div style="text-align: center; color:#FFFF00; font-size: 20px">THE GOOD: If you have a prepaid phone, then you can send text messages to a phone without wasting your minutes...</div>
<br />
<div style="text-align: center; color:#FF8000; font-size: 20px">THE BAD : Since I haven't been able to put a Skype or Google Voice library for use with C++, this application depends on using what's known as an SMS gateway, different for every phone carrier... meaning you must know your recipient's carrier to be able to send a message!</div>
<br />
<div style="text-align: center; color:#FF0000; font-size: 20px">THE UGLY: This program doesn't work on computers connected to safe networks (such as college/university networks) ... at least not yet!</div>
<br />
<div style="text-align: center; color:#00FF00; font-size: 20px">You will probably need the Visual C++ Redistributable Package (or the .NET framework or both, but most likely just the package) to run this program, if you don't have it installed on your pc yet</div>
<br />
<br />
<div style="text-align: center; color:#0000C8; font-size: 20px">Click here to download the Visual C++ Redistributable Package</div>
<div style="text-align: center; color:#0000C8; font-size: 20px">Click here to download the .NET Framework 4</div>
<br />
<br />
<div style="text-align: center; color:#00FF00; font-size: 20px"><a class="button" id="downbutton" style="width:115px;margin:0px;white-space:nowrap; word-spacing:0;" href="http://www.gfcf14greendream.com/Programs/SMSSender/SMS Sender.exe">Click here to download SMS Sender</a></div>
<br />
<div id='counter' style="text-align: center;"></div>
<br />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function handleTextFile()
{
document.getElementById('counter').style.color = "rgb(0, 255, 0)";
document.getElementById('counter').style.fontWeight = 'bold';
var downcounter = 0;
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
downcounter = data;
if (downcounter == 1) $("#counter").text("SMS Sender has been downloaded " + downcounter + " time...");
else $("#counter").text("SMS Sender has been downloaded " + downcounter + " times...");
});
$("#downbutton").click( function(){
$.get("http://www.gfcf14greendream.com/PHP/smssender.php", function(data){
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
downcounter = data;
if (downcounter == 1) $("#counter").text("SMS Sender has been downloaded " + downcounter + " time...");
else $("#counter").text("SMS Sender has been downloaded " + downcounter + " times...");
});
});
});
}
</script>
</body>
</html>
Upon running the page, I use this code (a piece from above) to read a txt file and get download count (this works):
var downcounter = 0;
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
downcounter = data;
if (downcounter == 1) $("#counter").text("SMS Sender has been downloaded " + downcounter + " time...");
else $("#counter").text("SMS Sender has been downloaded " + downcounter + " times...");
});
Then when the downbutton variable is clicked, this code should execute:
$("#downbutton").click( function(){
$.get("http://www.gfcf14greendream.com/PHP/smssender.php", function(data){
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
downcounter = data;
if (downcounter == 1) $("#counter").text("SMS Sender has been downloaded " + downcounter + " time...");
else $("#counter").text("SMS Sender has been downloaded " + downcounter + " times...");
});
});
});
, which should read a php file, whose code is:
<?php
$counter = intval(file_get_contents('/homepages/37/d434704165/htdocs/counters/smssender.txt'));
$counter++;
file_put_contents('/homepages/37/d434704165/htdocs/counters/smssender.txt', $counter);
?>
And running the php would overwrite the txt file "smssender" and thus increase the number of downloads. I noticed that manually entering the address of the php file on my site actually works, and the download increment takes place. Yet when JQuery executes the code, no increment takes place. I'm guessing it's on this line, but what would be the error here? :
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
Thank you very much for any help or suggestion!!
I think it would be a lot simpler to just use the PHP page by itself. You can use GET variables to determine whether you need to increment the download counter. For instance, do something like this in your PHP file:
<?php
$total = (int)file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/counters/smssender.txt');
if (isset($_GET['i'])) {
$total++;
// now update the file for future use
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/counters/smssender.txt', $total);
}
echo $total;
?>
Then you can call the PHP page by itself in the ajax so that you don't have to worry about both calls being executed simultaneously and causing errors. You could now just make a call to "smssender.php" when you want to retrieve the current number of downloads. In addition, you could call "smssender.php?i" when you want to retrieve the current number of downloads and increment the file contents.
If you wanted to only increment the file's contents and not echo the output, you could add another if statement, but I don't know if that's what you're trying to do. If so, please let me know and I can show you code for that as well. I hope that helps, if not, just let me know.
UPDATE: Just change your code to this:
Javascript File:
$.get("/PHP/smssender.php", function(data) {
$("#counter").text(data);
});
$("#downbutton").click( function() {
$.get("/PHP/smssender.php?i", function(data) {
$("#counter").text(data);
});
});
PHP File:
<?php
$total = (int)file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/counters/smssender.txt');
if (isset($_GET['i'])) {
$total++;
// now update the file for future use
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/counters/smssender.txt', $total);
}
$suffix = ($total == 1) ? 'time' : 'times';
echo 'SMS Sender has been downloaded ' . $total . ' ' . $suffix . '...';
?>
Now, you can simplify your Javascript/jQuery by A LOT. This code will have the exact same behavior as the code you had, without any errors. Now, I will explain the changes I have made. First, you only have to call a single PHP file with the $.get() method, regardless if you are just retrieving the current number of downloads or whether you are incrementing the total.
Secondly, the text handling is done in the PHP file. You no longer determine if it has been downloaded 1 or more times in Javascript, instead the PHP file handles this because it's a lot faster than retrieving the data and making a calculation afterwards.
Lastly, I made the download button only call $.get() once so that you don't have to worry about errors resulting from an attempt to retrieve two different pages simultaneously. Try replacing your code with the new code I posted above and let me know how it works out for you.

jQuery - growlUI Notification using screen scraped tweet

I am trying to pull my latest tweet into a variable in javascript, then use growlUI() to display this in a notification in jQuery.
Currently, I have pulled my tweet using PHP into a variable in javascript called test. I need to adjust the following jQuery code to use "test" instead of "Hello".
Current code works:
$.growlUI('Growl Notification','Hello');
Attempted code does not work:
$.growlUI('Growl Notification', $(test));
My Question
How do I use the variable test, which is a javascript variable, as a jQuery attribute?
Many thanks!
My source code:
<html>
<head>
<!-- Styling for growlUI -->
<style type="text/css">
div.growlUI { background: url(check48.png) no-repeat 10px 10px }
div.growlUI h1, div.growlUI h2 {
color: white; padding: 5px 5px 5px 75px; text-align: left
}
</style>
<!-- Import jquery from online -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<!-- Import blockUI -->
<script type="text/javascript" src="js/jquery.blockUI.js"></script>
<script type = "text/javascript">
<!-- Screenscrape using PHP, put into javascript variable 'test' -->
<?php
$url = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=XXXXXXXXXX";
$raw = file_get_contents($url);
$newlines = array("\t","\n","\r","\x20\x20","\0","\x0B");
$content = str_replace($newlines, "", html_entity_decode($raw));
$start = strpos($content,'<text>');
$end = strpos($content,'</text>',$start);
$latesttweet = substr($content,$start,$end-$start);
echo "var test = ".$latesttweet.";\n";
?>
</script>
</head>
<!-- Here I'm attempting to use test variable in second half of growlUI parameters -->
<body onLoad="$.growlUI('Latest Update',test); ">
</body>
</html>
Not sure if this is your problem, but it looks like your js string variable is not quoted:
echo "var test = ".$latesttweet.";\n";
Should be:
echo "var test = '".$latesttweet."';\n";
You should probably escape .$latesttweet to handle apostrophes.
If you have a variable test that is a string tweet, and you want to pass that string into your growlUI function...just do it:
var test = "my string blah";
$.growlUI('Growl Notification', test);

jQuery.get() method doesn't want to work

I am trying to load WalkScore Map into one of div's on the page. For some reason my code works only if I alert() something right after $.get() method. Have no idea why.
Can someone suggest something? Thanks.
<html>
<head>
<title>jQuery - Ajax dynamic content loading</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function loadWalkScore()
{
$.get("http://www.walkscore.com/tile/show-tile.php?wsid=567f19156a706dddb8a799630d85467e",null,null,"script");
alert("hello");
}
</script>
<div id="contentArea" style="margin: 20px 0px 10px 10px; border: 1px solid #CCC;">
<script type="text/javascript">
var ws_lat = "40.710318";
var ws_lon = "-74.016553";
var ws_width = "630";
loadWalkScore();
</script>
</div>
Try using something like this, to make the call when the DOM is ready.
<script type="text/javascript">
$(function()
{
$.get("http://www.walkscore.com/tile/show-tile.php?wsid=567f19156a706dddb8a799630d85467e",null,null,"script");
});
</script>
Put this block after your first <script> element.
For me is working. I had to change the wsid for my domain. I've checked the get request using Firebug and I get a javascript as a response. At the begining I was getting an error because I was using you wsid and it seems that for each calling sides they generate a new one. Try to see if your wsid is the correct one.

Categories