Calling a php variable in JS does not work - javascript

I’m trying to make a user input by reading the contents of my server directory with php. So the user can select a file, in my case a CSV file which gets saved into a variable and then gets processed further down in my JavaScript code that should make a chart from it. All it does now is output the path string of the selected file. I tried using the json_encode function but it still doesn’t seem to work.
<?php
$dir = '/var/www/html/';
$graphen = '';
if (!isset($_POST['submit'])) {
if ($dp = opendir($dir)) {
$files = array();
while (($file = readdir($dp)) !== false) {
if (!is_dir($dir . $file)) {
$files[] = $file;
}
}
closedir($dp);
} else {
exit('Directory not opened.');
}
if ($files) {
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">';
foreach ($files as $file) {
echo '<input type="checkbox" name="files[]" value="' . $file . '" /> ' .
$file . '<br />';
}
echo '<input type="submit" name="submit" value="submit" />' .
'</form>';
} else {
exit('No files found.');
}
} else {
if (isset($_POST['files'])) {
foreach ($_POST['files'] as $value) {
$graphen .= $dir . $value . '<br />';
}
} else {
exit('No files selected');
}
}
echo $graphen;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="highcharts.js"></script>
<script src="data.js"></script>
<script src="exporting.js"></script>
<script src="export-data.js"></script>
<script src="accessibility.js"></script>
<script src="jquery-3.5.1.min.js"></script>
</head>
<body>
<div id="container1"></div>
<script type="text/javascript">
var fileName = <?php echo json_encode($graphen); ?>; //doesn't work
$.ajax({
type: "GET",
url: fileName,
success: function (data) {
drawChart(data)
}
});
function drawChart(raw_data) {
//my code to draw chart is here and working
}

If you assign a String to a variable in JavaScript, use " or ':
var x = "Hello";
Your current code results in
var fileName = <?php echo json_encode($graphen); ?>; => var fileName = variable;
Add quotes and it should work:
var fileName = '<?php echo json_encode($graphen); ?>'; => var fileName = 'variable';

Related

How to Show result after uploaded file in PHP

