jQuery FormData and files - javascript

I'm attempting to do ajax file upload. When i check the variable form_data it is blank?
<form action='ajax_image_upload/process.php' method='post' enctype='multipart/form-data' class='upload_form'>
<textarea name='description' placeholder='Type Default Video Description'></textarea>
<span>
Channel Image: <input type='file' name='image' />
</span>
<input name='__submit__' type='submit' value='Upload'/>
</form>
var container = $(".upload_form");
var form_data = new FormData();
form_data.append('image', container.find("form > span").children("input[name='image']"));
var post_url = container.children("form").attr("action"); //get action URL of form
//jQuery Ajax to Post form data
$.ajax({
url : post_url,
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
mimeType: "multipart/form-data"
}).done(function(res){
});
How can I solve this?

The issue is because you need to append the binary data from the file input to the FormData, not the jQuery object. Try this:
var fileData = container.find("form > span").children("input[name='image']")[0].files[0];
form_data.append('image', fileData);
Obviously, if there are multiple inputs, or multiple files within the input, you'll need to loop through them and append them individually.

Related

send uploaded files and inputs data with ajax

I'm trying to upload files with datas using ajax.
here is my html form :
<body>
<input type="text" id="name" value="test" />
<input type="file" id="pic" accept="image/*" />
<input id = "submit" type="submit" />
</body>
when I send the uploaded file alone with ajax it is working using new FormData();
var file_data = $('#pic').prop('files');
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'test.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response);
}
});
but Idon't know how to send the input 'name' with Data
var DATA = 'name='+name;
$.ajax({
url: "test.php",
type: "post",
data: DATA,
success: function (response) {
console.log($response);
},
});
Thanks
First of all you should include form tags such as the following example.
<form id="uploadForm" enctype="multipart/form-data" action="http://yourdomain.com/upload" method="post" name="uploadForm" novalidate>
<input type="text" id="name" value="test" />
<input type="file" id="pic" accept="image/*" />
<input id = "submit" type="submit" />
</form>
Then you can send all of the form data using code such as the following:
var form = $('#uploadForm')[0];
var form_data = new FormData(form);
To answer your specific question about sending the value of only the text field with ID "name", simply use the following line:
var DATA = 'name=' + $('#name').val();
var name = $("#name").val();
form_data.append('name', name);
Maybe it's wrong, please try

files do not post when javascript submits form

I have an image upload form which is submitted by a javascript but the file data is not being submitted. I have looked at examples of how to fix this with ajax but cannot find any examples that address it with the javascript submit that I am using.
<td>New Photo<br>
<div id="editphoto">
<form id="editphoto" enctype="multipart/form-data" method="post" action="editphoto.php">
<input type="hidden" name="employeeid" value="<?php echo $listing[$k]["employeeid"] ?>">
<input type="file" name="file2">
<input type="submit" value="Submit">
</form></div></td>
<script>
$('#editphoto form').submit(function(){
var data=$(this).serialize();
$.post('editphoto.php', data , function(returnData){
$('#editphoto').html( returnData)
})
return false; // stops browser from doing default submit process
});
</script>
Files cannot be serialized. You can use FormData To submit a file using jQuery.
$('#editphoto form').submit(function(){
var formData = new FormData();
formData.append('file2', $('input[type=file]')[0].files[0]);
// append other form-data to formData object
var otherData = $(this).serialize();
$.each( otherData , function(key, field){
formData.append(field.name, field.value);
});
// post form
$.ajax({
url: 'editphoto.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function( returnData ) {
$('#editphoto').html( returnData)
}
});
return false; // stops browser from doing default submit process
})

Formdata append file upload is not working in codelgniter,Getting error

