PHP - Hide Code hide div - javascript

Hey stackoverflow comunity i need to make this script hidden or show when if i clik on some Words like Upload or a button this script disiper or show i want to make this script hidden first when the user clik on Upload or a button this script will show.
This is the script
<?php require_once("maxUpload.class.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload File</title>
<link href="style/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
$myUpload = new maxUpload();
//$myUpload->setUploadLocation(getcwd().DIRECTORY_SEPARATOR);
$myUpload->uploadFile();
?>
</body>
maxUpload.class.php:
<?php
/*************************************************
* Max's File Uploader
*
* Version: 1.0
* Date: 2007-11-26
*
****************************************************/
class maxUpload{
var $uploadLocation;
/**
* Constructor to initialize class varaibles
* The uploadLocation will be set to the actual
* working directory
*
* #return maxUpload
*/
function maxUpload(){
$this->uploadLocation = getcwd().DIRECTORY_SEPARATOR;
}
/**
* This function sets the directory where to upload the file
* In case of Windows server use the form: c:\\temp\\
* In case of Unix server use the form: /tmp/
*
* #param String Directory where to store the files
*/
function setUploadLocation($dir){
$this->uploadLocation = $dir;
}
function showUploadForm($msg='',$error=''){
?>
<div id="container">
<div id="header"><div id="header_left"></div>
<div id="header_main">Max's File Uploader</div><div id="header_right"></div></div>
<div id="content">
<?php
if ($msg != ''){
echo '<p class="msg">'.$msg.'</p>';
} else if ($error != ''){
echo '<p class="emsg">'.$error.'</p>';
}
?>
<form action="" method="post" enctype="multipart/form-data" >
<center>
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
</label>
</center>
</form>
</div>
<div id="footer">Powered by PHP F1</div>
</div>
<?php
}
function uploadFile(){
if (!isset($_POST['submitBtn'])){
$this->showUploadForm();
} else {
$msg = '';
$error = '';
//Check destination directory
if (!file_exists($this->uploadLocation)){
$error = "The target directory doesn't exists!";
} else if (!is_writeable($this->uploadLocation)) {
$error = "The target directory is not writeable!";
} else {
$target_path = $this->uploadLocation . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$msg = basename( $_FILES['myfile']['name']).
" was uploaded successfully!";
} else{
$error = "The upload process failed!";
}
}
$this->showUploadForm($msg,$error);
}
}
}
?>

Hide your upload form by default, and show onclick of a button.
<body>
<div id="uploadForm" style="display:none">
<?php
$myUpload = new maxUpload();
//$myUpload->setUploadLocation(getcwd().DIRECTORY_SEPARATOR);
$myUpload->uploadFile();
?>
</div>
<input type="button" onclick="document.getElementById('uploadForm').style.display='block';">
</body>
If you want a link instead of button use
Upload

Related

Pop up box with message from php file

I have been working on a php file and would like to display whether a file has been uploaded or not
I have tried:
if (move_uploaded_file($file_tmp, $file)) {
echo "<script type='text/javascript'>alert('File sucessfully uploaded');</script>";
} else {
echo "<script type='text/javascript'>alert('Upload failed');</script>";
}
But it is not producing a pop up. However I can see it in the developer options under response. Any idea how I can solve this please?
You'll have to print alert(); inside a valid html. See this example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload</title>
</head>
<body>
<form name="form" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
Upload File: <input type="file" size="30" id="userfile" name="userfile">
<?php
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . "/upload/";
if (!is_dir($upload_dir)) {
#mkdir($upload_dir, 0755, true);
}
if (isset($_FILES['userfile'])) {
$temp_name = $_FILES['userfile']['tmp_name'];
$file_name = $_FILES['userfile']['name'];
$file_path = $upload_dir.$file_name;
}
if ((isset($_FILES['userfile'])) && (is_uploaded_file($_FILES['userfile']['tmp_name']))) {
if (#move_uploaded_file($temp_name, $file_path)) {
#chmod($file_path,0755);
echo "<script type='text/javascript'>alert('File sucessfully uploaded');</script>";
} else {
echo "<script type='text/javascript'>alert('Upload failed');</script>";
}
}
?>
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
This example works fine for me. I hope this helps.

How do I display a JavaScript alert using my PHP variables?

