Access file from project directory and modify it using Javascript - javascript

I have a .json file in the same directory as my html file. I want to access this file and modify it. This modified file data will be used to load the contents of the same html file.
How can I access the file and modify it in Javascript?
Being a newbie in Javascript, any help is appreciated.
Thanks.

HTML5 added a file api for interacting with files on your computer.
This HTML5Rocks article explains how to use it.
this MDN page also explains it
html
<input type="file" id="input" multiple onchange="handleFiles(this.files)">
js
var inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
var fileList = this.files; /* now you can work with the file list */
}
api link:
FileReader.readAsText()

You cannot do this solely with HTML and javascript. What you want to do requires reading the file on the web server, not from the user's hard drive. Therefore, you must use a back-end language, like PHP. It's actually pretty easy.
If you haven't used PHP before, you can test that you have access to it (almost everyone does except those on Microsoft OS web servers). Just create a new file called test.php and make it look like this:
<?php
echo 'Hello there';
Then, navigate to http://whatever_your_domain_is/test.php
To access your JSON document, you can either do it as the page is loading, as follows:
(1) Rename the page from .html to .php -- all this does is allow PHP to be processed on the page. Otherwise, it is exactly the same as an HTML page.
(2) Add a section like this at the top:
<?php
$filePath = "json_file_name.txt";
$handle = fopen($filePath, "r");
$json = fread($handle, filesize($filePath));
?>
(3) Later, in your javascript code, plop that into a variable, like this:
$(function(){
var imported = "<?php echo $json; ?>";
var json = $.parseJSON(imported); //or, JSON.parse(imported);
}); //END document.ready
Or, you can use AJAX to do it on demand (i.e., triggered by a user event, such as a button click).
Here are some examples that demonstrate how easy AJAX is.
Note that using AJAX will not allow you to avoid the back-end server language (PHP). AJAX code communicates with a back-end (PHP) file, which does the same work as that described in the above section, and sends the result back to the AJAX success function in the javascript. The advantage of AJAX is being able to do it on demand, instead of just when the page is initially rendered.
Other refs:
how to parse json data with jquery / javascript?

Related

Include PHP variables directly into js files

I would like to use js code, which works with php variables.
My situation now:
mainFile.php
<?
$myPHPvar = 1234;
?>
<html>
<body>
MY CONTENT
<script>
var myJSvar = <? echo $myPHPvar; ?>
</script>
<script src="myFile.js"></script>
</body>
</html>
myFile.js
// Here some js code where I access the myJSvar, which was set by $myPHPvar before
console.log(myJSvar);
This works ! But I would like to change this structure. I would like to move the myJSvar definition out from main file into the jsFile.
But If I move this line var myJSvar = <? echo $myPHPvar; ?> into the myFile.js it will not work, because this is not an php file.
Not I thought that this could be a solution:
I rename the myFile.js to myFile.php and change the code like this:
// Here some js code where I access the myJSvar, which was set by $myPHPvar before
<script>
var myJSvar = <? echo $myPHPvar; ?>
console.log(myJSvar);
</script>
and in the mainFile.php I changed <script src="myFile.js"></script> to include('myFile.php');
This works !
BUT:
First question of all: Is this a good idea to do it like this?
Second: The "problem" now: All my files are now php files, also the files, which includes mainly js code. That's not very beautiful, because now I can't see on the first view, which is an js file and which is a php file.
Thank you for your support !
Using PHP, echo the values to hidden HTML fields on the page.
When you know the page is done loading, read them back out using JavaScript.
Note, Ideally, you'd just make the data a separate AJAX/xhr/fetch call to a URL (JSON or XML formatted data is nice for this), but as a stop-gap, hidden fields will do the trick for basic PHP pages.
Similarly, you can echo some inline JavaScript (tags and all) and reference the variables elsewhere. This approach will work but is often referred to as "spaghetti code" because the intertwined front-end (JavaScript) and back-end (PHP) code makes for tricky debugging and does not scale well to larger code projects... months or years after, developers will find themselves scratching their heads as to where code lives, how it's generated, where new code should be placed, etc.
You can do it like this. And there's nothing really wrong with it. You have to bring the data to the client browser somehow. You can do this with: 1. set php variables in the DOM 2. XHR call or 3. cookies
This can be achieved by generating the JS file dynamically... You can create a PHP file that would generate the JS dynamically like:
Note: THIS METHOD IS HIGHLY NOT RECOMMENDED. THIS IS FOR YOUR INFORMATION AND KNOWLEDGE ONLY.
myFile.php (The JS equivalent file)
console.log(123)
Your HTML file
<script type="text/javascript" src="a.php"></script>
But this is highly not recommended because JS files are static resources that can be cached. Using this method would request the JS file every time the page loads (where it will only be transferred at first load only if its static).
The best method is to keep the dynamic variables in your HTML and then include your static JS files which will use these variables.

Javascript save variable to .txt file on server and overwrite the.txt content

I've been browsing this website and the only answers I found were for saving the variable on client side (ie using Download atribute).
In PHP, I've done this:
<?php
$tracktitle = "test";
$location = fopen("textfile.txt","w+");
fwrite ($location, $tracktitle);
fclose($location);
?>
What is the javascript equivalent of this? I want the content of textfile.txt to be deleted/replaced with the actual variable.
Let's say var tracktitle = "test";
I want to get some text from an HTTP page and store it in a .txt file (on FTP) then load the .txt content on an HTTPS website.
I will use chronjob to schedule this to run every 5 seconds.
There is no equivalent, at least in how you're asking. Javascript is client-side; it cannot directly write to a file on a server (unless you're talking about Node, which it doesn't seem like you are). To have Javascript write a file, at best it can make a request to your server side tech (PHP in this case) with information about what to write.