All I am trying to do is upload files using ajax to my CodeIgniter based website.But i cannot get file field value in controller.I am getting message like "Undefined index: 'file_1'"
How to solve this issue?
Form
<form method="post" enctype="multipart/form-data">
<input type="file" id="file_1" name="file_1" value="" class="field1" />
<input type="button" onclick="up_img()" value="Upload" />
</form>
Javascript:
<script type="text/javascript">
function up_img()
{
formdata = false;
var imgfile = document.getElementById("file_1");
formdata = new FormData();
formdata.append("file_1",imgfile.files[0]);
$.ajax({
url: "<?php echo base_url(); ?>index.php/save_project_upload/",
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});
}
Controller:
function save_project_upload()
{
echo $upfile_name = $_FILES['file_1']['name'];
}
If you do a print_r( $_FILES ) are you getting any content?
Also, be aware that this is not supported by IE8 and earlier.
You could also try to do:
var formData = new FormData($('#yourformID')[0]);
EDIT:
formData.append('file_1', $('input[id="file_1"]')[0].files[0]);
Might also solve your problem, by adding [0] to the DOM element.

Uploading an image using jquery, instant uploading

how can i upload an image using jQuery so it wont have to refresh the page?
so i can use the uploaded image. i have no idea how to submit a file through jQuery :/
if i have the following form
<form action = "myCurrentPage" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "LogoImage" id = "LogoImage">
</form>
HTML:
<form id='myForm' onsubmit='doUpload()' action = "javascript:void(0)" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "LogoImage" id = "LogoImage">
</form>
Javascript:
function doUpload() {
var formData = new FormData(document.getElementById("myForm"));
$.ajax({
url: "/admin/scripts/addpet.php",
dataType: "xml",
type: "POST",
processData: false,
contentType: false,
data: formData
}).done(function(xmlDoc) {
});
}
On your php side you grab the file like you normally would. $_FILES['fileName']['tmp_name']

Upload image using ajax and form submitting

I want to upload an image to the server using Ajax, but there is a problem. Would somebody please help me what is wrong here. I could submit the image using submit form but not ajax.
here is my code:
html:
<div id="uploadPic" onclick="getFile()">
Select a photo to upload
</div>
<form name="myForm" id="avatar_form" enctype="multipart/form-data" method="post" action="">
<div style='height: 0px;width:0px; overflow:hidden;'>
<input id="upfile" class="botpic" type="file" name="avatar" value="upload" required="" onchange="sub1()">
</div>
</form>
javascript:
function getFile(){
document.getElementById("upfile").click();
}
function sub1(){
var photo = document.getElementById("upfile");
var file = photo.files[0];
data = new FormData();
data.append('file', file);
$.ajax({
url: 'url',
data: data
enctype: 'multipart/form-data',
processData: false, // do not process the data as url encoded params
contentType: false, // by default jQuery sets this to urlencoded string
type: 'POST',
success: function ( output ) {
document.getElementById('picTmp').innerHTML = output;;
}
});
}
PHP code:
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
.......
}
The first thing I notice is that you're missing a comma after the data parameter declaration. That might be your only issue.
$.ajax({
url: 'url',
data: data,
enctype: 'multipart/form-data',
//etc...
What's the name of your PHP script? That's what you should specify as 'url':
url: 'script_name.php',
Maybe this plugin could help you
Jquery Form
I had a lot of problem making from myself and with this plugin everething works, just try, this
$('form').ajaxForm(function() {
alert("Thank you for your comment!");
});
I would guess that without using preventDefault() method in your script,
you submit the form to the same page using action="" and method="post", thus never entering your $.ajax();
I've done something like this
$('#query_projects').submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
var request = $.ajax({
type: 'POST',
url: 'query_tab_projets.php',
mimeType:'application/json',
dataType:'json',
data: formData,
contentType: false,
processData: false,
success: function(data){
alert(JSON.stringify(data,null,4));
},
error: function(msg){
alert(JSON.stringify(msg,null,4));
}
});
});
where #query_projects is my form id
Finally I found where the problem is. Maybe it is useful for others struggling with ajax uploading a file.Now it is working perfectly.
The solution is:
In the php code, all the ["avatar"] should be replaced with ["file"] as we are sending the file specified as file in ajax.

Categories