Running PHP Script from HTML Leads to Blank PHP Page - php

(Note: Updated title to better match the question)
I am working on adding an image upload feature to ajax chat, and I have the HTML and PHP already written (basically copied from W3Schools) to do this. I have a test HTML page set up on the server to test the image uploads and that works just fine - the form works and the file is uploaded when the "Upload Image" button is pressed (to execute the PHP upload code). However, once the upload is complete the page switches to a blank page with the URL for my upload.php file.
I am currently using a modal in HTML to initially hide the image upload form and only appear when the "Image" button in the chat is pressed. The code is very simple, and as I said is basically the same as seen in the above link but placed inside a modal.
And before anyone complains, I know PHP is easy to exploit and can be dangerous when put on a website but this has been determined to be a non-issue in my case.
Below is the code for the image upload modal. Please pardon all the in-line CSS, I will eventually move it to its own stylesheet but have been using in-line for development purposes. Note that display is set to block for debugging. For the live site it would be set to none and a javascript function is used to set it to block when the "Image" button is pressed in the chat module.
<html>
<body>
<div id="imageUploadModal" style="display:block; position:fixed; z-index:1; left:0; top:0; width:100%; height:100%;.
overflow:auto; background-color:rgb(0,0,0); background-color:rgba(0,0,0,0.4);">
<div style="background-color:#fefefe; margin:15% auto; padding:20px; border:1px solid #888; width:80%;">
<span style="color:#aaa; float:right; font-size:28px; font-weight:bold;">×</span>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image:
<input type="file" name="fileToUpload" id="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
</div>
</div>
</body>
</html>
UPDATE:
Below are the contents of upload.php:
<?php
// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is an actual image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
//The file is an image
$uploadOk = 1;
} else {
//The file is not an image
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
//The file already exists
$uploadOk = 0;
}
// Check file size
if (2000000 < $_FILES["fileToUpload"]["size"]) {
//The file is too large
$uploadOk = 0;
}
// Allow certain file formats
if (($imageFileType != "jpg") && ($imageFileType != "png")
&& ($imageFileType != "jpeg") && ($imageFileType != "gif")) {
//Only JPG, JPEG, PNG, and GIF files are allowed
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
//The file was not uploaded
exit();
// if everything is ok, try to upload the file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
exit();
} else {
//There was an error uploading the file
exit();
}
}
?>
EDIT: Updated HTML/Javascript
// Ajax image upload
$(document).ready(function() {
$("#uploadForm").submit(function(event) {
event.preventDefault();
var $form = $("#uploadForm");
var serializedData = $form.serialize();
var request = $.ajax({
type: "POST",
url: "/upload.php",
data: serializedData
});
request.done(function() {
console.log("AJAX Success!");
closeImageUploadModal();
});
})
});
HTML:
<div id="imageUploadModal" style="display:none; position:fixed; z-index:1; left:0; top:0; width:100%; height:100%;
overflow:auto; background-color:rgb(0,0,0); background-color:rgba(0,0,0,0.4);">
<div style="background-color:#0e0e0e; color:#aaa; margin:15% auto; padding:20px; border:1px solid #888; width:50%;">
<span id="close" style="color:#aaa; float:right; font-size:28px; font-weight:bold;" onclick="closeImageUploadModal()">×</span>
<form id="uploadForm">
<h3><b>Select image:</b></h3>
<input type="file" name="fileToUpload" id="fileToUpload" accept=".jpg, .JPG, .png, .PNG, .jpeg, .JPEG, .gif, .GIF"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
</div>
</div>

How to upload a file without refreshing or redirecting.
Method 1: Plugins
Plugins would probably be the best for you, since they are usually well tested and relatively bug free and require hardly any work to get it running. There are a number of plugins you can use, I have them listed below.
jQuery File Uploader
Multiple File Upload Plugin
Mini Multiple File Upload
jQuery File Upload
Method 2: Other StackOverflow Answers
There has been plenty of answers for this type of problem. I have listed some below.
How can I upload files asynchronously?
jQuery AJAX file upload PHP
How to use $.ajax() for input field text AND FILE upload?
jQuery Ajax File Upload
File Upload Ajax PHP
Additional Sources to look at
https://www.sanwebe.com/2012/06/ajax-file-upload-with-php-and-jquery
https://www.formget.com/ajax-image-upload-php/
If you need more sources to look at try searching:
How to upload file with AJAX and PHP
Uploading File with AJAX and PHP
Sending File to AJAX and PHP upload
File Upload AJAX and PHP
Solution
HTML
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" onclick="UploadFile()" />
</form>
<progress></progress>
JavaScript and AJAX
Note: You will need jQuery for this section. Please link the lastest
CDN to your document.
function UploadFile()
{
$.ajax({
url: 'upload.php',
type: 'POST',
data: new FormData($('form')[0]),
cache: false,
contentType: false,
processData: false,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload)
{
myXhr.upload.addEventListener('progress', function(e)
{
if (e.lengthComputable)
{
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
}, false);
}
return myXhr;
},
success: function() {
// close modal here
}
});
}
This does work since I have tested it. You will need to change your PHP a little.