I have a script that uploads the video to a server, everything is correct but there is a problem, after the upload of the video to the server is completed
it shows all the uploaded files in the (uploads) folder as array!
I only want the result of the file I just uploaded, and it doesn't show me the previous files!
I need ffmpeg to improve video quality
index.php
<?php
//index.php
?>
<!DOCTYPE html>
<html>
<head>
<title>Personal Video Uploader</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.js"></script>
<link rel="stylesheet" href="css/main.css">
</head>
<body class="bg-body">
<div class="container">
<form action="upload.php" class="dropzone font" id="dropzoneFrom">
</form>
</form>
<br />
<div id="preview"></div>
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
Dropzone.options.dropzoneFrom = {
autoProcessQueue: true,
timeout: 300000,
acceptedFiles:"video/*",
init: function(){
var submitButton = document.querySelector('#submit-all');
myDropzone = this;
submitButton.addEventListener("click", function(){
myDropzone.processQueue();
});
this.on("complete", function(){
if(this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
{
var _this = this;
_this.removeAllFiles();
}
list_image();
});
},
};
list_image();
function list_image()
{
$.ajax({
url:"upload.php",
success:function(data){
$("#preview").html(data);
}
});
}
$(document).on('click', '.remove_image', function(){
var name = $(this).attr('id');
$.ajax({
url:"upload.php",
method:"POST",
data:{name:name},
success:function(data)
{
list_image();
}
})
});
});
</script>
upload.php
<?php
//upload.php
$folder_name = 'upload/';
$tumb_name = 'thumb/';
$imageext = '.png';
if(!empty($_FILES))
{
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
$upload = $_FILES['file']['name'];
$uploadStr = str_replace(" ", "\ ",$upload);
$locationStr = str_replace(" ","\ ",$location);
$cmd = "ffmpeg -y -i {$locationStr} -ss 00:00:15 -vframes 1 thumb/{$uploadStr}.png 2>&1";
echo shell_exec($cmd);
}
if(isset($_POST["name"]))
{
$filename = $folder_name.$_POST["name"];
$imagename = $thumb_name.$_POST["name"].$imageext;
unlink($filename);
unlink($imagename);
}
$result = array();
$files = scandir('upload');
$output = '<div class="row">';
if(false !== $files)
{
foreach($files as $file)
{
if('.' != $file && '..' != $file)
{
$output .= '
<img src="thumb/'.$file.'.png" class="img-thumbnail" width="246px" height="138px" style="height:138px;" />
<button type="button" class="btn btn-link remove_image" id="'.$file.'">Remove</button>
';
}
}
}
$output .= '</div>';
echo $output;
?>
EDIT:
I put the example on an Array, I don't want it, I just want it to show the downloaded video I just uploaded as a result.
EDIT 2 :
There are some who say type $location and it displays the downloaded file, but this does not work!!!
I just tried more than once and with several uses, there is no display where the text is empty
This is an example of that
<?php
//upload.php
$folder_name = 'upload/';
$tumb_name = 'thumb/';
$imageext = '.png';
if(!empty($_FILES))
{
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
$upload = $_FILES['file']['name'];
$uploadStr = str_replace(" ", "\ ",$upload);
$locationStr = str_replace(" ","\ ",$location);
$cmd = "ffmpeg -y -i {$locationStr} -ss 00:00:15 -vframes 1 thumb/{$uploadStr}.png 2>&1";
echo shell_exec($cmd);
}
if(isset($_POST["name"]))
{
$filename = $folder_name.$_POST["name"];
$imagename = $thumb_name.$_POST["name"].$imageext;
unlink($filename);
unlink($imagename);
}
$output .= 'Successfly file is "'.$location.'"';
echo $output;
?>
Result : Successfly file is ""
no name file :(
EDIT 3 :
this code upload.php
functions not working
<?php
//upload.php
$folder_name = 'upload/';
$tumb_name = 'thumb/';
$imageext = '.png';
if(!empty($_FILES))
{
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
$upload = $_FILES['file']['name'];
$uploadStr = str_replace(" ", "\ ",$upload);
$locationStr = str_replace(" ","\ ",$location);
$cmd = "ffmpeg -y -i {$locationStr} -ss 00:00:15 -vframes 1 thumb/{$uploadStr}.png 2>&1";
echo shell_exec($cmd);
}
echo "The file " . $location . " has been uploaded";
// not working
echo "<br>";
echo "The file " . $upload . " has been uploaded";
// not working
echo "<br>";
echo "The file " . $uploadStr . " has been uploaded";
// not working
echo "<br>";
echo "The file " . $locationStr . " has been uploaded";
// not working
?>
this error:
[23-Apr-2022 12:31:56 Asia/Riyadh] PHP Notice: Undefined variable: location in /home/prdix/public_html/test/upload.php on line 38
line 38: echo $location;
About the developer solution Markus AO
I did the experiment and it is quite good, but dropzone is still missing, because I will upload a large video and the normal upload compresses the video before uploading, here is a picture from my mobile while uploading, but this does not happen with dropzone
I want to implement this in dropzone as well, because this library does not compress the video, but upload it in full size.
Thank you bro.

Issues appending strings in PHP

I'm using Codeigniter and had written a method to create css/js links, concatenate them and then pass them to my view. It was working before, until I decided to create a clean copy of the project with the latest CI version and it's not working now.
The part of the method that concatenates the data is the following:
foreach ($header_css as $item) {
$str .= '<link rel="stylesheet" href="'. base_url() . $item . '" type="text/css" />';
}
There's a similar one for the JS files. When printing the previous piece of code I'm getting an empty string, so I decided to use htmlentities:
foreach ($header_css as $item) {
$str .= htmlentities('<link rel="stylesheet" href="'. base_url() . $item . '" type="text/css" />');
}
and it works... partially. I mean, if I print at this point the string with the links are there but now when I pass the string to the view the data is being printed on screen instead of being added to the head. So this is my view:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo (isset($title)) ? $title : ''; ?></title>
<meta name="description" content="Test">
<meta name="author" content="Test">
<?php
# load assets
echo (isset($assets)) ? $assets : '';
?>
<script>var ajax_home = "<?php echo base_url(); ?>ajax/";</script>
</head>
<body>
The part that echoes the assets is printing the content of the variable on screen instead of parsing the assets as <script>...</script> or <link rel="stylesheet" ... />
Any indication on why this is happening?
Thanks.
The part of the method that concatenates the data is the following:
foreach ($header_css as $item) {
$str .= '<link rel="stylesheet" href="'. base_url() . $item . '" type="text/css" />';
}
There's a similar one for the JS files. When printing the previous piece of code I'm getting an empty string, so I decided to use
htmlentities: Below Code is NOT FOR JavaScript, it's for Style sheet
foreach ($header_css as $item) {
$str .= htmlentities('<link rel="stylesheet" href="'. base_url() . $item . '" type="text/css" />');
}
it should be like,
foreach ($header_js as $item) {
$str .= "<script type='text/javascript' src='". base_url() . $item . "'/>";
}
& Your Views has (Ahem!):
<?php
# load assets
echo (isset($assets)) ? $assets : '';
?>
So, My Question is:
Where is $str variable and why you are not using inside view instead of $assets it should be echo (isset($str)) ? $str : '';
I am assuming that you are using your function inside your controller as method & storing all js & css file build in that
variable. So.. are you returning that $str variable.. ?
Well, Here is some example for you, Hope you can solve your problem :)
/**
* Build Css or Script link
* #param array $assets [description]
* #param string $type [description]
* #return [type] [description]
*/
function build_assets($assets = array(), $type = 'css')
{
$str = '';
if (!empty($assets) && is_array($assets) && $type == 'css') {
foreach ($assets as $key => $file) {
$str .= "<link type='text/css' rel='stylesheet' href='" . base_url($file) . ".css' />";
}
} elseif (!empty($assets) && is_array($assets) && $type == 'javascript') {
foreach ($assets as $key => $file) {
$str .= "<script type='text/javascript' src='" . base_url($file) . ".js'></script>";
}
}
return $str;
}
/**
* Testing the method
* #return [type] [description]
*/
function index()
{
$data = [];
// get all style sheets
$style = $this->build_assets(['style', 'page', 'form']);
// get all js files
$script = $this->build_assets(['style', 'page', 'form'], 'javascript');
// assign in 'assets' variable
$data['assets'] = $style . $script;
// send to template/view
$this->load->view('ViewTemplate', $data);
}
& Views Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CodeIgniter</title>
<!-- CSS and JavaScript -->
<?php echo isset($assets) ? $assets : '' ?>
<!-- End Here -->
</head>
<body>
<di class="welcome">Say Hello to CodeIgniter!!!</di>
</body>
</html>

