Pass PHP value to Javascript While They Are in Different Documents - javascript

I would like to create an upload form. In the form, member can upload multiple pictures to his/her own folder, which is named by the member's ID. For example, if the member's ID is 0001, then he/she can upload his pictures to image/0001/ folder.
In the uploading form, I use Javascript to let users upload multiple pictures in the same page. After user select the first picture, it generates the second <input type="file"> ; after selecting the 2nd picture, it generates the third <input type="file">.... and so on.
Now, I want to add constraint that each member can have at most 5 pictures in their folder. Therefore, I use a PHP variable $pic_in_folder to to count how many picture the member has already had in the his/her folder.
// test.js
$(document).ready(function(){
var pic_in_folder //To receive PHP variable $pic_in_folder
var blockCount = 1; //To count how many #upload_block.
$("body").on("change", "#picture", function(){
//if( pic_in_folder + blockCount < 5 ){
$("#upload_block" + blockCount ).after($("<div/>", {
id: "upload_block"+ (blockCount + 1),
class: "upload_block",
style: "margin: 1rem;"
}).fadeIn("slow").append($("<input/>", {
name: "picture[]",
type: "file",
id: "picture"
})));
blockCount += 1;
//}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Upload Picture</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/test.js"></script>
</head>
<body>
<?php
$member_Id = $_GET["member"];
$pic_in_folder = 0; //Count how many pictures this member currently have
foreach(glob("picture/".$member_Id."/*") as $file){
if(file_exists($file)){
$pic_in_folder += 1;
}
}
?>
<h3>You currently have <?php echo $pic_in_folder; ?> pictures.</h3>
<hr/>
<form name="upload_form">
<div id="upload_block1" class="upload_block" style="margin: 1rem;">
<input type="file" name="picture[]" id="picture" />
</div>
<input type="submit" />
</form>
</body>
</html>
For the Javascript codes, in order to avoid member having more than 5 pictures after they uploading pictures, I use variable pic_in_folder to get values from PHP variable $pic_in_folder ; blockCount to count how many input block is showing in the form. And the Javascript only generates input block when (pic_in_folder + blockCount) < 5
However, My HTML & PHP codes are in one document and the Javascript is in the other one. How can I pass the $pic_in_folder to the Javascript document variables ?
Thank you very much !!

You can declare the Variable for JS in your PHP-File:
echo '<script>var pic_in_folder = ' . $pic_in_folder . '</script>';
This will make it available globally. Then you can just use pic_in_folder in your other JS file. But be sure to include your external JS AFTER you did the script-tag above, so the external file actually knows about the variable.
Regarding best practices, I'm not sure if this is a good approach but it worked for me in one of my projects. Hope it helps :)

You can create a hidden field to store the $pic_in_folder value.
<input type="hidden" id="pic_in_folder" name="pic_in_folder" value="<?php echo $pic_in_folder;?>" />
Then read this value in JavaScript as follows:
var pic_in_folder = $("#pic_in_folder").val();

How about this?
<?php
$member_Id = $_GET["member"];
$pic_in_folder = 0; //Count how many pictures this member currently have
foreach(glob("picture/".$member_Id."/*") as $file){
if(file_exists($file)){
$pic_in_folder += 1;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload Picture</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function picsInFolder() { return <?= $pic_in_folder;?>; }
</script>
<script src="/test.js"></script>
</head>
<body>
<h3>You currently have <?php echo $pic_in_folder; ?> pictures.</h3>
<hr/>
<form name="upload_form">
<div id="upload_block1" class="upload_block" style="margin: 1rem;">
<input type="file" name="picture[]" id="picture" />
</div>
<input type="submit" />
</form>
</body>
</html>
Then in your JS file you can call picsInFolder();
var pic_in_folder = picsInFolder();

Related

Save textarea data from HTML page to a TXT file

I am building a database server for an organization that I am a member of, and one of the options is that they need to be able to change a list of names. This list is in a txt file located in the webroot.
I have loaded the txt file content in a textarea in an html page, and now what I need to be able to do is to save the textarea content to the same file, in case we need to update or change the names.
I have tried this:
<textarea id="toroq" style="width: 100%; height: 200px;"><?php include("lista_toroq.txt") ?></textarea>
<input id="save_toroq" type="button" value="Save" onclick="WriteToFile();"/>
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var text=document.getElementById("toroq").innerText;
//var fileName=document.getElementById("TextArea2").innerText;
var s = fso.CreateTextFile("lista_toroq.txt", true);
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
the problem is that it is not saving the file
JavaScript is not able to edit or make changes directly to files stored on the web server without having some form of code running.
Using something like this:
<?php
if ($_POST["text"]) {
file_put_contents("file.txt", $_POST["text"]);
}
?>
The above code runs when $_POST["text"] has been set.
Change your HTML form to something like this:
<html>
<body>
<form method="POST">
<textarea name="text tyle="width: 100%; height: 200px;"></textarea>
<input type="submit" value="submit" />
</form>
</body>
</html>
You can store both of these bits of code in one PHP file. The result would be like this:
<?php
if (isset($_POST["text"])) {
$filename = "lista_toroq.txt";
$fileContent = file_get_contents ($filename);
$separator = "***********************";
$new_content = $_POST["text"].$separator.$fileContent
file_put_contents($filename, $new_content);
echo "Text added to file";
}
?>
<html>
<body>
<form method="POST">
<textarea name="text" tyle="width: 100%; height: 200px;"></textarea>
<input type="submit" value="submit" />
</form>
</body>
</html>
You cant write directly from javascript. You have to use PHP to write. You can use file_get_contents to get file content and you can use file_get_contents to write.
You can do something like below with HTML form.
<?php
if (isset($_POST["text"])) {
$filename = "lista_toroq.txt";
$fileContent = file_get_contents ($filename);
$separator = "***********************";
$new_content = $_POST["text"].$separator.$fileContent
file_put_contents($filename, $new_content);
echo "Text added to file";
}
?>

Reading data from text file using AJAX doesn't work as expected

I am writing a simple online message board where people can post messages. I hope people can see new messages without refreshing the page so I'm using jquery to do $.ajax() on a text file containing messages. What's very weird is, sometimes the ajax doesn't work. Even though the message.txt has been updated, the data read from it in ajax is still old.
I observed that after I make a modification of my code on the server, it would stop working correctly. And clearing all browser history also makes it stop working correctly for a while. I have no idea what's causing the problem.
This is the code in my php file
#!/usr/local/bin/php
<?php
ob_start();
session_name('message_board');
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<?php
if (!isset($_SESSION['loggedin']) or !$_SESSION['loggedin']) {
header('Location: index.php');
}
else {
?>
<?php
if (isset($_POST['message'])) {
$file = fopen('message.txt', 'a') or die('Can not open file');
date_default_timezone_set('America/Los_Angeles');
$date_time = new DateTime();
fwrite($file, $_POST['message'].'#~,'.$_SESSION['username'].'#~,'.$date_time->format('Y-m-d H:i:s').'#~;');
fclose($file);
}
?>
<head>
<meta charset="UTF-8">
<title>Message Board</title>
<link rel="stylesheet" type="text/css" href="msg_board.css">
<script src="https://code.jquery.com/jquery-latest.min.js" defer></script>
<script src="msg_board.js" defer></script>
</head>
<body>
<h1 id="msg_board_title">
Awesome Message board
</h1>
<form action="logout.php">
<p id="welcome_message">
Welcome to the Message Board! Your email address is <?php echo $_SESSION['username'] ?>
<input type="submit" value="log out">
</p>
</form>
<section id="all_messages">
</section>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<p>
<textarea rows="8" name="message" id="posting_area" required></textarea>
</p>
</fieldset>
<fieldset>
<input type="submit" value="Post">
</fieldset>
</form>
</body>
<?php } ?>
</html>
This is the javascript
$.ajax({
url: "message.txt",
dataType: "text",
success: function(data) {
let large_text = "";
if (data !== "") {
let msg_blocks = data.split("#~;");
for (let i = 0; i < msg_blocks.length - 1; ++i) {
temp = "<p>";
temp += msg_blocks[i].split("#~,")[0];
temp += "<br>";
temp += msg_blocks[i].split("#~,")[1];
temp += "<br>";
temp += msg_blocks[i].split("#~,")[2];
temp += "</p>";
large_text = temp + large_text;
}
}
else {
large_text = "<p>Post something! There hasn't been any messages yet!</p>";
}
$("#all_messages").html(large_text);
}
});
A sample from message.txt
Hi#~,hello#test.com#~,2019-06-04 17:58:35#~;
Not only would it stop working right after I clear browser history or change any file related to these on my server, it also doesn't fulfill the one reason I use AJAX. I'm hoping it would show new messages other users post on their computers without me having to refresh, but that doesn't happen either. I think my usage of php POST and javascript AJAX are very standard. I've spent an entire afternoon already and feeling nauseous literally. Please help!
Just to clarify: By AJAX not working properly, I mean it doesn't update the change to the webpage, even though I've checked the text file indeed has been updated by php. No errors reported anywhere.

Sending variable to php from Javascript, not working

I am trying to make images change on click to a value (a file name) collected from a text file with PHP. This is done by collecting the file as an array (data) and echoing the right item in the array with the help of a counter (counter). This counter is incremented on each click with Javascript, but I want to return this incremented variable to PHP, to be able to change the images. Is there a way to do this? This is my attempt so far, trying my hand at posting the variable (see full code further down):
<script>
var variableToSend = JSON.parse(localStorage.getItem('counter'));
$.post('lan7_old.php', {variable: variableToSend});
</script>
<?php $counter = $_POST['variable'];
echo $counter; ?
I thought that it ought to work to post as the page is refreshed on image click, but maybe I am mistaken here. Or is anything else wrong with my code? The images shown are still the first ones from the text file, but this is only because I add integers to counter in the PHP echo - there is no value set to the PHP counter variable.
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="styles.css">
<script src="jquery-3.1.1.min.js"></script>
</head>
<body>
<script>
// Saves counter variable although the page is refreshed
$(document).ready(function(){
if (localStorage.getItem('counter') === null) {
localStorage.setItem('counter', JSON.stringify(0));
}
// Incrementing counter until next page is needed
$("img").click(function(){
var counter = JSON.parse(localStorage.getItem('counter'));
if(counter < 60) {
counter += 4;
localStorage.setItem('counter', JSON.stringify(counter));
}
else {
localStorage.setItem('counter', JSON.stringify(0));
window.location.href = '8.php';
return false;
}
$("#test").text(localStorage.getItem('counter')); //for testing
// sending js variable to be obtained by PHP
var variableToSend = JSON.parse(localStorage.getItem('counter'));
$.post('lan7_old.php', {variable: variableToSend});
});
$("#test").text(localStorage.getItem('counter'));
});
</script>
<div class="main">
<h1>Heading</h1>
<p>Heading 2</p>
<div id="test">hello</div>
<?php $data = getData($subtest_nr);
// retrieving counter variable
$counter = $_POST['variable'];
echo $counter; //for testing ?>
<form id="myform" method="post">
<div class="four_images">
<div class="flex-item">
<input type="radio" name="image" value="7.11" id="alt1" class="hidden">
<label for="alt1"><img src="images/<?php echo $data[$counter+0]; ?>"></label>
</div>
<div class="flex-item">
<input type="radio" name="image" value="7.12" id="alt2" class="hidden">
<label for="alt2"><img src="images/<?php echo $data[$counter + 1]; ?>"></label>
</div>
<div class="flex-item">
<input type="radio" name="image" value="7.13" id="alt3" class="hidden">
<label for="alt3"><img src="images/<?php echo $data[$counter+2]; ?>"></label>
</div>
<div class="flex-item">
<input type="radio" name="image" value="7.14" id="alt4" class="hidden">
<label for="alt4"><img src="images/<?php echo $data[$counter+3]; ?>"></label>
</div>
<div>
<input type="submit" name="save" value="Save Image Selection">
</div>
</div>
</form>
</div>
</body>
</html>
Your page is only refreshed if counter reaches 60 or above (window.location.href = '8.php¨).
Php only renders server side, now you are doing a javascript post request but ignoring the response, so this doesn't do anything.
Either you need to make your php return a response which you by javascript use to update the page (the DOM tree), or you should reload the whole page with for example window.location.href = "index.php?counter=" + counter.

jQuery.get to read a file and use the data into a form

I want the script to do the following:
On page load, read a text file with a number (just one line)
Increment the number by 1
Insert the number in an <input> box of the form
Once <form> is submitted, write the number to the text file
When the form gets loaded again, it will rerun the code and the number will increment by 1. This is basically to pre-populate a field with a unique and progressive number prior to form submission.
I am currently using jQuery, PHP and of course HTML:
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js">
$.get("http://www.domain.com/tools/formdata.txt");
function test(){
$.get('http://www.domain.com/tools/formdata.txt', function(data){
x = data++;
});
}
</script>
</head>
<body onload="test()"/>
<form action="save_json.php" method="post">
Contract: <input type="number" name="contract" id="contract" value="x" /><br />
<input type="submit" id="submit" value="Invia" />
</form>
</body>
</html>
PHP
<?php
if(isset($_POST['contract'])) {
// if form fields are empty, outputs message, else, gets their data
if(empty($_POST['contract'])) {
echo 'All fields are required';
}
else {
// adds form data into an array
$formdata = $_POST['contract'];
if(file_put_contents('/var/www/domain/tools/formdata.txt', $formdata)) echo 'Data successfully saved';
else echo 'Unable to save data, try again or contact IT';
}
}
else echo 'Form fields not submitted';
?>
First: I recommend that instead of javascript, you do this with PHP file_get_contents('formdata.txt') at the start of your file, and then you echo it in. That way, the value will be there on load, rather than having to wait for the HTML to render and the javascript to run. Also, it is a much better practice and will let you do a lot more things if you choose to expand the page.
However, here's the solution to the issue presented:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
var x;
function test(){
$.get('file.txt', function(data){
console.log('data',data);
var x = ++data;
console.log('x',x);
$('#contract').val(x);
});
}
</script>
</head>
<body onload="test()"/>
<form action="aoeu.php" method="post">
Contract: <input type="number" name="contract" id="contract" /><br />
<input type="submit" id="submit" value="Invia" />
</form>
</body>
</html>
The things to note:
Close off your <script> tag including the jquery library, then open another one after it.
No need to do the first $.get() you have - save it for the function.
var x = data++; - this increments data AFTER its value has been assigned to x. So, it will never increase. Do ++data instead, and it increments before.
You need to place it somewhere afterwards. How you had the input (value='x') is just trying to put the character "x" into the input. Use javascript to edit the functions value, as in my example.
Your PHP works fine.

Using Javascript for setting PHP variable as HTML text field's value

I am a learning Javascript and PHP, I am trying to do this ,
I have stored some variables in a PHP session, i am trying to set the values present in the session as the values in the form's input field, i have used javascript for that purpose,
PHP :
<html>
<head>
<link rel='stylesheet' type='text/css' href='http://localhost/Matrix/frameCSS.css' />
<script lang='text/javascript' src='http://localhost/Matrix/gd.js'></script>
</head>
<body>
<?php
// ------- --------- -------- -------- ------
$debug=true;
dBug("Started Code Execution ... ");
function dBug($text)
{
global $debug;
if($debug) { echo "<p class='status'>debug : $text</p>"; }
else { return; }
}
// ------ ----------- ------------ -----------
$db = mysqli_connect("127.0.0.1","user","xyz","sample");
if(mysqli_connect_errno())
{
die(mysqli_connect_error());
}
session_start();
if($_SESSION['is_open']==true)
{
$username = $_SESSION['username'];
dBug('retreived username > '.$username);
}
?>
<table class="content">
<form method="POST" action="http://localhost/gen_det.php" onload="load_data()">
<tr>
<td>
Full Name :
</td>
<td>
<input type="text" class="txtbox" id='name'/>
</td>
</tr>
<tr>
<td>
Age :
</td>
<td>
<input type="text" class="txtbox" id='age' />
</td>
</tr>
<tr>
<td>
<p class='status' id='status'> </p>
</td>
</tr>
<tr>
<td colspan="2" align='center'>
<input type="submit" class="btn" onclick="return validateData();" value="save" />
<input type="button" class="btn" onclick="redirect()" value="cancel" />
</td>
</tr>
</form>
</table>
</body>
Javascript :
function load_data()
{
var name = document.getElementById('name');
var age = document.getElementById('age');
name.value = " <?php echo ''.$_SESSION['username']; ?> ";
age.value = " <?php echo ''.$_SESSION['username']; ?> ";
}
This page is actually inside a iframe in another page (if that is important). When I open this page, it opens , but the values aren't filled in the text fields. What have I done wrong ?
here is the method
<body onload="javascript: load_data('<?php echo $_SESSION['name']; ?>', '<?php echo $_SESSION['age']; ?>') >
and in the JS file you can define the function
function load_data(param_name, param_age)
{
var name = document.getElementById('name');
var age = document.getElementById('age');
name.value = param_name;
age.value = param_age;
}
Your <form> tag cannot have an onload attribute. This is simply not possible.
Try assigning the onload event to your <body> element:
<body onload="load_data();">
A better solution would be to directly register the event in the JavaScript code:
window.addEventListener("load", load_data);
For one, you're inserting your PHP data incorrectly. You can very easily produce JS syntax errors by directly dumping arbitrary PHP values into a JS context. You should ALWAYS use json_encode() to produce valid JS text:
name.value = <?php echo json_encode($_SESSION'username']); ?>;
json encoding will take care of any quoting/escaping necessary.
You don't mention HOW this JS is getting included in your site. If it's in (say) an external .js file, then by default this file will NOT be passed through the PHP interpreter, and you'll be sending raw un-executed PHP code to the browser, where it will be seen by the JS parser and rejected as a outright syntax error. That will kill the entire script block and your JS code dies right then and there.
If it is somehow being parsed/executed by the server, then you should directly hit that JS script file with your browser and see WHAT is being output. There could be other structural problems causing JS to ignore the entire script.
If you already have the value of the data within the PHP variable you can just build the required input element with the value already included
<input type="hidden" id="foo" name="foo" value="<?php echo $_SESSION['foo']; ?>"/>
When your event (click/submit) fires the target element will then contain the value
foo = document.getElementById('foo');
console.log(foo.value);
well is very simple, when a web page is loaded the load order they are as follows.
HTML->CSS->JavaScript->PHP.
So if you want to get that variable in your js file, you have to do it this way...
<html>
<head>
<link rel='stylesheet' type='text/css' href='http://localhost/Matrix/frameCSS.css' />
<script lang='text/javascript' src='http://localhost/Matrix/gd.js'></script>
<script>
function load_data()
{
var name = document.getElementById('name');
var age = document.getElementById('age');
name.value = "<?php echo ''.$_SESSION['username']; ?>";
age.value = "<?php echo ''.$_SESSION['username']; ?>";
}
</script>
</head>
<body>
...
</body>
</html>

Categories

Resources