Just merge your PHP code and HTML to a file and then, in the form, submit to it self.
<?php
$Fname = $_POST["Fname"];
$Lname = $_POST["Lname"];
?>
<html>
<head>
<title>Personal INFO</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
</form>
<?
echo "Hello, ".$Fname." ".$Lname.".<br />";
?>

Related

html upload file(image) in one click

I'd like to upload a file in one click, so I tried to combine two click events in one, but the $_FILE variable does not load the image, here's my code :
<form target='_self' action='upload.php' method='post' enctype='multipart/form-data'>
<div class = 'testocentrato'>
<input style='display:none' type='file' accept='.jpg' name='file' id='file'/>
<input style='display:none' type='submit' id='caricaimmagine' name='caricaimmagine' />
<input class='inputfile' type='button' value='Scegli file da PC' onclick='document.getElementById('file').click(); document.getElementById('caricaimmagine').click();' />
<input style='display:none' type='submit' />
<input class='inputfile' type='submit' name='eliminaimmagine' onclick='document.getElementById('eliminaimmagine').click();' value='".$lang['TASTO_ELIMINA_FOTO']."' />
<input type='hidden' name='id_utente' value='".$user['id']."' />
</form>
It is possible to upload images with one click with ajax, check https://makitweb.com/how-to-upload-image-file-using-ajax-and-jquery/.
here is my html code I used the label tag so when I click the upload icon the select file windows will appear.
<form method="post" enctype="multipart/form-data">
<label class='foto' for="imgid">
<img id="photo" src="images/photo.png">
<p>Foto</p>
</label>
<input type="file" value="chosen File" id="imgid" name="img" accept="image/*">
<img class="previewimg" src="" width="100" height="100">
<span id="showImagePath" ></span>
<button class="btn btn-primary" id="toPost">Post</button>
</form>
mycss.
#imgid{
display:none;
}
.foto{
float:left;
}
.previewimg{
display:none;
background-color:grey;
}
#imgToPost{
display:none;
}
my Jquery:
I used setInterval() function to make my script run until the image is selected that way is going to be uploaded and the name and the image can be previewed.
$("#photo").click(function(){
setInterval(function(){
var fd = new FormData();
var files = $('#imgid')[0].files;
// Check file selected or not
if(files.length > 0 ){
$(".previewimg").show();
fd.append('file',files[0]);
$.ajax({
url: 'action.php?action=postcontentimage',
type: 'post',
data:fd,
contentType: false,
processData: false,
success: function(result){
var name ="";
if(result != 0){
$(".previewimg").attr("src", result).show();
for(var i=0; i < result.length;i++){
if(i>8){
name += result[i];
}
$("#showImagePath").html(name);
clearInterval();
}
}
}
})
}else{
alert("no image has been selected");
}
}, 2000);
})
my PHP:
<?php
if(isset($_FILES['file']['name'])){
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "uploads/".$filename;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
/* Valid extensions */
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
/* Check file extension */
if(in_array(strtolower($imageFileType), $valid_extensions)) {
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
$response = $location;
}
}
echo $response;
exit;
}else{
echo 0;
}
?>
Because you are directly clicking on submit before secting the file.
Remove
document.getElementById('caricaimmagine').click();
You need to click that button manually.

Upload a file in folder using PHP script