Passing argument from javascript to PHP function

I am using jqueryfiletree to display a folder of files on the web server. I also have php to parse the csv and display it on the page. How can I pass the selected jqueryfiletree file to the php in the page so it displays the selected csv? Here's what I have so far:
Javscript:
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.easing.js" type="text/javascript"></script>
<script src="jqueryFileTree.js" type="text/javascript"></script>
<link href="jqueryFileTree.css" rel="stylesheet" type="text/css"
media="screen" />
<script type="text/javascript">
$(document).ready( function() {
$('#fileTreeDemo_1').fileTree({ root: '../data/', script:
'connectors/jqueryFileTree.php' }, function(file) {
alert(file);
var file = "<?php echo $file;?>";
});
});
</script>
</head>
<body>
<h1>Select a file to view</h1>
<div class="menuleftcontent">
<div id="fileTreeDemo_1" class="demo"></div>
</div>
</td><td>
PHP
<div class="maincontent">
<?php
$row = 1;
if (($handle = fopen($file, "r")) !== FALSE) {
echo '<table border="1">';
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<thead><tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
//echo $data[$c] . "<br />\n";
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
echo '<td>'.$value.'</td>';
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
?>
</div>
I can see two problems so far. Firstly, you do not have a semi-colon to end the line on this line:
var file = "<?php echo $file;?>";
(i've added it).
Also, $file is not defined in your php. And you can not try and define it in javascript (I fear that is what you are trying to do maybe?).
Best options is to make an AJAX request so you can send it to the server side and use it there (which is what you want?). And of course, you can then respond data back to the front end.
THis is a rough idea:
$('#fileTreeDemo_1').fileTree({ root: '../data/', script:
'connectors/jqueryFileTree.php' }, function(file) {
$.post('myphpfile.php', {file:file}, function(response){
// handle response
});
});
and then in php, check for the post with if(isset($_POST['file'])) ,etc etc

Javascript call php function and receives back results

This postprovides sample code using obtaining a server file list as an example. Here is the code I have used:
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>How to create form using jQuery UI</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/pepper-grinder/jquery-ui.css" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$.get('getfilename.php', { dir : '/ajax1/' }, function(data) {
// you should now have a json encoded PHP array
$.each(data, function(key, val) {
alert('index ' + key + ' points to file ' + val);
});
}, 'json');
alert ("ok");
});
</script>
</head>
<body>
<h1>Get file names... </h1>
</body>
</html>
getfilename.php
$dir = $_REQUEST['dir'] ;
$dir = $_SERVER['DOCUMENT_ROOT'] . $dir;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file) {
if ($file!='.' && $file!='..' ) {
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'';
$Counter++;
}
}
echo json_encode($filesArray);
My problem is that the javascript alert alert('index ' + key + ' points to file ' + val); fails to display anything on the page. The script is working because I get a response in the Firebug console log.
ajax.jsajax.phpindex.html["ajax.js","ajax.php","index.html"]
What I need to change on the script to return this information to the html page so that I can use the JSON for further processing ?
Thanks.
With your debug you broke the JSON output in PHP. So, remove:
echo $filesArray[$Counter].'';
Also, before any output, you should add JSON header:
header('Content-Type: application/json');
At the end, your PHP file should look like this:
$dir = $_REQUEST['dir'] ;
$dir = $_SERVER['DOCUMENT_ROOT'] . $dir;
$filesArray = array();
$files = scandir($dir);
foreach ($files as &$file) {
if ($file!='.' && $file!='..' ) {
$filesArray[] = $file;
}
}
header('Content-Type: application/json');
echo json_encode($filesArray);

