Problem with value of $_GET from php to javascript

Discuss coding issues, and scripts related to PHP and MySQL.
User avatar
JanMolendijk
Posts: 184
Location: Holland Rotterdam

Problem with value of $_GET from php to javascript

I found a script from: tutorialzine.com/2014/09/cute-file-browser-jquery-ajax-php
what I wanna use for my website.

But I can`t find out how to place $id = (int) $_GET['id']; in the document
I`m now for 8 hours buisy to find-out without any succes

PLEASE HELP ME

I wanna place $_GET into this document scan.php
but when I place $id = (int) $_GET['id']; I don`t get any result

But when I put manual a number in WHERE id='' " it is working

Code: Select all

$sql = mysqli_query($conn,"SELECT * FROM `user` WHERE id='' ");
scan.php

Code: Select all

<?php
include "../inc/init.php";
include '../lib/pagination.class.php';

include "connection.php";
$sql = mysqli_query($conn,"SELECT * FROM `user` WHERE id='' ");
$users = mysqli_fetch_assoc($sql);
$dir = "$users[name]";

// Run the recursive function 
$response = scan($dir);

// This function scans the files folder recursively, and builds a large array
function scan($dir){
	$JanMolendijk = array();

	// Is there actually such a folder/file?

	if(file_exists($dir)){
	
		foreach(scandir($dir) as $f) {
		
			if(!$f || $f[0] == '.') {
				continue; // Ignore hidden files
			}

			if(is_dir($dir . '/' . $f)) {

				// The path is a folder

				$JanMolendijk[] = array(
					"name" => $f,
					"type" => "folder",
					"path" => $dir . '/' . $f,
					"items" => scan($dir . '/' . $f) // Recursively get the contents of the folder
				);
			}
			
			else {

				// It is a file

				$JanMolendijk[] = array(
					"name" => $f,
					"type" => "file",
					"path" => $dir . '/' . $f,
					"size" => filesize($dir . '/' . $f) // Gets the size of this file
				);
			}
		}
	
	}

	return $JanMolendijk;
}

// Output the directory listing as JSON

header('Content-type: application/json');

echo json_encode(array(
	"name" => "$users[name]",
	"type" => "folder",
	"path" => $dir,
	"items" => $response
));
?>
This under is the index file but the $_GET[id] is not working in the scan.php

Code: Select all

<?php 
include('connection.php');

$id = (int) $_GET['id'];

$sql=mysqli_query($conn,"SELECT * FROM `user` WHERE id='" . $id . "' ");
$users=mysqli_fetch_assoc($sql);
?>
okok{<?php echo $user->filter->username ?>}

<br><?php echo $user->filter->userid ?>

<br><br>
<?php echo $users['name'];?>

<!DOCTYPE html>
<html>
<head lang="en">
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<title>Cute file browser</title>
	<!-- Include our stylesheet -->
	<link href="assets/css/styles.css" rel="stylesheet"/>
</head>
<body>
	<div class="filemanager">

		<div class="search">
			<input type="search" placeholder="Find a file.." />
		</div>
		<div class="breadcrumbs"></div>
		<ul class="data"></ul>

		<div class="nothingfound">
			<div class="nofiles"></div>
			<span>No files here.</span>
		</div>

	</div>

	<footer>
        @ Molendijk        <div id="tzine-actions"></div>
        <span class="close"></span>
    </footer>

	<!-- Include our script files -->
	<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
	<script src="script.js"></script>
</body>
</html>

JanMolendijk
This is the code for the script.js

Code: Select all

$(function(){
	var filemanager = $('.filemanager'),
		breadcrumbs = $('.breadcrumbs'),
		fileList = filemanager.find('.data');

	// Start by fetching the file data from scan.php with an AJAX request
	$.get('scan.php', function(data) {
		var response = [data],
			currentPath = '',
			breadcrumbsUrls = [];

		var folders = [],
			files = [];

		$(window).on('hashchange', function(){
			goto(window.location.hash);
		}).trigger('hashchange');

		filemanager.find('.search').click(function(){
			var search = $(this);
			search.find('span').hide();
			search.find('input[type=search]').show().focus();
		});

		filemanager.find('input').on('input', function(e){
			folders = [];
			files = [];
			var value = this.value.trim();
			if(value.length) {
				filemanager.addClass('searching');
				window.location.hash = 'search=' + value.trim();
			}

			else {
				filemanager.removeClass('searching');
				window.location.hash = encodeURIComponent(currentPath);
			}

		}).on('keyup', function(e){
			var search = $(this);

			if(e.keyCode == 27) {

				search.trigger('focusout');

			}

		}).focusout(function(e){

			// Cancel the search

			var search = $(this);

			if(!search.val().trim().length) {

				window.location.hash = encodeURIComponent(currentPath);
				search.hide();
				search.parent().find('span').show();

			}

		});


	

		fileList.on('click', 'li.folders', function(e){
			e.preventDefault();

			var nextDir = $(this).find('a.folders').attr('href');

			if(filemanager.hasClass('searching')) {

				// Building the breadcrumbs

				breadcrumbsUrls = generateBreadcrumbs(nextDir);

				filemanager.removeClass('searching');
				filemanager.find('input[type=search]').val('').hide();
				filemanager.find('span').show();
			}
			else {
				breadcrumbsUrls.push(nextDir);
			}

			window.location.hash = encodeURIComponent(nextDir);
			currentPath = nextDir;
		});

		breadcrumbs.on('click', 'a', function(e){
			e.preventDefault();

			var index = breadcrumbs.find('a').index($(this)),
				nextDir = breadcrumbsUrls[index];

			breadcrumbsUrls.length = Number(index);

			window.location.hash = encodeURIComponent(nextDir);

		});


		// Navigates to the given hash (path)

		function goto(hash) {

			hash = decodeURIComponent(hash).slice(1).split('=');

			if (hash.length) {
				var rendered = '';

				// if hash has search in it

				if (hash[0] === 'search') {

					filemanager.addClass('searching');
					rendered = searchData(response, hash[1].toLowerCase());

					if (rendered.length) {
						currentPath = hash[0];
						render(rendered);
					}
					else {
						render(rendered);
					}

				}

				// if hash is some path

				else if (hash[0].trim().length) {

					rendered = searchByPath(hash[0]);

					if (rendered.length) {

						currentPath = hash[0];
						breadcrumbsUrls = generateBreadcrumbs(hash[0]);
						render(rendered);

					}
					else {
						currentPath = hash[0];
						breadcrumbsUrls = generateBreadcrumbs(hash[0]);
						render(rendered);
					}

				}

				// if there is no hash

				else {
					currentPath = data.path;
					breadcrumbsUrls.push(data.path);
					render(searchByPath(data.path));
				}
			}
		}


		function generateBreadcrumbs(nextDir){
			var path = nextDir.split('/').slice(0);
			for(var i=1;i<path.length;i++){
				path[i] = path[i-1]+ '/' +path[i];
			}
			return path;
		}


		// Locates a file by path

		function searchByPath(dir) {
			var path = dir.split('/'),
				demo = response,
				flag = 0;

			for(var i=0;i<path.length;i++){
				for(var j=0;j<demo.length;j++){
					if(demo[j].name === path[i]){
						flag = 1;
						demo = demo[j].items;
						break;
					}
				}
			}

			demo = flag ? demo : [];
			return demo;
		}


		// Recursively search through the file tree

		function searchData(data, searchTerms) {

			data.forEach(function(d){
				if(d.type === 'folder') {

					searchData(d.items,searchTerms);

					if(d.name.toLowerCase().match(searchTerms)) {
						folders.push(d);
					}
				}
				else if(d.type === 'file') {
					if(d.name.toLowerCase().match(searchTerms)) {
						files.push(d);
					}
				}
			});
			return {folders: folders, files: files};
		}


		// Render the HTML for the file manager

		function render(data) {

			var scannedFolders = [],
				scannedFiles = [];

			if(Array.isArray(data)) {

				data.forEach(function (d) {

					if (d.type === 'folder') {
						scannedFolders.push(d);
					}
					else if (d.type === 'file') {
						scannedFiles.push(d);
					}

				});

			}
			else if(typeof data === 'object') {

				scannedFolders = data.folders;
				scannedFiles = data.files;

			}


			// Empty the old result and make the new one

			fileList.empty().hide();

			if(!scannedFolders.length && !scannedFiles.length) {
				filemanager.find('.nothingfound').show();
			}
			else {
				filemanager.find('.nothingfound').hide();
			}

			if(scannedFolders.length) {

				scannedFolders.forEach(function(f) {

					var itemsLength = f.items.length,
						name = escapeHTML(f.name),
						icon = '<span class="icon folder"></span>';

					if(itemsLength) {
						icon = '<span class="icon folder full"></span>';
					}

					if(itemsLength == 1) {
						itemsLength += ' item';
					}
					else if(itemsLength > 1) {
						itemsLength += ' items';
					}
					else {
						itemsLength = 'Empty';
					}

					var folder = $('<li class="folders"><a href="'+ f.path +'" title="'+ f.path +'" class="folders">'+icon+'<span class="name">' + name + '</span> <span class="details">' + itemsLength + '</span></a></li>');
					folder.appendTo(fileList);
				});

			}

			if(scannedFiles.length) {

				scannedFiles.forEach(function(f) {

					var fileSize = bytesToSize(f.size),
						name = escapeHTML(f.name),
						fileType = name.split('.'),
						icon = '<span class="icon file"></span>';

					fileType = fileType[fileType.length-1];

					icon = '<span class="icon file f-'+fileType+'">.'+fileType+'</span>';

					var file = $('<li class="files"><a href="'+ f.path+'" title="'+ f.path +'" class="files">'+icon+'<span class="name">'+ name +'</span> <span class="details">'+fileSize+'</span></a></li>');
					file.appendTo(fileList);
				});

			}


			// Generate the breadcrumbs

			var url = '';

			if(filemanager.hasClass('searching')){

				url = '<span>Search results: </span>';
				fileList.removeClass('animated');

			}
			else {

				fileList.addClass('animated');

				breadcrumbsUrls.forEach(function (u, i) {

					var name = u.split('/');

					if (i !== breadcrumbsUrls.length - 1) {
						url += '<a href="'+u+'"><span class="folderName">' + name[name.length-1] + '</span></a> <span class="arrow">→</span> ';
					}
					else {
						url += '<span class="folderName">' + name[name.length-1] + '</span>';
					}

				});

			}

			breadcrumbs.text('').append(url);


			// Show the generated elements

			fileList.animate({'display':'inline-block'});

		}


		// This function escapes special html characters in names

		function escapeHTML(text) {
			return text.replace(/\&/g,'&amp;').replace(/\</g,'&lt;').replace(/\>/g,'&gt;');
		}


		// Convert file sizes from bytes to human readable units

		function bytesToSize(bytes) {
			var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
			if (bytes == 0) return '0 Bytes';
			var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
			return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
		}

	});
});


Admin
If $_GET['id'] isn't working it means that the php script is not accessed with an URL address with "?id=value".
The $_GET['id'] gets the value of 'id' from URL.
For example, if you have $_GET['id'] in index.php, you must access the file with: index.php?id=2.

Other thing, the following code from your script is wrong:

Code: Select all

$dir = "$users[name]";
Correct is:

Code: Select all

$dir = $users['name'];

The file scan.php is accessed with ajax from script.js. The $_GET['id'] can work in scan.php only if the file is accessed with: scan.php?id=Nr.
The solution is to output the $id from php into a js variable in index.php, then, add the variable as the value for 'id' in the ajax call.

For example, in index.php:

Code: Select all

<?php 
include('connection.php');

$id = isset($_GET['id']) ?(int) $_GET['id'] :'';
//your code ..
?>
<head lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Cute file browser</title>
<link href="assets/css/styles.css" rel="stylesheet"/>
<script>
var id_usr ='<?php echo $id; ?>';
</script>
</head>
In script.js:

Code: Select all

$.get('scan.php?id='+id_usr, function(data) {
  //code...
}
In scan.php:

Code: Select all

$id = isset($_GET['id']) ?(int) $_GET['id'] :'';
$sql = mysqli_query($conn,"SELECT * FROM `user` WHERE id=$id ");
//your code..

JanMolendijk
Thanks Chief for the support `it is working now`

Similar Topics