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.
Related
(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 />";
?>
I have one form and in that form i have input type file to upload zip files i upload zip file using that form and than it goes to zip extract php file but i want to show loader till the file extract.How can i do using php or jquery?
<form enctype="multipart/form-data" method="post" action="zip_upload.php">
<label>Upload Zip File: </label> <input type="file" name="zip_file">
<input type="submit" name="submit" value="Upload" class="upload" id="submitzip"> <br><br>
</form>
Showing a percentage based progress bar is tricky work. You're much better off displaying a loading status or a spinning icon if your knowledge on this subject is limited.
Not the prettiest of methods but has worked wonders for me and many others in the past.
CSS:
#uploadFrame {
height:1px;
width:1px;
visibility:hidden;
}
HTML:
// hide this on your page somewhere. It's only 1x1 pixels, so should be simple.
<iframe src="zip_upload.php" name="uploadFrame" id="uploadFrame"></iframe>
// your upload form
<form enctype="multipart/form-data" method="post" action="zip_upload.php" target="uploadFrame">
// form content
</form>
jQuery:
$(form).submit(function() {
$('#loading-spinner').show();
});
$("#uploadFrame").load(function() {
$('#loading-spinner').hide();
});
When the form is submitted, a loading icon is displayed, and when the upload and extraction process has finished (iFrame loaded), the loading icon disappears. This all happens without reloading the page.
The bonus of using this is, if modified slightly (convert jQuery to Javascript) you don't need any external libraries or plugins to use it. Also, it is very simple and understandable.
ANOTHER OPTION --------------------------------------------
A bit more advanced and inclusion of jQuery library & a plugin is required, but has the percentage feature.
Check out http://malsup.com/jquery/form/#file-upload for documentation and full spec and here for demo: http://malsup.com/jquery/form/progress.html.
Here is the code:
<form action="zip-upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="zip_file">
<input type="submit" value="Upload">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
})();
</script>
And on your PHP page:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['zip_file']['name']);
if(move_uploaded_file($_FILES['zip_file']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['zip_file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
You can use jQuery UI. Here you can check it http://jqueryui.com/progressbar/#default
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 :-)
Let me know if anyone know what is the issue with this code.
Basically i want to upload a file using jQuery
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(event) {
$('#form1').submit(function(event) {
event.preventDefault();
$.post('post.php',function(data){
$('#result').html(data);
});
});
});
</script>
</head>
<body>
<form id="form1">
<h3>Please input the XML:</h3>
<input id="file" type="file" name="file" /><br/>
<input id="submit" type="submit" value="Upload File"/>
</form>
<div id="result">call back result will appear here</div>
</body>
</html>
and my php 'post.php'
<?php
echo $file['tmp_name'];
?>
Uploaded File name is not returned back. Issue is i couldn't access the uploaded file.
Thanks in advance!
Shiv
Basically i want to upload a file using jQuery
You cannot upload files using AJAX. You could use the jquery.form plugin which uses a hidden iframe:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(event) {
$('#form1').ajaxForm(function(data) {
$('#result').html(data);
});
});
</script>
</head>
<body>
<form id="form1" action="post.php" method="post" enctype="multipart/form-data">
<h3>Please input the XML:</h3>
<input id="file" type="file" name="file" /><br/>
<input id="submit" type="submit" value="Upload File"/>
</form>
<div id="result">call back result will appear here</div>
</body>
</html>
Also notice the enctype="multipart/form-data" on the form.
Another possibility is to use the HTML5 File API which allows you to achieve that assuming the client browser supports it.
It's not possible to upload files with jQuery $.post, neverthless, with the file API and XMLHttpRequest, it's perfectly possible to upload a file in AJAX, and you can even know how much data have been uploaded yet…
$('input').change(function()
{
var fileInput = document.querySelector('#file');
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload/');
xhr.upload.onprogress = function(e)
{
/*
* values that indicate the progression
* e.loaded
* e.total
*/
};
xhr.onload = function()
{
alert('upload complete');
};
// upload success
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
{
// if your server sends a message on upload sucess,
// get it with xhr.responseText
alert(xhr.responseText);
}
var form = new FormData();
form.append('title', this.files[0].name);
form.append('pict', fileInput.files[0]);
xhr.send(form);
}
No no no, you should use a jQuery form plugin for async uploading files. You can't upload file with jQuery $.post method. The file will be uploaded with hidden iframe
Another way is to use HTML5 uploading with FileAPI/BlobApi
Your upload.php has some error.
you should change your this part.
echo $file['tmp_name'];
to:-
echo $_FILES['file']['tmp_name'];
Try uploading with an iframe because you can't send a file with $.post method.
You could also try jquery uploadify - http://www.uploadify.com/
so I have a PHP iframe (ajax) file uploader. I would like to display a loading message when submit is clicked (easy on click event) and then once the file is uploaded, so when the iframe is loaded with the PHP response, vanish (jquery fadeOut) and an alert box pop up saying the file is uploaded. what would be the easiest way to go about this?
You can attach an event handler to load on the iframe and put your fade out logic in there.
Edit 2: Some sample code (changed from ready to load)
<iframe name="process"></iframe>
<form method="post" action="upload.php" target="process" enctype="multipart/form-data" onsubmit="Upload.start()">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
<script>
var Upload = function() {
$(function() {
$('iframe[name=process]').load(function() {
// finished uploading file
$('.loading-div').hide('slow', function() {
alert('Your file has been successfully uploaded.');
});
});
});
return {
start: function() {
$('.loading-div').show();
}
}
}();
</script>