PHP `file_get_contents()` output pass to JavaScript and calculate length

I want to pass the output from PHP's file_get_contents() to JavaScript and calculate its length. Everything ok but when passing the variable JavaScript evaluates it as HTML code, so I have to use PHP's json_encode() to keep it "sane" but this way the string length from JavaScript will be different from the one in PHP. Using JS's JSON.parse() doesn't help because again the HTML code gets interpreted. Any idea how can I achieve the same evaluated data length?
EDIT: Basically I need to count all the characters in the page source, that includes tags and special characters. To have the same output computed in JS like the one i get in PHP's strlen($url_data).
EDIT 2: I thought about doing bin2hex() on the $url_data then reconvert in JS and check the length. Would be that reliable?
Here is what I did so far:
<?php
ini_set('display_erros', -1);
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['urlinput']) && !filter_var($_POST['urlinput'], FILTER_VALIDATE_URL) === false) {
$url = filter_var($_POST['urlinput'], FILTER_SANITIZE_URL);
$url_data = #file_get_contents($url);
$js_url_data = json_encode($url_data);
//$url_src = htmlspecialchars($url, ENT_IGNORE);
$url_data_len = mb_strlen($url_data);
$url_src = strip_tags($url_data);
echo '<ul id="resultList">';
echo "<li>The following page contains " . $url_data_len . " characters</li>";
echo "<li>Page URL: " . $_POST['urlinput'] . "</li>";
echo "<li>Page title: " . page_title($url_data) . "</li>";
echo "<li>Protocol: " . parse_url($url, PHP_URL_SCHEME) . "</li>";
echo "<li>Host: " . parse_url($url, PHP_URL_HOST) . "</li>";
echo "</ul>";
//var_dump($url_src);
} else {
$error = "URL is not valid!";
}
}
function page_title($str) {
$matches = array();
if (preg_match('/<title>(.*?)<\/title>/i', $str, $matches)) {
return $matches[1];
}
else {
return null;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP file_get_contents()</title>
</head>
<body>
<div class="url_class">
<form id="getsrc" method="post">
<input style="width: 300px;" type="text" name="urlinput" id="urlinput" placeholder="URL">
<input type="submit" name="submit" value="Get SRC">
</form>
</div>
<textarea rows="20" cols="50">
<?php
if (!empty($url_src)) {
echo $url_src;
}
?>
</textarea>
<?php echo '<br><span style="color:red">' . $error . '<span>'; ?>
<?php
if (!empty($js_url_data)) {
$script = <<<EOT
<script>
var url_data = $js_url_data;
var node = document.createElement("li");
var textnode = document.createTextNode("JavaScript page characters: " + url_data.length);
node.appendChild(textnode);
document.getElementById("resultList").appendChild(node);
</script>
EOT;
echo $script;
}
?>
</body>
</html>
Simply use the value calculated by php, it can be used within EOT block:
...
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['urlinput']) && !filter_var($_POST['urlinput'], FILTER_VALIDATE_URL) === false) {
...
$url_data = #file_get_contents($url);
$fileSize = strlen($url_data);
...
}
....
if (!empty($js_url_data)) {
$script = <<<EOT
<script>
...
var textnode = document.createTextNode("JavaScript page characters: " + $fileSize);
...
</script>
EOT;
echo $script;
Since no good answer, I would post my solution to my problem. The only way I could find was to hex-encode $url_data, pass it to JS, decode it and count the characters. For the pack() function I used the one ported in php.js.
...
$js_url_data = bin2hex($url_data);
...
if (!empty($js_url_data)) {
/* This is a good example when one is forced to use inline JS */
$script = <<<EOT
<script>
var url_data = "$js_url_data";
var url_data_len = pack('H*', url_data).length;
var node = document.createElement("li");
var textnode = document.createTextNode("JavaScript calculation page characters: " + url_data_len);
node.appendChild(textnode);
document.getElementById("resultList").appendChild(node);
</script>
EOT;
echo $script;
...

Categories