I am trying to generate random number with New York Lottery's Take 5, it generates right, but then i wanted to write it to .txt file and then load it with ajax.
HTML:
<div class="col-lg-10" id="rolled"></div>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
<input type="submit" value="submit">
</form>
PHP:
function roll() {
$server_seed = "39b7d32fcb743c244c569a56d6de4dc27577d6277d6cf155bdcba6d05befcb34";
$lotto = "0422262831";
$round_id = "1";
$hash = hash("sha256",$server_seed."-".$lotto."-".$round_id);
$roll = hexdec(substr($hash,0,8)) % 15;
$fn = "ram.txt";
$file = fopen($fn, "w");
fwrite($file, $roll);
fclose($file);
echo "<script>paste_rolled();</script>";
}
if (isset($_POST["submit"])) {
roll();
}
JAVASCRIPT:
function paste_rolled() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("rolled").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ram.txt", true);
xhttp.send();
}
It doesn´t work, even doesn´t write number to .txt file and i don´t know why.
When i tried that lotery system in another file, it worked. Thank you for any help.
Related
I am trying to use a .php file to edit a .txt file on my http web server. I can call the .php file and get it to run (and echo something random back) just fine, but when I use file_put_contents it doesn't work. I have tried setting file permissions to 777, 0775, etc but nothing happens. (although from what I have gathered, it seems that permissions are for local systems only). I know that there are some similar questions already here, but I cannot understand the answers to any of them.
testingPHP.js (trimmed):
function submitData() {
var data = prompt('Enter data');
sendToServer(data, 'test.txt');
}
function sendToServer(data, file) {//file is file to write into, not the php file
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
}
xmlhttp.open("GET", "editTXT.php?txtFile=file&data=data");
xmlhttp.send();
setTimeout(update, 500);
}
function update() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = xhttp.responseText;
console.log(response);
}
};
xhttp.open("GET", "readTxt.php?file=test.txt", true);
xhttp.send();
}
setInterval(update, 1000);
editTxt.php:
<?php
$txtFile = $_GET["txtFile"];
$data = $_GET["data"];
file_put_contents($txtFile, $data);
?>
readTxt.php:
<?php
$file = $_GET['file'];
$data = file_get_contents($file);
echo $data;
?>
I hope the following might help - I think the main problem is in the javascript funnily enough but I'll post here the changes I made to all files anyway. Incidentally - constant polling like this using Ajax could instead be done in a cleaner way using an EventSource connection and Server Sent Events.
If the textfile is to be overwritten completely when the script is invoked then this works fine ( in test anyway ) but if the data is intended to add to existing content you'd need to add FILE_APPEND as the final argument to file_put_contents
editTxt.php
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['txtFile'], $_GET['data'] ) ){
$file=__DIR__ . '/' . $_GET['txtFile'];
$data=$_GET['data'];
$bytes=file_put_contents( $file, $data );
if( !$bytes )exit('error');
}
?>
readTxt.php
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['file'] ) ){
$file=__DIR__ . '/' . $_GET['file'];
exit( file_get_contents( $file ) );
}
?>
And the HTML & Javascript
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<script>
function submitData() {
var data = prompt('Enter data');
if( data ){/* only submit if there is data */
sendToServer(data, 'test.txt');
setInterval(update, 1000);
return true;
}
}
function sendToServer(data, file) {//file is file to write into, not the php file
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
}
/* the filename and the data need to be escaped in the string */
xmlhttp.open("GET", "editTXT.php?txtFile="+file+"&data="+data);
xmlhttp.send();
setTimeout(update, 500);
}
function update() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = xhttp.responseText;
console.log(response);
}
};
xhttp.open("GET", "readTxt.php?file=test.txt", true);
xhttp.send();
}
/* call the function that prompts for data input */
submitData();
</script>
</body>
</html>
I have a page that displays the content of a C++ file into a textarea and I need to be able to save the contents of it using a script. (The C++ file does not have to be configured just saved.)
I'm using a PHP script to load the code from a file to display it on the textarea. How can I send back the contents to the script and save it to the same file or to a file with a new name?
PHP, HTML file:
<?php
$file = '/var/www/cgi-bin/cpp_get3.cpp';
$content = file_get_contents($file);
?>
<input type="text" id="filename" value="cpp_get3.cpp"><br>
<textarea id="cpp_content" rows="15">
<?php
echo($content);
?>
</textarea><br/>
<button id="save"onclick="savefile();">save</button>
Script:
function savefiles() {
var contentArea = document.getElementsById('cpp_content');
var cpp_content = contentArea.value;
var request = new XMLHttpRequest();
request.open('POST', '/php/save_contents.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
console.log("Success");
var resp = this.response;
} else {
alert ("Target server reached, but it returned an error" );
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send(cpp_content);
}
PHP file:
<?php
$filename = '/var/www/html/cgi-bin/cpp_get3.cpp';
$cpp_content = $_POST['cpp_content'];
if(file_exists($filename)){
file_put_contents($filename, $cpp_content);
}
?>
I expect for the C++ file of a text file at this point to get save with the content in the textarea.
You don't deserve me ;)
<?php
$fn = 'example.cpp';
file_exists($fn) or touch($fn);
if (!empty($_POST)) {
var_dump($_POST);
$_POST['filename'] === $fn or $fn = $_POST['filename'];
file_exists($fn) or touch($fn);
file_put_contents($fn, $_POST['cpp_content']);
}
$file = file_get_contents($fn);
?>
<html>
<head></head>
<body>
<form action="hi.php" method="post">
<h1>ig #WookieeTyler</h1>
<input type="text" name="filename" value="<?=$fn?>">
<br>
<textarea name="cpp_content" rows="15">
<?= htmlspecialchars($file); ?>
</textarea>
<br/>
<button id="save" type="submit">save</button>
</form>
</body>
</html>
Another option would be to send the contents to a separated PHP file through an XMLHttpRequest. This way you don't have to reload the page when saving. Something like this:
var request = new XMLHttpRequest();
request.open('POST', '/my/url/save_contents.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.response;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send('cpp_content=' + cpp_content);
How to get different variable value in different ids from ajax response.
In my programming get all responses from test.php file but i want to differently for both variable.
Index.php File:-
<html>
<span> Picture : </span>
<!-- In picture hint i want to print $varbilefirst value from test.php file -->
<span id="picturehintget"></span>
<input type="button" id="<?php echo "8"; ?>" class="submitnone" name="ansclick" onclick="QuestionId(this.id)" value="Submit">
<div> Demo : <p id="demoquiz"></p> </div>
<!--In Demo i want to print $varbilesec value from test.php file -->
<script type="text/javascript">
function QuestionId(obj)
{
var id = obj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("demoquiz").innerHTML = this.responseText;
document.getElementById("picturehintget").innerHTML = this.responseText;
}
};
xhttp.open("GET", "test.php?id=" + id, true);
xhttp.send();
}
</script>
</html>
test.php file
<?php
$id = $_GET['id'];
$varbilefirst = "For Picture Hint";
echo $varbilefirst;
$varbilesec = "For Demo Hint";
echo $varbilesec;
?>
I want exactly different varible value for different ids.
<span id="picturehintget">For Picture Hint</span>
<p id="demoquiz">For Demo Hint</p>
You can try with in php file using array
<?php
$id = $_GET['id'];
$varbilefirst = "For Picture Hint";
$varbilesec = "For Demo Hint";
echo json_encode(["varbilefirst"=>$varbilefirst, "varbilesec"=>$varbilesec]);
?>
In Javascript
<script type="text/javascript">
function QuestionId(obj)
{
var id = obj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("demoquiz").innerHTML = this.responseText.varbilesec;
document.getElementById("picturehintget").innerHTML = this.responseText.varbilefirst;
}
};
xhttp.open("GET", "test.php?id=" + id, true);
xhttp.send();
}
</script>
If I understood well your request you can return JSON from test.php like this:
<?php
$id = $_GET['id'];
$myObj->demo= $varbilefirst;
$myObj->picture = $varbilesec;
$myJSON = json_encode($myObj);
echo $myJSON;
?>
Inside if of Javascript:
if (this.readyState == 4 && this.status == 200)
{
var myObj = JSON.parse(this.responseText);
document.getElementById("demoquiz").innerHTML = myObj.demo;
document.getElementById("picturehintget").innerHTML = myObj.picture;
}
So I have a code, where a number is retrieved from a text file and is displayed through HTML.
The thing is that it only retrieves the number when I refresh the page. If I change the number on other page, it doesn't change on the other page.
I've seen similar questions before, most of them said to use AJAX, but I don't understand much about AJAX and I only need it for this bit of code, it's not like I'm going to constantly use it. I would like to know if there is any other besides AJAX and if there is only AJAX, please present examples of code.
PHP code:
<?php
$file = "num.txt"; //Path to your *.txt file
$contents = file($file);
$num = implode($contents);
?>
JavaScript code. Basically it gets the PHP value and outputs to the html.
document.getElementById("num").innerHTML = '<?php echo $num; ?>';
Keep in mind, I don't want to refresh the page. Just the variable.
EDIT: PHP code - Getting an error - Notice: Undefined index: keynum in C:\xampp\htdocs\num.php on line 3
Here is the code of the PHP
<?php
$keynum = $_POST['keynum'];
$post = "INSERT INTO post (keynum) VALUES ($keynum)";
$fileLocation = getenv("DOCUMENT_ROOT") . "/num.txt";
$file = fopen($fileLocation,"w");
$content = $keynum;
fwrite($file,$content);
fclose($file);
echo 'Response';
die();
?>
You can achieve what you want using XMLHttpRequest, like this:
function updateData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('num').innerHTML = this.responseText;
}
};
xhttp.open('GET', '/num.php', true);
xhttp.send();
}
setInterval(updateData, 2000);
If you want to refresh the variable without refreshing the page, then you need to use an asynchronous request. It doesn't need to be AJAX, you can use the native XMLHttpRequest() function.
If you want more info: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
or with jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
setInterval(function(){
$.ajax({url:"num.php", success:function(result){
$("#num").html(result);
}});
}, 3000);
</script>
<textarea id="num"></textarea>
get_nbr.php
<?php
$file = "num.txt"; //Path to your *.txt file
$contents = file($file);
$num = implode($contents);
echo $num;
?>
index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!---trigger get_nbr() on page load on an infinite loop every two seconds -->
<body onload="setInterval(get_nbr, 2000)">
<script>
function get_nbr() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("num").innerHTML = this.responseText;
}
};
xhttp.open("GET", "get_nbr.php", true);
xhttp.send();
}
</script>
<p id="num"></p>
like this.
let url = ""; //whatever url your requesting.
setInterval(function(){
var x = new XMLHttpRequest();
x.open("GET" , url , true);
x.onreadystatechange = function(){
if(x.readyState == 4 && x.status == 200)
{
document.getElementById("num").innerHTML = x.responseText;
}
}
x.send();
} , 2000);
-- UPDATE , added post --
setInterval(function(){
var x = new XMLHttpRequest();
x.open("POST" , url , true);
x.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
x.onreadystatechange = function(){
if(x.readyState == 4 && x.status == 200)
{
document.getElementById("num").innerHTML = x.responseText;
}
}
x.send("postVar1=123");
} , 2000);
Just learning ajax today and am stock somewhere. Trying to link my php links to work with ajax so the data with that link Id would be displayed without refreshing the page. Below are the codes of what I have tried.
index.php
<div class="page">
<ul>
<?php
$sql = <<<EOF
SELECT * FROM addcategory ;
EOF;
$ret = $db->query($sql);
While ($row = $ret->fetchArray(SQLITE3_ASSOC)) {
$catname = $row['catname'];
$catid = $row['catid'];
echo "<li><a href='index.php?category_id=$catid'>$catname</a></li>";
}
?>
</ul>
</div>
<div class="cat_question">response displays here</div>
php script
require_once ("db.php");
$db = new MyDb();
$catid = (int)$_GET['category_id'];
$csql = <<<EOF
SELECT * FROM questions WHERE category_id = {$catid};
$cret = $db->query($csql);
While ($crow = $cret->fetchArray(SQLITE3_ASSOC)) {
$catquestion = $crow['question'];
$catans = $crow['answer'];
echo "<div>$catquestion</div><p>$catans</p>";
}
JavaScript
$('.page a).click(function(e) {
e.preventDefault();
If (window.XMLHttpRequest) {
var xhttp = new XMLHTtpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
If (xhttp.readyState == 4 && xhttp.status == 200) {
var response = xhttp.responseText;
$('.cat_question').html(response);
}
};
xhttp.open("GET", "category.php?category_id=$catid", true);
xhttp.send();
});
I know if i change the xhttp URL to category.php?category_id=1 or any id it works but that would mean in would have to write ajax request for each a tags. Please what is the way to solve this block. Thanks in advance.