I want to upload an image from an input, and save it in a folder (called 'photos').
In HTML, I have a simple input type file like this:
<input type="file" name="inputFile" id="inputFile" accept="image/jpeg,
image/png">
<span>Scegli una foto</span>
<input id="Invia" type="button" value="Invia">
In Javascript, i used this AJAX call:
var myFormData = new FormData();
myFormData.append($("#inputFile")[0].files[0]['name'], $("#inputFile")[0].files[0]);
$("#Invia").click(function (){
$.ajax({
type: 'POST',
processData: false,
contentType: false,
data: myFormData,
url: "../api/photo.php",
dataType : 'json',
success: function(jsonData){}
});
});
In PHP, the '../api/photo.php' file is this:
<?php
header('Content-Type: application/json; charset=utf-8');
$destination= '../app/photos';
$tmp_name = $_FILES["inputFile"]["tmp_name"];
$name = $_FILES["inputFile"]["name"];
move_uploaded_file($tmp_name, "$destination/$name");
?>
But it doesn't work. I'm not an expert of POST method, so i don't know what I'm doing wrong. Can you help me?
The problem is because your append values... I Checked in my local with your Script and alter something like ajax-url and success message for my convenient This is my code Please Check and let me know:
$("#Invia").click(function (){
var form = new FormData();
var myFormData = document.getElementById('inputFile').files[0]; //get the file
if (myFormData) { //Check the file is emty or not
form.append('inputFile', myFormData); //append files
}
$.ajax({
type: 'POST',
processData: false,
contentType: false,
data: form,
url: "test1.php", //My reference URL
dataType : 'json',
success: function(jsonData){
if(jsonData == 1)
$('#img_msg').html("Image Uploaded Successfully");
else
$('#img_msg').html("Error While Image Uploading");
}
});
});
You don't need to change your php file but, Double check your Folder path is correct for storing the Image...
Related
This question already has answers here:
Ajax Upload image
(6 answers)
Closed 8 months ago.
In Codeigniter by using ajax i am adding record to (products) and everything is working fine so i decided to add (image) field , and for some reason it's no longer adding any record to database
and i add input type=file to my form
<input type="file" name="image">
and i add this to my controller
$image = $this->input->post('image');
$data = array('title'=>$title,'description'=>$description,'price'=>$price,'quantity'=>$quantity,'image'=>$image);
but when i remove $image = $this->input->post('image'); it gets to work again
just in case this is my ajax code
var postData = $(this).serialize();
$.ajax({
type:'post',
url: baseURL+"admin/Products/add_product",
data:postData,
dataType:'json',
success:function(data){
}
});
any ideas how to solve it?
Hope this will help you :
Your ajax should be like this :
var formdata = new FormData();
$.ajax({
type: 'POST',
url: baseURL+"admin/Products/add_product",
data: formdata,
cache: false,
contentType: false,
processData: false,
success: function(response)
{
alert(response);
}
});
In controller accessing image using $_FILES super variable
public function add_product()
{
print_r($_FILES);
print_r($this->input->post());
exit;
}
Note : make sure URL path is correct , see ur network tab to see the output
For more : https://www.formget.com/ajax-image-upload-php/
May Be You can use instead of baseURL
var formdata = new FormData();
$.ajax({
type: 'POST',
url: <?=base_url()?>+"admin/Products/add_product",
data: formdata,
cache: false,
contentType: false,
processData: false,
success: function(response)
{
alert(response);
}
});
I've been trying to get a basic file upload through an ajax form without success. I'm looking for the bare minimum basics and nothing I have found through searching has worked.
I've been messing about with this for about 8 hours and have tried at least a dozen different methods but have not been able to get anything successfully uploaded.
I have narrowed down my code to the most bare necessities as best I can.
My JavaScript goes like this:
function uploadFile(param) { //Upload File
$.ajax({
url: "modules/upload/upload.php",
type: "post",
data: new FormData($(param)[0]),
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
}
});
}
which is called with:
$(".app-canvas").on('change', ".fileUpload", function () {
uploadFile($(this));
});
and the PHP:
<?php
$sourcePath = $_FILES['driver_licence_image']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "uploads/".$_FILES['driver_licence_image']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
?>
FormData takes an HTMLFormElement as an argument to its constructor, you're passing what looks a file input. To add a file from a form element you have to use append.
$(".app-canvas").on('change', ".fileUpload", uploadFile);
function uploadFile() { //Upload File
var fd = new FormData();
fd.append('driver_licence_image', this.files[0]);
$.ajax({
url: "modules/upload/upload.php",
type: "post",
data: fd,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
}
});
}
p.s. $(param)[0] is equivalent to param(when param is a dom node), so please don't do that.
I'm trying to do a file upload through ajax and php. The PHP works fine when called directly, but each time I call it through ajax it is failing. I'm not getting any errors (annoying) it just does not want to upload.
My JQUERY looks like
$('.fileUpload').on('click', function(){
var file_data = $('#medical').prop('files')[0];
console.log(file_data);
var form_data = new FormData();
form_data.file = file_data;
console.log(form_data);
var fileType = $(this).parent().find('input[type="hidden"]').val()
console.log(fileType);
$.ajax({
url: '/docs/upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
fileType:fileType,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
$('.message').html(data) // display response from the PHP script, if any
}
});
});
and my PHP looks like
$file_upload="true";
$file_up_size=$_FILES['file_up'][size];
print_r($_FILES[file_up]);
if ($_FILES[file_up][size]>250000){$msg=$msg."Your uploaded file size is more than 250KB
so please reduce the file size and then upload.<BR>";
$file_upload="false";}
$file_name=$_FILES[file_up][name];
$add="medicalPaperwork/$file_name"; // the path with the file name where the file will be stored
if($file_upload=="true"){
if(move_uploaded_file ($_FILES[file_up][tmp_name], $add)){
echo "Thank god!";
}else{echo "Fuck you.";}
}else{
echo $msg;
}
What am I doing wrong? I'm going crazy trying to figure this out.
edit: the content of the form_data
You are using FormData incorrectly, use append to set the fields you want to upload
$('.fileUpload').on('click', function(){
var file_data = $('#medical').prop('files')[0];
console.log(file_data);
var form_data = new FormData();
var fileType = $(this).parent().find('input[type="hidden"]').val()
form_data.append('file_up', file_data);
form_data.append('fileType', fileType);
console.log(form_data);
console.log(fileType);
$.ajax({
url: '/docs/upload.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(data){
$('.message').html(data) // display response from the PHP script, if any
}
});
});
I want to upload an image to a local folder using jquery ajax. The complex part is i have the forms which are generated dynamically, and to those forms and fields i am giving the id to it so as to show which form is submitted as shown below. I am using following code but the image is not uploaded.
View: Upload_View.php
<script type="text/javascript">
function sendVideoData(frm_id)
{
var data = new FormData(document.getElementById("post_video_"+frm_id));
// make the AJAX request
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>"+"dashboard/do_upload",
data: data+'&form_id='+frm_id,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
alert("data"+data);
},
});
return false;
}
</script>
<form name="post_video" id="post_video_<?=$row1['id']?>" method="post" onsubmit="return sendVideoData(<?=$row1['id']?>)">
<input type="file" name="save_movie_<?=$row1['id']?>" id="movie_<?=$row1['id']?>" />
<input name="type_lecture_id" class="get_lecture_id" id="get_lecture_id_<?=$row1['id']?>" value="<?=$row1['id']?>" type="hidden"/>
<input type="button" class="postbtn" id="submit_movie_<?=$row1['id']?>" value="Upload Video File"/>
</form>
Controller:
$formid=$_POST['form_id'];
$filename='save_movie_'.$formid;
$path_parts = pathinfo($_FILES[$filename]["name"]);
$extension = $path_parts['extension'];
$Random_file_name=$filename.".".$extension;
move_uploaded_file($_FILES[$filename]['tmp_name'], "http://localhost/dummy/uploads/".$Random_file_name);
save_movie_ this is the id of the file control and $formid shows from which form and which field we have to take data, but because i am new to Codeigniter i don't know from how to upload it. One thing more i want to display progress bar also to display the progress of image upload.Please reply. Thanks...
You must have to modify your jQuery ajax function in the following way
var data = new FormData(document.getElementById("post_video_"+frm_id)[0]);
jQuery("#progressbar").show(); // add your prgress bar here like this
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>"+"dashboard/do_upload",
data: data+'&form_id='+frm_id,
mimeType:"multipart/form-data",
contentType: false,
async: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
alert("data"+data);
jQuery("#progressbar").hide(); //hide your loader like this
},
});
return false;
Thank You.
I am relatively new to jQuery and Ajax functions, but have been working with Ajax forms over the past few days. I have come to a problem with file uploads however when trying to upload images. Whilst looking for resources, I couldn't find anything useful because they seem to be over-complicated with pointless extras or have no explanation whatsoever, which doesn't help me to learn any further.
I have wrote this code to handle the image upload in Ajax:
$(function() {
$('.input_photo').on("change",function() {
var formData = new FormData($('form.upload-form'));
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
success: function (msg) {
alert(msg)
}
});
});
});
This sends a request to the upload.php file, however no data is sent, basically my form is literally this:
<form class="upload-form">
<input type="file" name="input_photo" class="input_photo" />
</form>
No data seems to be passed in the headers whatsoever and I assume I would access it through PHP with $_POST['data'] array or $_FILES? Someone with better knowledge please help to explain this, it'd be great to understand this further.
Thanks.
This will work for one or multiple files.
$('input:file').on('change', function () {
var data = new FormData();
//Append files infos
jQuery.each($(this)[0].files, function(i, file) {
data.append('file-'+i, file);
});
$.ajax({
url: "my_path",
type: "POST",
data: data,
cache: false,
processData: false,
contentType: false,
context: this,
success: function (msg) {
alert(msg);
}
});
});
Then
$_FILES['file-0']
$_FILES['file-1']
[...]
But be careful that using FormData doesn't work on IE before IE10
You need to set processData and contentType in your ajax call ( also added id to your input element in order to fetch the file contents).
HTML
<form class="upload-form">
<input type="file" id="photo" name="input_photo" class="input_photo" />
</form>
JS
$(function() {
$('.input_photo').on("change",function() {
var file = document.getElementById("photo").files[0]; //fetch file
var formData = new FormData();
formData.append('file', file); //append file to formData object
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false, //prevent jQuery from converting your FormData into a string
contentType: false, //jQuery does not add a Content-Type header for you
success: function (msg) {
alert(msg)
}
});
});
});
Try with this:
var formData = $('form.upload-form').serialize();