I am trying to upload and save an image using PHP scripting, but the image is not getting saved in the specified folder. Please help
here's my code:
<?php
if(isset($_POST['button'])){
$name= "product_name.jpg";
move_uploaded_file($_FILES["fileField"]["tmp_name"],"student_images/$name");
header("location: tryupload.php");
}
?>
<html>
<body>
<form action="tryupload.php" enctype="multiple/form-data" name="myForm" id="myform" method="post">
<table>
<tr>
<td align="right">Product Image</td>
<td><label>
<input type="file" name="fileField" id="fileField" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button"/>
</label></td>
</tr></table>
</form>
</body>
</html>
This part of your code enctype="multiple/form-data" is incorrect.
It needs to read as enctype="multipart/form-data".
Also make sure that the folder you intend on uploading to, has proper permissions to write to.
http://php.net/manual/en/features.file-upload.post-method.php
http://php.net/manual/en/function.chmod.php (setting folder/files permissions).
Uploading security-related links:
https://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form
100% safe photo upload script
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
To upload multuple files you can have.
Multiupload.php
<? session_start()?>
<!DOCTYPE html>
<html>
<head>
<title>Blank</title>
<!-------Including jQuery from google------>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/script.js"></script>
<!-------Including CSS File------>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
<body>
<div id="formdiv">
<h1 class="uploadH2">Upload Your Artwork</h1>
<form enctype="multipart/form-data" action="" method="post">
Take a photo, upload your artwork, or choose an image from Facebook or Instagram
<label for="file">
<div id="image" style="margin-top:5%;">
<img src="img/camera.png">
</div>
</label>
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="button" class="add_more" id="add_more" value="Add More Files"/>
<input type="submit" value="Upload File" name="submit" id="img_upload" class="show-page-loading-msg" data-theme="b" data-textonly="false" data-textvisible="false" data-msgtext="" data-icon="arrow-r" data-iconpos="right"/>
</form>
<br/>
<br/>
<!-------Including PHP Script here------>
<?php include "uploadScript.php"; ?>
</div>
</body>
</html>
uploadScript.php
<?php
$dir_id = session_id(md5(uniqid()));
session_start($dir_id);
$path = "uploads/";
$dir = $path.$dir_id;
$path = $path.$dir_id."/";
if (file_exists($dir)) {
system('/bin/rm -rf ' . escapeshellarg($dir));
} else {
mkdir($path);
chmod($path, 0722);
}
$_SESSION["id"] = $dir_id;
$_SESSION["directory"] = "/" . $dir;
$_SESSION["path_name"] = $path;
?>
<?
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = $path;
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png", "gif"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">Only JPG, JPEG, PNG and GIF files types allowed.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
This script will only accept, jpg, png, gif and jpeg. You can't upload or execute anything inside the directory unless you are owner and you can't have a file size bigger than 10KB.
script.js
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src='' style='width:40%; height:40%;'/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'delete', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
else {}
});
});
This will upload multiple files, preview the image on the same page as the upload form, this will create a directory inside /uploads on the server with a directory matching the users session_id(). If the directory exists, the directory will be deleted, if it doesn't the directory will be created. The files will then be uploaded to that directory on the server.
You have incorrect enctype for the form. Instead of "multiple/form-data" use "multipart/form-data".

uploadprogress_get_info installed correctly and but not working in different code

