How to append to textarea with PHP and then refresh the textarea?
THANK YOU
edit:
It should be server triggered from PHP code
The simplest approach would be to have a javascript function that polls the php script using ajax - say every 10 seconds. You could add a timestamp as a parameter to the php function so it only returns the latest log entries.
When the ajax call returns you can append the resulting text to your textarea using javascript.
I could fish out some sample code if you like?
So, here's an HTML file - it has a function to make an AJAX call to a script - log.php that returns some stuff (in this example it's a very simple line of text) and then append this to the text area.
When the script loads we set up a timer to fire every 1000 milliseconds (obviously change this according you your needs).
We've also got a "cancel updates" function and a "start updates".
So - put the html file and the php file (which you need to call log.php - or call it what you like and change the code) into the same directory on your web server and see what happens!.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var http = createRequestObject();
var updateInt=self.setInterval("updateLog()",1000);
function startAutoUpdate(){
if(updateInt==""){
updateInt=window.setInterval("updateLog()",1000)
}else{
stop_Int()
}
}
function stopAutoUpdate(){
if(updateInt!=""){
window.clearInterval(updateInt)
updateInt=""
}
}
function createRequestObject() {
var objAjax;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
objAjax = new ActiveXObject("Microsoft.XMLHTTP");
}else{
objAjax = new XMLHttpRequest();
}
return objAjax;
}
function updateLog(){
http.open('get','log.php');
http.onreadystatechange = updateNewContent;
http.send(null);
return false;
}
function updateNewContent(){
if(http.readyState == 4){
document.getElementById('log').innerHTML = document.getElementById('log').innerHTML + http.responseText;
}
}
</script>
</head>
<body>
<h2>Log</h2>
<textarea cols="80" rows="10" name="log" id="log"></textarea>
<span onclick="updateLog()">Update</span><br>
<span onclick="stopAutoUpdate()">Cancel Auto Update</span><br>
<span onclick="startAutoUpdate()">Start Auto Update</span><br>
</body>
</html>
Here's the php script (very simple)...
<?PHP
/* Log responder script
*
* When invoked this script returns log entries
* as this is a sample it just returns a couple of random items
*
*/
echo "Log Entry ".date("d/m/y h:i:s")."\n";
?>
Related
Basically I want to have a button on my HTML/PHP page which will once clicked send a call to another php page which will update a value in mysql table.
<html>
<head>
<script>
src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
function toggleText(button_id){
if(document.getElementById(button_id).innerHTML == "Uninstall All"){
document.getElementById(button_id).innerHTML = "Cancel Uninstall";
//ajax////////////////////
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "valueChange.php?uninstalled=1&type=all", true);
xmlhttp.send();
////////////////////////
}
}
</script>
</head>
I'm curious why this isn't working.
I had tested my toggleText function without the ajax and it changed the HTML properly.
But once I add in the ajax to visit this valueChange.php page and update an sql value it doesn't work.
I've tested the php page by itself and it properly updated the value in sql.
I've never used ajax so I'm curious if I'm doing it wrong? I thought my src = "google/ajax/jquery" was the way to install it. Or is there a library I need to install on the VPS hosting my site?
The only mistake I see in above code is just a typo. See line 3 you closed the script tag before the second attribute it should have been <script src="*link to jQuery*" ></script>
And another thing you don't need to use the jQuery library to use XMLHttpRequest() method.
The modified code:
<html>
<head>
<script>
function toggleText(button_id)
{
if(document.getElementById(button_id).innerHTML == "Uninstall All")
{
document.getElementById(button_id).innerHTML = "Cancel Uninstall";
//ajax////////////////////
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "valueChange.php?uninstalled=1&type=all", true);
xmlhttp.send();
////////////////////////
}
}
</script>
</head>
re this post AJAX Post to self in PHP
When using exit() doesn't something have to be printed before this call?
I have written markup/ph with references to external css php scripts. The script uses print (or echo) and a
call to header('type: text/css'). Isn't this useful or necessary in self processing php pages? I find
them endlessly useful. A whole site can be displayed in any state by one page using get queries and posts
from forms. I remember the text I was reading early on when beginning to learn php asserted that when
the page submits to itself, the browser will automatically use asynchronous requests. But in certain situations
an explicit ajax call is useful.
Here is what I am doing and what I am trying to do.
I have a text field and a button in a page
I write text to the text field and click the button
The javascript click event handler for the button gets the text field value
and appends it to a get query attached to the url in the request. The method is get
edit: to specify the environment in which this has been successful.
I am using Firefox v12.0 On Mac OSX with pre-installed apache server on local machine.
(anyone with a Mac running OSX, there is a pre installed apache server, but activating php requires
editing the httpd.com file to un comment the line(s) that load the php module. Also, there is a line
that tells Apache what extensions to use to look for and execute php code. You also must tell it
to take index.php as an index file to run the php in it and have it act as a directory index file)
the javascript code:
function _FETCH()
{
this.init = function(oName, elem, txt)
{
var but = document.getElementById(elem);
but.addEventListener('click', function(){ oName.req('GET', self, '', null, oName, txt) } )
}
this.req = function(method, url, type, msg, oName, txt)
{
var field = document.getElementById(txt);
url+="?ajxTst="+encodeURIComponent(field.value);
var it = new XMLHttpRequest();
it.open(method, url, type);
it.setRequestHeader('Content-Type', 'text/plain');
it.onreadystatechange = function()
{
var elem = document.getElementById('well');
switch(it.readyState)
{
case 0:
case 1:
break;
case 2:
case 3:
elem.childNodes[0].data = " waiting";
break;
case 4:
oName.handleResponse(it.responseText);
break;
default:
alert('ajax processing error');
break;
}
}
it.send(msg);
}
this.handleResponse = function(resp)
{
var elem = document.getElementById('well');
elem.childNodes[0].data = " "+resp;
}
}
The php, javascript and markup in the page:
<?php
/*
created 11/4/2014
*/
$_self = basename($_SERVER['PHP_SELF']);
if($_POST || $_GET)
{
if($_GET['ajxTst'])
{
header("Content-Type: text/plain");
print $_GET['ajxTst'];
exit();
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>JS lab 2</title>
<link rel="stylesheet" type="text/css" href="local.css" media="screen" />
<script type="text/javascript" src="local.js">
</script>
<script type="text/javascript">
//<![CDATA[
var self = "<?php print $_self; ?>";
window.onload = function()
{
var ajx = new _FETCH();
ajx.init(ajx, 'send', 'tlk');
}
//]]>
</script>
</head>
<body>
<div class="panel">
<p class="title">Js Lab 2</p>
<p class="norm">Lab 3 home</p>
<p class="norm">Work with ajax and self processing page (this)</p>
<hr />
<p class="norm" id="well"> idle </p>
<p class="norm">
<input type="text" id="tlk" value="" /><input type="button" id="send" value="send" />
</p>
</div>
</body>
</html>
I hope That someone looking for this will find it. It took me a while to get it right
Hi I am very new to JavaScript. With the help of some friends around I was able to compile this code below. However I am not able to connect them all together.
Mission:
I want to replace the <div> in my index.php with corresponding php code in respective files based on the viewport.
Generalize the function getAsides() for use with multiple files and divs.
Once visitor changes browser size, Automatically page must be reloaded.
The entire code must be compatible with IE6 too. (this is a mandate) Currently my function getAsides() is compatible with IE6.
Code I have:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript">
function getAsides(){
document.getElementById("aside").innerHTML="<img src='loadingImage.gif'>";
var x = null;
if (window.XMLHttpRequest) {
var x = new XMLHttpRequest();
} else if (window.ActiveXObject) {
var x = new ActiveXObject('MSXML2.XMLHTTP.3.0');
} else {
// #TODO Fallback
}
x.open("GET", "other_content_1.php", true);
x.send("");
x.onreadystatechange = function() {
if(x.readyState == 4) {
if(x.status==200)
document.getElementById("aside").innerHTML = x.responseText;
else
document.getElementById("aside").innerHTML = "Error loading document";
}
}
}
function getViewport() {
var
x=window.innerWidth||document.documentElement.clientWidth||document.getElementsByTagName.clientWidth,
y=window.innerHeight||document.documentElement.clientHeight||document.getElementsByTagName.clientHeight;
if (x >=960 && x<=1200) {
// Here using the function ' function getAsides()' I want to replace
//'<div id='aside'></div>' with 'aside.php'
} else if (x >=1201 && x<=1600) {
// Here using the function ' function getAsides()' I want to replace
//'<div id='aside'></div>' with 'aside.php' and
//'<div id='aside_medium'></div>' with 'aside_medium.php'
} else if (x >=1600) {
// Here using the function ' function getAsides()' I want to replace
//'<div id='aside'></div>' with 'aside.php' and
//'<div id='aside_medium'></div>' with 'aside_medium.php' and
//'<div id='aside_large'></div>' with 'aside_large.php'
}
}
if(window.addEventListener) {
window.addEventListener('DOMContentLoaded', ready, false);
window.addEventListener('load', ready, false);
} else if(window.attachEvent) {
window.attachEvent('onload', ready);
}
window.onresize = function() {
reloadPage(self.innerWidth);
};
</script>
</head>
<body>
<div id="wrapper">
<div id="header"></div>
<div id="aside"></div>
<div id="aside_medium"></div>
<div id="aside_large"></div>
<div id="content"></div>
<div id="footer"></div>
</div>
</body>
</html>
My Questions:
Am I on the right track? Is there a better way of doing this? If yes then how?
What should be the correct code / syntax to achieve what is mentioned in the 'Mission'
Special notes:
I am not going to use jQuery or any other JavaScript libraries because this is the only JavaScript in my template and I do not want to slowdown my page speed / performance as that is the key factor for this template.
A function can be written in thousand different ways and there is no one correct way to write one. Your question might in fact solicit opinion, debate or extended discussion, not really fitting into stackowerflow's Q&A format. That being said, there is some room for improvement to your code.
Consider congesting your cross-browser XMLHttpRequest check. Like so:
var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : (XMLHttpRequest && new XMLHttpRequest()) || null;
Move your code to an external js file. It's always never a good idea to have inline javascript.
I am calling a very simple PHP page with some equally simple AJAX, but the call always returns nothing, even though the PHP is fine. That is, you can go to the URL of the PHP page and see that it echoes "Hello World" but when it is called with JS, it returns nothing.
Below is the HTML Page with the Javascript:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......<br />
Enter your email: <input id="email" type="text" />
<input type="button" onclick="setXMLHttpRequest()" value="Go!" />
<script type='text/javascript'/>
var http;
function setXMLHttpRequest()
{
if(window.XMLHttpRequest)
http = new XMLHttpRequest();
else if(window.ActiveXObject)
http = new ActiveXObject("Microsoft.XMLHTTP");
url = "http://www.convolutedconstruct.com /Ajax/checkemail.php?email=" +
document.getElementById('email').value;
http.onreadystatechange = display;
http.open("GET", url, true);
http.send(null);
}
function display()
{
if (http.readyState == 4)
{
infostr = http.responseText;
alert("From the PHP: " + infostr);
}
}
</script></body></html>
Here is the content of the PHP page
Click here for the live PHP page
<?php
$email = $_GET['email'];
echo "Hello World!";
?>
Why does this return nothing to the JS, even though the PHP page echoes the text correctly?
As has been suggested above, AJAX request will only work usually when both the caller and called are on same domain, You have to ensure that your html code, which contains the javascript, resides on same domain http://www.convolutedconstruct.com.
If that is not the case you can use CORS to allow your ajax to receive input from your php page by sending this header in your php output
<?php
header("Access-Control-Allow-Origin: *");
//rest of your code
?>
See: http://enable-cors.org/
i dont like using the XMLHTTP request. instead i use jQuery's method $.ajax({}); method. it always works for me!
$.ajax({
type: "POST", // or 'GET'
url: "your-url.php", // url that you are passing the data to
data: {
dataName: 'data to pass' // string, variable, object, array, etc
},
success: function(output) { // output is what the url is 'echoing' back to the jQuery
// do something when the ajax method is complete.
}
});
dont forget to import the jQuery source code - http://code.jquery.com/jquery-1.7.2.min.js
these are the most common of the components that are used in ajax.
I'll be glad to help you out some more if you would like it.
If you want to know more just check the documentation on it: http://api.jquery.com/jQuery.ajax/
I want to display the browsed time of a user, But when i refresh it, it will be again start from 0:0:0.
How can it handle?
<?php
$total_mints=($live_match['match_name']) * (60);
?>
<script language="javascript">
display_c(<?=$total_mints?>,'ct');
</script>
<script type="text/javascript">
function display_c(start,div){
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end ){
mytime=setTimeout("display_ct('"+div+"')",refresh)
}
else {alert("Time Over ");}
</script>
Once the time is over, you could set a cookie to 'Time Expired'... When the page is loaded, if the cookie is 'Time Expired' then you can display the 'Time Over' alert. You can also use the cookie to keep track of accumulated browsing time.
Edit - added some specifics... but I think you'll have to think about this some more.
Basically, you want to use JS to write the cookie as the user uses the page, and you want to use PHP to read the cookie when the page is loaded. You can use the cookie to either only track whether time is up, total accumulated time, or both. I think you'd want to renew the cookie every minute or so?
It's going to look SOMETHING like this - this code just shows how to keep track of whether time has expired or not with a cookie, not accumulated time.
<?php
$total_mints=($live_match['match_name']) * (60);
// check for cookie and only proceed if it is not expired
// can also use cookie to keep track of total accumulated number
// of minutes between session
if ($_COOKIE["yourMints"] != "expired")
{
?>
<script language="text/javascript">
display_c(<?php echo $total_mints; ?>,'ct');
</script>
<script type="text/javascript">
function display_c(start,div)
{
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end )
{
mytime=setTimeout("display_ct('"+div+"')",refresh)
} else
{
alert("Time Over ");
// set cookie to expired
document.cookie = "yourMints=expired";
}
}
</script>
<?php
} else // What follows is what happens if cookies IS expired
{
?>
<script type="text/javascript">
alert("Time Over ");
</script>
<?php
}
?>
Here is a good JS cookies tutorial:
http://www.quirksmode.org/js/cookies.html
Here is using $_COOKIE to read cookies with PHP
http://php.net/manual/en/reserved.variables.cookies.php
EDIT: Added in JQuery example after seeing PlagueEditor's example.
Nice script PlagueEditor. Thought I'd try the same thing w/ JQuery for fun.
JQuery has a simple little cookie plugin... only 40 lines of code or so.
Here's a page with a cookie stored timer and a timeout of 10 seconds with a possible reset:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Time Spent on Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="PATH-TO-YOUR-JQ-DIRECTORY/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="PATH-TO-YOUR-JQ-DIRECTORY/cookie.js"></script>
<script type="text/javascript">
<!--
$.myTimer =
{
timeLimit: 10,
displayTime: function ()
{
if ($.myTimer.time < $.myTimer.timeLimit)
{
$("#timeHere").html($.myTimer.time);
$.cookie('yourMints', $.myTimer.time, { expires: 7});
++$.myTimer.time;
$.myTimer.toggle = setTimeout("$.myTimer.displayTime()",1000);
} else
{
$("#page").html('<h1>Time expired</h1>');
}
}
}
// When the page is ready ==================================================
$(document).ready(function()
{
// Read time spent on page cookie. Set it, if it doesn't exist.
if (!$.cookie('yourMints'))
{
$.cookie('yourMints', '0', { expires: 7});
}
$.myTimer.time = $.cookie('yourMints');
// Start timeer
$.myTimer.displayTime();
// Reset the timer
$("#reset").click( function()
{
$.cookie('yourMints', '0');
window.location.reload();
});
});
// -->
</script>
</head>
<body>
<div id="page">
<h2>Your total time here: <span id="timeHere"></span></h2>
You can only look at this page for 10 seconds.
</div>
<input id="reset" type="button" value="Reset Timer" />
</body>
</html>
Below is a solution for keeping track of the browsed time, even with refreshing. It gets the date when the page loads and every second subtracts that date from the given date. The date is then displayed in the span. The page should work by itself. I hope this is what you were looking for, or at least helps. Two functions were W3Schools examples*.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
/**
* getCookie and setCookie were taken from http://www.w3schools.com/JS/js_cookies.asp.
*/
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
var totalTime=0;
var storedTime=getCookie("storedTime");
if(storedTime.length == 0){
//If it doesn't exist..
storedTime=0;
}else{
storedTime=parseInt(storedTime);
totalTime=storedTime;
}
function updateTime(){
totalTime+=1000;
document.getElementById("duration").innerHTML= Math.ceil(totalTime / 1000);
}
onbeforeunload = function(){
setCookie("storedTime",totalTime,3);
}
setInterval(updateTime, 1000);
</script>
Your total time here: <span id="duration"><script type="text/javascript">document.write( Math.ceil(totalTime / 1000));</script></span> seconds...
</body>
</html>