PHP include Javascript-generated filename?

while(x<=num_of_cpkgs){
var cpkg_navtray = '\'navtrays/' + cpkg_array[x] + '.html\'';
<?php include ?> cpkg_navtray <?php ; ?>;
x++;
}
cpkg_array contains potentially multiple file names. I'm wondering if there's a way to include a Javascript-generated filename in a PHP include statement like this?
This doesn't work like this.
TL;DR:
You need AJAX calls for this.
Longer:
When you load a page in your Browser, the server send you the file. If the file is a php file, then it calls the php to process the file. After the file is processed the server send it to you as a static file.
With JS you can do some interaction to the website. Until now you probably got used to sending each file as a GET or POST data with a form. With JS you have to make an XMLHttpRequest to create a dynamic request and your page is won't be refreshed again however you will get the response as a variable in JS.
Read all about this here.

PHP to Javascript: dirname and document_root

I got a little problem. I am working on a project and I got my root, then I got 2 folders: website1 and website2.
website1 is the staff panel, where the upload script is on (where this problem is on). website2 is the website the 'customer' will see. Here all the uploaded images, PDFs etc. are uploaded to.
So, I have a few notes before I start:
I cannot use PHP in my Javascript. The Javascript is in .js files and not in my .php file.
I cannot do this at my AJAX request as something client-side has to be done correctly to see the image.
So basically, I am in website1 and when I upload a file (with DropzoneJS (http://www.dropzonejs.com/)) it does a AJAX request. Here it has to upload a file to a directory in website2. In website1 I have to see that image after uploading it in a IMG tag.
So in PHP I got this:
$uploadPath = filter_input(INPUT_POST, 'uploadPath');
$uploadPath = dirname(getenv('DOCUMENT_ROOT')) . '/' . $uploadPath;
This works and the file gets uploaded to that directory. $uploadPath is this (in Javascript, sent as POST parameter in AJAX request):
/SITE2/assets/uploads/
Now I need to translate the dirname and getenv('DOCUMENT_ROOT') into Javascript. I tried document.location.hostname but this does return a different value than getenv('DOCUMENT_ROOT').
document.location.hostname: 127.0.0.1
getenv('DOCUMENT_ROOT'): D:/xampp/htdocs
How can I get the same value as getenv('DOCUMENT_ROOT') in Javascript?
In php file you can create script with JavaScript variable like this:
<script>
var DOCUMENT_ROOT = "<?= getenv('DOCUMENT_ROOT') ?>";
</script>
the other option is to have your JavaScript file as PHP script then you can use PHP code inside.
You have two options, but I caution you sending the actual file path on the server/disk to the client side is a bad idea.
Use Ajax so the client sends a request like $.ajax({url: "getdir.php", success: someJSFuntion } );
Change your JavaScript file to be a ".php" file and then include the code right in there.
There is no spec that says you can't have your JS file be a ".php" file. So you'd link to it like this:
<script type="text/javascript" src="/js/myjs.php"></script>
And that would let you use PHP directly in your JS file.
Check out php.js for a JavaScript port of dirname...
http://phpjs.org/functions/dirname/
As for getenv('DOCUMENT_ROOT'), you can't get this variable value via JavaScript. The reason for this is the client-side "location" of the JavaScript file says nothing about it's actual location on the server. The best you can do is get the parent directory of the file or the domain name.
For example:
http://example.com/path/to/file
The "DOCUMENT_ROOT" as far as JavaScript is concerned is...
/path/to
It seems very improper to even assume the need to have the server-side location of the file available to the JavaScript. I would simply use either a specific URL query that indicates what location to use, or to send the location back with the AJAX response since you can add whatever you need there.
{
"document-root": "/SITE2/assets/uploads/",
"normal-response": {
...
}
}
And then wherever you would normally use what is normally received, this use...
// For example
var response = JSON.parse (request.responseText);
// Normal response
console.log (response['normal-response'][...]);
// Document Root
console.log (response['document-root']);

"Unexpected token <" when using <?php in a Javascript file

Being new to this, I'm trying to pass a variable from PHP to Javascript.
In my php page, I use a test variable:
$testval = "x";
In my .js file:
var exarr = <?php echo json_encode($testval); ?>;
I've tried several things, but it seems I always get Unexpected token < when I include "
What am I doing wrong ?
Thanks !
In order to use PHP code in any file, the web server has to run that file through the PHP processor. This is configured to happen by default with .php files, but not with .js files.
You could configure your server to process .js files as PHP, but that's generally unwise. At the very least, it creates a lot of unnecessary overhead for those files since most of them won't (or shouldn't) have PHP code.
Without knowing more about the structure of what you're trying to accomplish, it's difficult to advise a "best" approach. Options include (but may not be limited to):
Defining that one var on a PHP page which references the JS file, thereby making it available to the JavaScript code.
Putting the value in a page element somewhere that it can be accessed by JavaScript code, either as a form value or perhaps a data value.
Making an AJAX request to the server to get that value (and other values) after the page has been loaded.
If you have that in a js file (like somefile.js) then PHP isn't going to parse that file by default. In the PHP file that links to that JS you can output a script tag and the var you want like:
echo "<script>var exarr = " . json_encode($testval) . "; </script>";
And make sure your script is linked in after that code;
.js files are not compiled by PHP. The easiest workaround is to put the Javascript in a <script> block within a .php, but you're making one of the most basic of serverside/clientside mistakes and should rethink your entire approach.

Categories

Resources