PHP include Javascript-generated filename? - javascript

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.

Related

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.

Access file from project directory and modify it using 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?

Using ajax or jsonp to retrieve php source code

Is there a way, using ajax or jsonp, to retrieve a php file source code?, the request is made by the same domain as the php files, I don't want the server to process the files, I only interesting with retrieval the content of the files, maybe there is a specific header used to request the server not to process the requested file?
The only solution I found is to change the file suffix, from .php to .txt/.html/etc but this solution is my last resort, if there is any other way I will be very thankful.
You could implement a php wrapper which your ajax code could request and pass in the file you would like to see the contents of:
Request via ajax: http://yourdomain.com/get_content.php?file=test.php
get_content.php:
<?php
if (isset($_GET['file'] && file_exists($_GET['file'])) {
echo file_get_contents($_GET['file']);
}
?>
Please do not use the code above in production mode, it is just an idea how to handle your problem.

Escape <?php ... ?> on javascript file

I'm busy doing server side and client side validation for magento. this validation works fine on server side (php)
on the client side i am using javasrcript.
When i started on this. i had my javascript embedded on a phtml file and everything was working as expected.
because i am using magento so I decided to inject the javascript file via page.xml
When I added the javascript code instead of getting the message pulled I get the php as is.
Here is my javascript:
function DefaultAddressErrorChangeNotAllowedMessage() {
alert("<?php echo Mage::helper('invent_general')->getDefaultAddressErrorChangeNotAllowedMessage();?>");
return;
}
I run this when a user hit the onclick it will point to this function DefaultAddressErrorChangeNotAllowedMessage()
and the
<?php echo Mage::helper('invent_general')->getDefaultAddressErrorChangeNotAllowedMessage();?>
will be populated as is.
but when I embed this directly to a phtml file it pull the correct message.
I there a way for javasrcipt that I can use to escape the php and get the correct message which is pulled from config.xml
PHP is rendered server side only. If you need to "inject" PHP specific values to your javascript, then you either need to render the actual value as part of the output of the php script, or you need to take a new roundtrip to the server, using Ajax.
Javascript is clientside, PHP is server side, so all php has been evaluated when javascript is loaded. This means, you can alert php echos, but you can't run PHP operations or any PHP logic in Javascript. You need ajax for this.
sorry for my clumsy answer, but maybe you lost the simple things.
I see that your javascript contains php tag, so i think you should insert your javascript code into .php extension because .js extension can't recognise the php tag.

Categories

Resources