I know I have no issues with installing uploadprogress extension because when I tried this very simple tutorial: http://www.ultramegatech.com/2010/10/create-an-upload-progress-bar-with-php-and-jquery/, it worked beautifully!
I then tweaked it just a little bit to have a very simple (not jQuery-UI) progress bar, which also worked. Here's the working code:
upload_getprogress.php:
<?php
if (isset($_GET['uid'])) {
$status = uploadprogress_get_info($_GET['uid']);
if ($status) {
echo round($status['bytes_uploaded']/$status['bytes_total']*100);
}
else {
echo 100;
}
}
?>
upload_form.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Upload Something</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
#progress-bar, #upload-frame {
display: none;
}
</style>
<script>
(function ($) {
var pbar;
var started = false;
$(function () {
$('#upload-form').submit(function() {
$('#upload-form').hide();
pbar = $('#progress-bar');
pbar.show();
$('#upload-frame').load(function () {
started = true;
});
setTimeout(function () {
updateProgress($('#uid').val());
}, 1000);
});
});
function updateProgress(id) {
var time = new Date().getTime();
$.get('upload_getprogress.php', { uid: id, t: time }, function (data) {
var progress = parseInt(data, 10);
if (progress < 100 || !started) {
started = progress < 100;
updateProgress(id);
}
started && $('#inner').css('width', progress+ "%");
});
}
}(jQuery));
</script>
<style>
#progress-bar
{
height:50px;
width:500px;
border:2px solid black;
background-color:white;
margin:20px;
}
#inner
{
height:100%;
background-color:orange;
width:0%;
}
</style>
</head>
<body>
<form id="upload-form"
method="post"
action="upload.php"
enctype="multipart/form-data"
target="upload-frame" >
<input type="hidden"
id="uid"
name="UPLOAD_IDENTIFIER"
value="<?php echo $uid; ?>" >
<input type="file" name="file">
<input type="submit" name="submit" value="Upload!">
</form>
<div id="progress-bar"><div id='inner'></div>
<iframe id="upload-frame" name="upload-frame"></iframe>
</body>
</html>
All fine and dandy, no issues! So I know for a fact there is nothing wrong with the way I've set up the uploadprogress extension.
However, having completed the demo successfully, I needed to integrate it into my javascript and jQuery intensive web-app, which includes file uploads.
Now when I try it, I get “NULL” from the uploadprogress_get_info() function. Why?
In my application page, my image upload form is created dynamically. But at the beginning of my page (and before the user hits a button that dynamically creates an image upload form), I am using this line:
<input type='hidden' name='UPLOAD_IDENTIFIER' id='uid' value='<?php echo md5(uniqid(mt_rand())); ?>' />
Is this the problem? Is there a specific time or place this hidden input should be present?
Before including the above line at the top of my page, I've also included a long .js file that includes a bunch of jQuery plugins, but starts with the following code:
var started = false;
function updateProgress(id) {
console.log("updating progress"); // this msg appears, so i know i'm getting this far
var time = new Date().getTime();
$.get('upload_getprogress.php', { uid: id, t: time }, function (data) {
var progress = parseInt(data, 10);
if (progress < 100 || !started) {
started = progress < 100;
updateProgress(id);
}
//started && pbar.progressbar('value', progress);
$('#inner').css('width', progress+ "%");
});
}
// a lot more functions, then:
function imageDialog(imgtype, x, y, editsource) {
// this function dynamically generates a dialog for image uploading
// which shows up when a user hits an "image upload" button
// there's lots of code that creates a new form which is assigned to $imgform
// lots of elements and a couple of iframes are appended to $imgform
// then finally:
$imgform.submit(function() {
pbar = $('#progress-bar');
$('#inner').css('width', "0%");
pbar.show();
started = true;
setTimeout(function () {
updateProgress($('#uid').val());
}, 1000);
});
/* other irrelevant stuff */
}
However, while the upload progress bar shows up as expected, it never increases in progress.
So I edited the upload_getprogress.php to look like this:
if (isset($_GET['uid'])) {
$uid = $_GET['uid'];
//$status = uploadprogress_get_info($_GET['uid']);
echo "progress for $uid is: ".uploadprogress_get_info($uid);
}
In Firefox, I can see the response of the ajax call, and what I get as output from upload_getprogress.php is:
progress for 6e728b67bd526bceb077c02231d2ec6f is:
I tried to dump $status into a variable and output to file, and the file said:
the current uid: 02e9a3e0214ffd731265ec5b0b220b4c
the current status: NULL
So basically, the status is consistently returning NULL. Why? This was (and still is) working fine in the demo, what could be going wrong while integrating it into my web app code? There's nothing wrong with the image uploading on its own - my images are getting uploaded fine, but the progress isn't getting tracked!
The form that gets created dynamically looks like this:
<div class="dialog-container">
<form id="imgform" method="post" enctype="multipart/form-data" action="upload_1-img.php" target="upload_target">
Select image:
<br>
<input id="image" type="file" name="image">
<div id="imgwrapper"></div>
<input id="filename" type="hidden" value="" name="filename">
<input id="upath" type="hidden" value="xxxxxxxxxxxxxxxxxxxxxxxxxx" name="upath">
<center>
<input id="imgupload" type="submit" onclick="showUploadedItem()" value="Upload">
<input id="clearcrop" type="button" disabled="disabled/" value="Clear selection">
<input id="imgapproved" type="button" disabled="disabled" value="Done">
<input id="imgcancel" type="button" value="Cancel">
</center>
</form>
</div>
<div id="progress-bar"><div id='inner'></div></div>
<!-- etc etc some other elements -->
</div>
and my own upload_1-img.php starts off with:
$filename = $_FILES["image"]["tmp_name"];
$file_info = new finfo(FILEINFO_MIME);
$bfr = $file_info->buffer(file_get_contents($filename)) or die ("error");
// some more stuff, getting file type and file's $name
if( /* a bunch of conditions */ )
move_uploaded_file( $_FILES["image"]["tmp_name"], $upath . "/" . $name);
Woohoo! I figured it out, thanks to this bug:
https://bugs.php.net/bug.php?id=57505
Basically, just I removed this static line from the page where users get to upload files:
<input type='hidden' name='UPLOAD_IDENTIFIER' id='uid' value='<?php echo md5(uniqid(mt_rand())); ?>' />
and in my javascript function that creates the image dialog dynamically, I just added the hidden input dynamically, right above the line where I generated the file input.
So the relevant part of the dynamically created form then looks like:
<input type='hidden' name='UPLOAD_IDENTIFIER' id='uid' value='1325a38f3355c0b1b4' />
<input id="image" type="file" name="image">
Now since this is getting dynamically created via javascript anyway, I can just replace that value above with a random js function.
Now the progress bar is advancing as it ought to! :D

