Uploading an image using jquery, instant uploading - javascript

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']

Related

jQuery FormData and files

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.

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["sendImageFile"]["name"] return null value [duplicate]

This question already has answers here:
jQuery Ajax File Upload
(27 answers)
Closed 6 years ago.
I want to upload image without page loading, here sendImageFile is the value of file field. Now when I trying to upload any file from file_upload_to_user.php but every time $_FILES["sendImageFile"]["name"] returns null value.
<form enctype="multipart/form-data" method="post" name="img_upload_form" id="img_upload_form" action="file_upload_to_user.php">
<input name="sendImageFile" id="sendImageFile" type="file" accept=".png, .jpg, .jpeg"/>
<input type="submit" name="photoUploadToSend" id="photoUploadToSend" style="display:none" />
</form>
JS
var frm = $('#img_upload_form');
frm.submit(function (ev) {
var sendImageFile = document.getElementById("sendImageFile").value;
var to_hash = "000000000";
var dataString = 'sendImageFile='+sendImageFile+"&to_hash="+to_hash;
$.ajax({
type:"POST",
url:"file_upload_to_user.php",
data:dataString,
cache:false,
success: function(info) { alert(info);}
});
}
document.getElementById("sendImageFile").onchange = function change(){
// Upload image
document.getElementById("photoUploadToSend").click();
}
If you want to upload a file with ajax then you have to do it with FormData. And to send a formData with jQuery you need to send two other properties to to disable sending wrong stuff. so it's just easier to use fetch...
var form = document.getElementById("img_upload_form")
var fd = new FormData(form)
fetch("file_upload_to_user.php", {method: 'POST', body: fd})
To send a formdata with jQuery ajax you have to set this two:
processData: false,
contentType: false,
You need to use formData
var formData = new FormData();
formData.append('file', $('#sendImageFile')[0].files[0]);
formData.append('to_hash',"000000000");
$.ajax({
url : 'file_upload_to_user.php',
type : 'POST',
data : formData,
processData: false,//prevent automatic processing
contentType: false,//do not set any content type header
success: function(info) { alert(info);}
});

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.

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