This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 7 years ago.
I'm trying to make an image uploader with php and jquery but i can't get it to work.
My question is
Why is $_FILES['image']; empty?
Heres my code
Html
index.php
<form id="uploadForm" action="" method="post">
<input name="image" type="file" id="image" />
Upload
</form>
<div id="uploadresult"></div>
jQuery
javascript.js
function uploadimages(){
$.ajax({
type: 'POST',
url: '../ajax/upload.php',
processData: false,
contentType: false,
cache: false,
data: new FormData(this),
success: function (data) {
$("#uploadresult").html(data);
},
});
}
$("#uploadforms").click(function(){
uploadimages();
});
Php
Upload.php
<?php
if(!empty($_FILES['image'])) {
echo "Upload image";
}
else{
echo "Error";
}
?>
You forgot enctype='multipart/form-data' in your form
like this
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
For more info click here and here
Update:
Pass form from function call
$("#uploadforms").click(function(){
var form = $('form')[0]; //access form obj
uploadimages(form);
});
And access it in function as
function uploadimages(formObj){
$.ajax({
type: 'POST',
url: '../ajax/upload.php',
processData: false,
contentType: false,
cache: false,
data: new FormData(formObj), //changes here
success: function (data) {
$("#uploadresult").html(data);
},
});
}
Related
I am attempting to upload a file to a server from a bootstrap modal window, using ajax.
The modal html is
<div class="modal-body">
<div>
<form class="form" role="form" id="attachform" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit" class="btn btn-primary">Upload</button>
</form>
</div>
</div>
The Javascript
$("#attachform").on('submit',function(event){
event.preventDefault();
var postData = new FormData($("#attachform")[0]);
console.log(postData);
$.ajax({
url: "attachment.php",
type: "POST",
data: data,
processData: false, // tell jQuery not to process the data
contentType: false
}).done(function(msg) {
console.log(msg);
$('#myAttachModal').modal('hide');
});
});
});
The PHP server code
print_r($_POST);
print_r($_FILES);
I am not seeing anything in the $_FILES array when I run this.
Any suggestions?
Change the data value in your Ajax post to postData. postData contains the form data.
Change this section
data: data,
To
data: postData,//this contains the form data
You just need to change the data : data kew value inside the
$.ajax({
data : postData,
});
$.ajax({
url: "attachment.php",
type: "POST",
data: postData,
processData: false, // tell jQuery not to process the data
contentType: false
}).done(function(msg) {
console.log(msg);
$('#myAttachModal').modal('hide');
});
});
});
I have a really simple HTML page with an image upload form as follows:
<form id="file_data">
<input type='file' id='image_uploaded' accept='image'/>
<input type='submit' id="upload_image"/>
</form>
My Javascript:
$(document).ready(function() {
$("form[id='file_data']").submit(function() {
var form_data = new FormData(this);
$.ajax({
url: "upload.php",
type: "POST",
data: form_data,
processData: false,
success: function(data) {
alert(data);
}
});
});
});
upload.php is creating a directory to store images, if the directory does not already exists. Then is supposed to store image in the directory:
<?php
define("IMAGE_DIRECTORY", "images");
//If the directory for images does not exist, create it
if(!is_dir(IMAGE_DIRECTORY)) {
mkdir(IMAGE_DIRECTORY, 0777, true);
}
move_uploaded_file($_FILES["tmp_name"], IMAGE_DIRECTORY . "\\" .basename($_FILES["file"]["name"]));
?>
While the PHP script will create the directory, if it does not already exist, it is not saving any images to the directory. I'm assuming I am not accessing the image correctly from PHP, but the tutorials I've looked at don't explain too much of the details of what is actually going on when an image is sent in an Ajax call to PHP.
Problem you are missing in code:
Html: enctype="multipart/form-data" on form to upload file, also <input type="file" missing name="file"
Php: move_uploaded_file is not correct you are missing ['file'] for tmp_name $_FILES['file']["tmp_name"]
Ajax: dataType:"html" is missing so that your ajax get response as string from server
Update your Html, Php and Ajax code like this:
Html Code:
<form id="file_data" enctype="multipart/form-data" method="post">
<input type='file' name='file' id='image_uploaded' accept='image'/>
<input type='submit' id="upload_image"/>
</form>
Php Code:
<?php
define("IMAGE_DIRECTORY", "images");
//If the directory for images does not exist, create it
if(!is_dir(IMAGE_DIRECTORY)) {
mkdir(IMAGE_DIRECTORY, 0777, true);
}
move_uploaded_file($_FILES['file']["tmp_name"], IMAGE_DIRECTORY . "\\" .basename($_FILES["file"]["name"]));
?>
Ajax Code:
$.ajax({
url: "upload.php",
data : form_data,
type : "POST",
async: false,
cache: false,
contentType: false,
processData: false,
dateType : "html",
success: function(data) {
alert(data);
}
});
I have a form which use to I send using Ajax with jQuery. And like you can see in the title the question is: Why ajax upload file doesn't need enctype="multipart/form-data" in the form tag?
The example something like this:
<html>
<head>
<script>
$("form1").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'formprocessing.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
}
});
return false;
});
</script>
</head>
<form id="form1">
<input name="image" type="file" />
<input type="submit" value="Submit">
</form>
</html>
You're posting the form content with ajax, so the attributes on the <form> tag are irrelevant. Your own code is basically doing the work that the browser would do if the form were posted implicitly by the browser.
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 7 years ago.
I have found my errors via console log in chrome and remove them but my problem now is that it doesn't call the php script that supposed to process the data.
<legend><strong>Select type of machine model</strong></legend>
<form id="form1" name="form1" method="post" enctype="multipart/form-data">
<select id="machine" name="machine" class="field" >
<option value="" selected="selected">Choose..</option>
<option value="machine1.php">Machine 1</option>
<option value="machine2.php">Machine 2</option>
</select>
</fieldset>
<fieldset>
<legend><strong>Select a file to upload</strong></legend>
<input type="file" id="files" name="files[]" size="40" multiple="multiple" />
<br />
<p></p>
<input type="submit" value="Upload File" id="upload"/>
<br />
<br />
</form>
<div id="information">
</div>
</fieldset>
<fieldset>
<legend><strong>Uploaded Files</strong></legend>
<div id="uploaded"></div>
</fieldset>
<script type="text/javascript">
jQuery(document).ready(function(e){
jQuery('#upload').click(function(e){
var formData = new FormData($('form')[0]);
var page = $("#machine option:selected").val();
//check the output here
e.preventDefault();
console.log("formData",formData)
$.ajax({
url: page,
type: 'POST',
data: formData,
cache: false,
contenType: false,
processData: false,
success: function(data){
$("#information").empty();
$("#information").append(data);
}
});
});
});
It's becoming my dilemma and I have been searching google for 3 straight days now and I found some useful codes but when I apply it to mine, it does not work even errors I have none. Thanks in advance.
I finally got the answer to my question, thanks for the help that you gave me..
$(document).ready(function(){
$("#form1").submit(function(e){
var formObj = $(this);
var page = $("#machine option:selected").val();
if(window.FormData !== undefined)
{
var formData = new FormData(this);
$.ajax({
url: page,
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data){
$("#uploaded").empty();
$("#uploaded").append(data);
}
});
e.preventDefault();
}
});
});
Check your formdata, this is not a solution but will help you debug your own code.
<script type="text/javascript">
$(document).ready(function(e){
$('#upload').click(function(e){
var formData = new FormData($('form')[0]);
var page = $("#machine option:selected").val();
//check the output here
e.preventDefault();
console.log("formData",formData)
$.ajax({
url: page,
type: 'POST',
data: formData,
cache: false,
contenType: false,
processData: false,
success: function(data){
$("#information").empty();
$("#information").append(data);
}
});
});
})
$( document ).ready(function(){
function eventListener(){
$('#upload').click(function(){
event.preventDefault();
var formData = new FormData($('form')[0]);
var page = $("#machine option:selected").val();
$.ajax({
url: page,
type: 'POST',
data: { formData : formData },
cache: false,
contenType: false,
processData: false,
}).done(function(data){
console.log(data);
$("#information").empty();
$("#information").append(data);
});
});
}
eventListener();
}
With that you can access your formData variable on PHP with $_POST["formData"]. But it's hard to help you further without really knowing what you want to achieve. Give us more informations please and tell us what your "data" should return and returns in fact in console.
Hope I could help.
I'm trying to POST the html input file to my PHP file, instead of using the traditional synchronous html forms.
The issue i'm facing is that i'm don't think im POST'ing the input file correctly to my PHP file because my PHP file is saying that its not receiving any POST data.
HTML:
<form id="uploadForm">
Begin by uploading a file (<5mb): <br> <br>
<span class="btn btn-info btn-file" id="buttonColor">
Browse... <span class="glyphicon glyphicon-folder-open"></span><input type="file" id="uploadBrowseBtn" name="uploadBrowseBtn" onchange='$("#upload-file-info").html($(this).val());'>
</span>
<br>
<span class='label label-info' id="upload-file-info">Choose a file.</span>
<br> <br>
<input type="button" class="btn btn-info" id="uploadSubmitBtn" value="Upload">
</form>
JS:
$("#uploadSubmitBtn").click( function() {
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
url: '/upload.php',
data: formData,
async: false,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data)
{
},
})
});
PHP:
<?php
if(empty($_POST)){
echo true;
}else{
echo false;
}
?>
PHP puts posted files in the _FILE variable:
http://php.net/manual/en/reserved.variables.files.php
So even if the posting jquery part is working correctly, you could not see if a file was received by checking if the _POST variable is empty in PHP.
I'm not very good at jQuery, but this should do what you want.
$( document ).ready(function() {
$('#uploadSubmitBtn').on('click', function() {
var file_data = $('#uploadBrowseBtn').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
$('#uploadForm').html(data);
}
});
});
});
<form id="uploadForm">
<input type="file" id="uploadBrowseBtn">
<input type="button" id="uploadSubmitBtn" value="Upload">
</form>
<?php
var_dump($_POST); // empty when received a file
var_dump($_FILES); // filled when received a file
?>
This question: jQuery AJAX file upload PHP answers your question, and has a perfect explanation to what it actually does.