Ajax file upload not working in I.E

I am uploading images using ajax and php. My code is working fine in firefox. But in I.E, it doesn't work!
Here is my HTML code,
<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<style>
body { padding: 30px }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<form action="fileup.php" method="post" enctype="multipart/form-data">
<input id="inp" type="file" name="uploadedfile" style="display:none"><br>
<input id="btn" type="submit" value="Upload File to Server" style="display:none">
</form>
<div id="fileSelect" class="drop-area">Select some files</div>
<script>
(function() {
$('form').ajaxForm({
complete: function(xhr) {
alert(xhr.responseText);
}
});
})();
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("inp");
fileElem.addEventListener("change",function(e){
document.getElementById('btn').click();
},false)
fileSelect.addEventListener("click", function (e) {
fileElem.click();
e.preventDefault();
}, false);
</script>
</body>
</html>
Here is php code,
<?php
$target_path = "images/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
In firefox the file uploads perfectly and alert comes up, But in I.E nothing happens!
From the examples page of the form plugin
Browsers that support the XMLHttpRequest Level 2 will be able to
upload files seamlessly.
IE doesn't support XMLHttpRequest Level 2.
EDIT:
Okay, it doesn't seem to be an Ajax issue, because the plugin uses a iframe fallback. You may need to refactor your javascript code
$(function(){
$('form').ajaxForm({
complete: function(xhr) {
alert(xhr.responseText);
}
});
$('#inp').change(function(e) {
$('#btn').click();
});
});
But as a side note, file drop is also not available in IE. So it only works if you select a file manually in IE. And a hidden file select will not allow the user to select a file. Raising the click event from javascript on a file input is also not possible, you have to go with a transparent file input.

PHP - Upload picture and display on page

The following code allows me to upload pictures (using a html form) to a directory on my server.
<?php
$target = "http://www.mockcourt.org.uk/user/htdocs/pics/2012/";
$target = $target . basename( $_FILES['uploaded']['name']);
$ok=1;
if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
Is there any way to modify it so that it will add the pictures to a html page instead?
Thanks
Well after you upload it, you can use javascript to put it on the html page.
I'm not quite sure what your question is, though
EDIT:
So, html form on your page:
<form action="imageUpload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="jupload();" id="form1" >
<div style="visibility:'hidden';" class="imageholder"> <!-- a gif image to show that the process wasn't finished -->
</div>
<input type="file" name="imgfile" />
<input type="submit" name="uploadButton" class="upbtn" value="Submit" />
</form>
Javascript(JQUERY) code for the upload and image add:
function jupload()
{
$(".imageholder").append('<img src="./images/loading.gif">');
}
function juploadstop(result)
{
if(result==0)
{
$(".imageholder").html("");
}
// the result will be the path to the image
else if(result!=0)
{
$(".imageholder").html("");
// imageplace is the class of the div where you want to add the image
$(".imageplace").append("<img src='"+result+"'>");
}
}
php code:
<?php
$target = "http://www.mockcourt.org.uk/user/htdocs/pics/2012/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
$result=$target;
}
else
{
$result=0;
}
?>
<script language="javascript" type="text/javascript">
window.top.window.juploadstop(<?php echo $result; ?>);
</script>
Suppose you have the form in HTML to submit the image.. make the submit button, not a submit button, but just a button.. e.g.
<input type='button' id='submit_form' value='upload' />
and in the javascript, use Ajax to submit the form and Jquery to display it in the web page
$('#submit_form')click(function(){
$.ajax({
type: 'POST',
url: path/phpfile.php,
data: image_input_name
});
//after submitting, get the url of the image form the server
$('#div_to_display_image').html("<img src='path/image_file.jpg' alt='this' />");
});
Hope this helps :-)

Categories