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.
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);
}
});
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 am using ajax to upload file cross domain. I think the bug is in js part.
But I can't figure it out what exactly wrong.
<form id="upload">
<div class="control-group">
<div class="controls">
<input id="file" name="file" type="file">
</div>
<div class="form-group">
<button class="btn btn-primary" onclick="Submit()" type="button">submit</button>
</div>
</div>
</form>
Here is my js
var form = $('#upload');
var formData = new FormData(form);
$.ajax({
url: URLs,
data: formData,
cache:false,
contentType: false,
processData: false,
crossDomain: true,
type:"POST",
dataType:'jsonp',
success: function(msg){
alert(msg["foo"]);
}
});
dataType:'jsonp',
JSONP is incompatible with POST requests (which file uploads require).
Use any other dataType supported by jQuery.
Since you are making a cross origin request, you will need the target server to grant you permission via CORS.
When the user clicks the button, you're calling the function Submit() but it isn't defined in your js. This should work:
function Submit()
{
var form = $('#upload');
var formData = new FormData(form);
$.ajax({
url: URLs,
data: formData,
cache:false,
contentType: false,
processData: false,
crossDomain: true,
type:"POST",
dataType:'jsonp',
success: function(msg){
alert(msg["foo"]);
}
});
}
I have some AJAX script that submits a form and then updates the web page.
My Code:
HTML:
<form action='jobs.php' method='post' name='editUpdate' enctype='multipart/form-data' id="form-add">
<hr />
<textarea name='description' id="title" class="text1" placeholder="Add Update" cols='100' rows='5'></textarea>
<input type="submit" name='action' id="submit" value="Save Update"></input>
</form>
AJAX:
<script>
$('#form-add').submit(function(e){
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData(this);
var prependbdDiv = $('#prependbody');
$.ajax({
url: formURL,
type: 'POST',
data: formData,
dataType: "json",
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(response) {
if(response.success == "1"){
prependbdDiv.prepend("<tr><td>"+response.datetime+"</td><td>"+response.updatedesc+"</td></tr>");
$('#title').val('');
$("#form-add").fadeToggle();
}
},
error: function(response)
{
alert("ERROR");
},
});
e.preventDefault();
});
</script>
This seems to have resolved my issue:
Submiting a form with Ajax by using FormData on Firefox and IE10+
I am curious why this is the case or is it bad programming on my behalf?
Also when using FireBug the post data does not appear similar to that of the post data from a standard HTML form. IE, with the ajax post using formdata FireBug lists no "Parts" section under the POST details.
Thanks for your help!