I am trying to bring up a javascript alert with my variables from php. My upload.php file so far is:
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('File successfully uploaded.\n![File Upload]('+window.location.href+')');
</script><?php
}
else
{
?><script>alert('Sorry, error while uploading file. Please try again');</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Photo Uploader for use in markdown</title>
</head>
<body>
<h2>Photo Uploader & Markdown generator</h2>
<p>Click 'Choose file' to choose the file to be uploaded. The filename should appear. Then click 'upload'. <br>A popup should show you what to copy and paste.</p>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
I then have my html code which looks like (only the relevant part included):
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
The purpose of this script is to upload a picture to a server and then display the markdown code for the user to use that image. I am aiming to output the following if the file uploads correctly:
![Alternative Text](http://www.example.com/folder/photo.jpg)
I have tried the following:
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('File successfully uploaded.\n![File Upload]('+window.location.href+.$folder.'/'.$pic.')');</script><?php
}
else
{
?><script>alert('Sorry, error while uploading file. Please try again');</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Photo Uploader for use in markdown</title>
</head>
<body>
<h2>Photo Uploader & Markdown generator</h2>
<p>Click 'Choose file' to choose the file to be uploaded. The filename should appear. Then click 'upload'. <br>A popup should show you what to copy and paste.</p>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
This results in a working webpage that uploads the file but does not show the js alert.
I have also tried the following:
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
<script>var folder = "<?php echo $folder ?>";</script>
<script>var pic = "<?php echo $pic ?>";</script>
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('File successfully uploaded.\n![File Upload]('+window.location.href+folder+'/'+pic+')');</script><?php
}
else
{
?><script>alert('Sorry, error while uploading file. Please try again');</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Photo Uploader for use in markdown</title>
</head>
<body>
<h2>Photo Uploader & Markdown generator</h2>
<p>Click 'Choose file' to choose the file to be uploaded. The filename should appear. Then click 'upload'. <br>A popup should show you what to copy and paste.</p>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
This results in an http error 500
Any advice?
Many thanks,
You can create a function in php and call it where ever you need to call alert.
Function :
function alertMsg($str) {
print("<script>alert('$str')</script>");
}
And call in php as
//string
alertMsg("Success");
//php variable
$alertMsg = "Some alert message";
alertMsg($alertMsg);
//even you can concatenate both
alertMsg("This is an alert. ".$alertMsg);
Hope this helps.
Thanks.
In both attempts you're trying to mix PHP, HTML, and JavaScript as though they were all the same language. They are not. From the perspective of any one of them, code in another one of them is nothing but a string. They can't directly share variables and logic.
See how this line:
alert('File successfully uploaded.\n![File Upload]('+window.location.href+.$folder.'/'.$pic.')');
is attempting to use PHP code (both the variables and the syntax) directly in JavaScript. This is simply resulting in syntax errors in your JavaScript, which your browser's development console is pointing out to you. Instead, enclose the PHP code in <?php ?> tags and echo the result:
alert('File successfully uploaded.\n![File Upload]('+window.location.href+'<?php echo $folder.'/'.$pic ?>'+')');
The second attempt has the same problem, you're putting HTML/JavaScript directly in your PHP:
$folder="uploaded_files/";
<script>var folder = "<?php echo $folder ?>";</script>
This is resulting in PHP syntax errors, which your PHP logs are telling you about (as well as the 500 Internal Server Error you're getting).
PHP code needs to be in <?php ?> tags. Always. So this would be something like:
$folder="uploaded_files/";
?>
<script>var folder = "<?php echo $folder ?>";</script>
<script>var pic = "<?php echo $pic ?>";</script>
<?php
if(move_uploaded_file($pic_loc,$folder.$pic))
Note also that in HTML/JavaScript you don't need a <script> tag for every line of JavaScript code. You can have multiple lines of code in a single <script> element.
Using variable PHP in JS
<?php
if (isset($_POST['btn-upload'])) {
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder = "uploaded_files";
if (move_uploaded_file($pic_loc, $folder . '/' . $pic)) { ?>
<script>
alert("File successfully uploaded! " +
"\n" +
location.hostname +
"<?php echo '/' . $folder . '/' . $pic; ?>");
</script>
<?php
} else { ?>
<script>alert("Sorry, error while uploading file. Please try again");</script>
<?php
}
}
?>
location.hostname = $_SERVER['HTTP_HOST'] // localhost

Read in PHP Div value into a $variable and in Javascript read file names of uploaded files into array

I have a few questions:
Part 1: I have a div with the id="hiddenID". I would like to create (if the sub folder does not exist) a subfolder with this id under the existing mainfolder sobimages.
And then to write the files in this new sub folder.
Note: Without the subfolder is it working!
Part 2: The uploaded files leave always the names and the success mnessage behind. I would like to delete this messages including the names of the uploaded files from the screen.
Part 3: Read before all file names in a simple Javascript array. I will then safe this with Json in the MySql-Databse. After your great help. I know how to do this, hehe
File body_editarticles.php
<?php session_start();
$_db_host = "myserver.com:3306";
$_db_username = "admin0";
$_db_passwort = "star1dgffh";
$_db_datenbank = "sob";
$_db_currentID ="";
# Verbindung zur Datenbank herstellen
$_link = mysql_connect($_db_host, $_db_username, $_db_passwort);
# Pr�fen ob die Verbindung geklappt hat
if (!$_link)
{
# Nein, also das ganze Skript abbrechen !
die("Keine Verbindung zur Datenbank m�glich: " .
mysql_error());
}
# Datenbank ausw�hlen
mysql_select_db($_db_datenbank, $_link);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/scroll.js"></script>
<script type="text/javascript" src="js/jquery.js" ></script>
<script type="text/javascript" src="js/jquery.uploadfile.min.js"></script>
</head>
<body class="page page-id-11505 page-template-default" onload="jsRecordCurrent();">
<div id="page-wrap">
<?php
include('includes/header.html');
?>
<div id="hiddenID" style="display: none;"></div>
<div id="mulitplefileuploader" title="">
<br>
Upload
</div>
<div id="status"></div>
<script>
$(document).ready(function()
{
var settings = {
url: "upload.php",
method: "POST",
allowedTypes:"jpg,png,gif",
fileName: "myfile",
multiple: true,
onSuccess:function(files,data,xhr)
{
$("#status").html("<font color='green'>Upload successful</font>");
},
onError: function(files,status,errMsg)
{
$("#status").html("<font color='red'>Upload failed</font>");
}
}
$("#mulitplefileuploader").uploadFile(settings);
});
</script>
</div>
</div>
</div>
<div id="aside">
</div>
<br class="clearfloat" />
</div> <!-- End of main container -->
</div><!-- END Page Wrap -->
<div id="footer">
<br class="clearfloat" />
</div>
</body>
</html>
file "upload.php"
<?php
//If directory doesnot exists create it.
$output_dir = "sobimages/";
if(isset($_FILES["myfile"]))
{
$ret = array();
$error =$_FILES["myfile"]["error"];
{
if(!is_array($_FILES["myfile"]['name'])) //single file
{
$fileName = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
//echo "<br> Error: ".$_FILES["myfile"]["error"];
$ret[$fileName]= $output_dir.$fileName;
}
else
{
$fileCount = count($_FILES["myfile"]['name']);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile"]["name"][$i];
$ret[$fileName]= $output_dir.$fileName;
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName );
}
}
}
echo json_encode($ret);
}
You could use mkdir to create folders and subfolders recursively before writing the files:
mkdir($path, 0777, true);
Note the third parameter, which means recursive
See the mkdir docs: http://php.net/manual/en/function.mkdir.php
1) send hiddenID value to ajax call
like var hiddenID = $("#hiddenID").val();
pass this id to ajax call, in PHP page you can get like $_POST['hiddenID];
then make a directory using the $_POST['hiddenID] using mkdir function (mkdir($pathtocreate, 0777, true);)
3) to read file names.....
http://www.html5rocks.com/en/tutorials/file/dndfiles/

Trying to get value from textbox on index.php and use it on upload.php

We have a simple upload application, just trying to upload files to a location using FTP, but before uploading the files we want users to enter in a name of a folder and we would create this folder then put the files in it. We can successfully do this entering in static values, but we need to pull the text from the textbox 'foldername' on index.php and use the value of foldername on upload.php and are having no success with POST or GET. Any help would be great.
index.php
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Image upload</title>
<link href='http://fonts.googleapis.com/css?family=Boogaloo' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript" src="js/multiupload.js"></script>
<script type="text/javascript">
var config = {
support : "image/jpg,image/png,image/bmp,image/jpeg,image/gif,text/plain,text/anytext,application/csv", // Valid file formats
form: "demoFiler", // Form ID
dragArea: "dragAndDropFiles", // Upload Area ID
uploadUrl: "upload.php" // Server side upload url
}
$(document).ready(function(){
initMultiUploader(config);
});
</script>
<link href="css/style.css" type="text/css" rel="stylesheet" />
</head>
<body lang="en">
<center><h1 class="title">Multiple Drag and Drop File Upload</h1></center>
<div id="dragAndDropFiles" class="uploadArea">
<h1>Drop Images Here</h1>
</div>
<form method="POST" name="demoFiler" id="demoFiler" enctype="multipart/form-data" action="upload.php" >
Please name your folder: <input type="text" name="foldername" id="foldername"/></br>
<input type="file" name="multiUpload" id="multiUpload" multiple />
<input type="submit" name="submitHandler" id="submitHandler" value="Upload" class="buttonUpload" />
</form>
<div class="progressBar">
<div class="status"></div>
</div>
</body>
</html>
upload.php
<?php
$newdir = $_POST['foldername'];
$dir = '/1';
$connect = ftp_connect('server');
ftp_login($connect, 'user', 'password');
ftp_pasv($connect, true);
ftp_chdir($connect, $dir);
if($_SERVER['REQUEST_METHOD'] == "POST"){
if (#ftp_chdir($connect, $newdir)){
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name']; //3
$targetFile = $_FILES['file']['name']; //5
ftp_put($connect, $targetFile, $tempFile, FTP_ASCII);
}
}
else
{
ftp_mkdir($connect, $newdir);
ftp_chdir($connect, $newdir);
if (!empty($_FILES))
{
$tempFile = $_FILES['file']['tmp_name']; //3
$targetFile = $_FILES['file']['name']; //5
ftp_put($connect, $targetFile, $tempFile, FTP_ASCII);
}
}
}
ftp_close($connect);
echo($_POST['index']);
exit;
?>
The solution to this is in multiupload.js you need to add a line to the _uploader function as such :
data.append('index',ids');
data.append('foldername', $('#foldername').val());
The foldername line is the line you need to add, should be around line number 72 based on the github version.

ajax form not finding javascript function

I can't seem to figure out what I'm doing wrong with this no matter how many things I try. I've looked through Google for a related issue but found nothing specific. Hopefully someone can help me.
The script runs through a external .js file calling a list of music albums, then listing the song of the album chosen via ajax. The user can then edit of delete the songs. Everything works fine until I submit the edited information through a form. When I click the submit button I get a web developer error "updateSong is not a function"
Here's the form:
<?php
include("database.php");
$song = $_GET['song'];
$query = "SELECT * FROM song INNER JOIN genre ON song.gID = genre.gID INNER JOIN album ON song.alID = album.alID WHERE sID = '$song'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo ("
<form action='#' method='POST' name='updateSong' onSubmit='updateSong(\"$song\")'>
<input name='songName' type='text' value='$row[songName]' />
<input type='text' id='genreSearch' name='genre' alt='Genre Search' onkeyup='searchSuggest();' autocomplete='off' value='$row[genreName]'/>
<div id='genre_search_suggest'></div>
<input name='songURL' type='text' value='$row[songUrl]' />
<input name='sID' type='hidden' value='$row[sID]' />
<input name='Submit' type='Submit' value='Update Song' />
</form>
");
}
?>
Here's the javascript:
function updateSong(sID) {
if(ajax) {
var song = sID;
alert("2");
ajax.open('get', './song_update.php' + encodeURIComponent(sID));
alert("3");
ajax.onreadystatechange = function() {
handleResponse(ajax);
}
ajax.send(null);
return false;
}
}
//EDIT//
Here's the page it's loaded into. I removed the unnecessary stuff around what this question is dealing with.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="artistPageStyle.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="javascripts/artistAjax.js"></script>
</head>
<body>
<div id="mediaPlayerBox">
<div id="artistAlbumList">
<?php
$query = "SELECT * FROM `album` INNER JOIN artist ON album.aID = artist.aID WHERE artist.LoginKey = '$token'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo ("<div id='artistAlbumBox'><div id='artistAlbum'><a href='#' onclick='loadAlbum($row[alID])'><img src='$row[albumCover]' width='75px' height='75px' border='0px' ></a></div><div id='artistAlbumLabel'>$row[albumName]</div></div>");
}
?>
</div>
</div>
</body>
</html>
Shouldn't it be: onSubmit='updateSong("$song")'?
try doing onSubmit='return updateSong($song)'
It's saying it is not a function because it isn't loaded, are you loading the external script in the display page at all?

Categories

Resources