Upload image to server using Jquery - php

I need your help to upload an image on my server.
Indeed, with this code, I have an array(0) {} response while the values are well populated.
No image is uploaded... thank you for your help, here are my two files:
index.php
<input type="file" id="txt_image_user" name="txt_image_user" accept="image/*" required >
<script>
function upload_image() {
var handle = document.getElementById("txt_handle").value;
var reference = document.getElementById("txt_reference").value;
var fd = new FormData();
var files = $('#txt_image_user')[0].files[0];
fd.append('txt_image_user', files);
$.ajax({
type: 'POST',
url: '_upload-image.php',
cache: false,
data: {fd:fd, handle:handle, reference:reference},
contentType: false,
processData: false,
error: function (e) {console.log('Ajax Error', e);alert('Erreur Ajax');},
success: function(response){
console.log(response);
},
});
}
</script>
_upload-image.php
<?php require($_SERVER['DOCUMENT_ROOT']."/ew-includes/config.php");
var_dump($_POST);
$PathImage = $_SERVER['DOCUMENT_ROOT']."/ew-content/images/images-clients/";
if (!is_dir($PathImage)) {mkdir($PathImage);}
if(isset($_POST["handle"])) {
if(is_array($_POST["handle"])) {$handle = implode(", ", $_POST['handle']);} else {$handle = $_POST['handle'];}
if(is_array($_POST["reference"])) {$reference = implode(", ", $_POST['reference']);} else {$reference = $_POST['reference'];}
$img_name = $_FILES["txt_image_user"]["name"];
$img_tmp = $_FILES["txt_image_user"]["tmp_name"];
$filename = "ew".$reference."_".$handle."_".date("YmdHi");
$ext = pathinfo($img_name, PATHINFO_EXTENSION);
$photo = $filename.".".$ext;
$resultat = move_uploaded_file($img_tmp, $PathImage.$photo);
echo "img_name: ".$img_name."\n";
echo "img_tmp: ".$img_tmp."\n";
echo "ext: ".$ext."\n";
echo "photo: ".$photo."\n";
echo "resultat: ".$resultat."\n";
}
Thanks for your help.
I specify that I am new in Jquery

That's not the way to use FormData it should be the data. You can append other values to it.
function upload_image() {
var handle = document.getElementById("txt_handle").value;
var reference = document.getElementById("txt_reference").value;
var fd = new FormData();
var files = $('#txt_image_user')[0].files[0];
fd.append('txt_image_user', files);
fd.append('handle', handle);
fd.append('reference', reference);
$.ajax({
type: 'POST',
url: '_upload-image.php',
cache: false,
data: fd,
contentType: false,
processData: false,
error: function(e) {
console.log('Ajax Error', e);
alert('Erreur Ajax');
},
success: function(response) {
console.log(response);
},
});
}

Related

Save multiple browsed file to a folder [duplicate]

I have designed a simple form which allows the user to upload files to the server. Initially the form contains one 'browse' button. If the user wants to upload multiple files, he needs to click on the "Add More Files" button which adds another 'browse' button in the form. When the form is submitted, the file upload process is handled in 'upload.php' file. It works perfectly fine for uploading multiple files. Now I need to submit the form by using jQuery's '.submit()' and send a ajax ['.ajax()'] request to the 'upload.php' file to handle the file upload.
Here is my HTML form :
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" id="upload" value="Upload File" />
</form>
Here is the JavaScript :
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file' />");
});
});
Here is the code for processing file upload :
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
Any suggestions on how I should write my '.submit()' function will be really helpful.
Finally I have found the solution by using the following code:
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
HTML
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" value="Upload File" id="upload"/>
</form>
Javascript
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file'/>");
});
});
for ajax upload
$('#upload').click(function() {
var filedata = document.getElementsByName("file"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = filedata.files.length, img, reader, file;
for (; i < len; i++) {
file = filedata.files[i];
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("file", file);
}
}
if (formdata) {
$.ajax({
url: "/path to upload/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res) {
},
error: function(res) {
}
});
}
});
PHP
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
/**
Edit: $target_path variable need to be reinitialized and should
be inside for loop to avoid appending previous file name to new one.
*/
Please use the script above script for ajax upload. It will work
Using this source code you can upload multiple file like google one by
one through ajax. Also you can see the uploading progress
HTML
<input type="file" id="multiupload" name="uploadFiledd[]" multiple >
<button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
<div id="uploadsts"></div>
Javascript
<script>
function uploadajax(ttl,cl){
var fileList = $('#multiupload').prop("files");
$('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
var form_data = "";
form_data = new FormData();
form_data.append("upload_image", fileList[cl]);
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
$('#prog'+cl).text(percent+'%')
}, false);
}
return xhr;
},
success: function (res, status) {
if (status == 'success') {
percent = 0;
$('#prog' + cl).text('');
$('#prog' + cl).text('--Success: ');
if (cl < ttl) {
uploadajax(ttl, cl + 1);
} else {
alert('Done');
}
}
},
fail: function (res) {
alert('Failed');
}
})
}
$('#upcvr').click(function(){
var fileList = $('#multiupload').prop("files");
$('#uploadsts').html('');
var i;
for ( i = 0; i < fileList.length; i++) {
$('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
if(i == fileList.length-1){
uploadajax(fileList.length-1,0);
}
}
});
</script>
PHP
upload.php
move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);
My solution
Assuming that form id = "my_form_id"
It detects the form method and form action from HTML
jQuery code
$('#my_form_id').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var msg_error = 'An error has occured. Please try again later.';
var msg_timeout = 'The server is not responding';
var message = '';
var form = $('#my_form_id');
$.ajax({
data: formData,
async: false,
cache: false,
processData: false,
contentType: false,
url: form.attr('action'),
type: form.attr('method'),
error: function(xhr, status, error) {
if (status==="timeout") {
alert(msg_timeout);
} else {
alert(msg_error);
}
},
success: function(response) {
alert(response);
},
timeout: 7000
});
});

PHP Ajax file upload not working

Please help me find the problem here. I am trying to upload a file via AJAX but For some reason which I am unaware of this code has refused to work i.e uploaded file is not copied to the location.
function save()
{
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append('files',files[i],files[i].name);
}
var datastring = $("#businessform").serializeArray();
$.each(datastring,function(key,input){
data.append(input.name,input.value);
});
$.ajax({
type: "POST",
url: "../include/update_ajax.php",
contentType: false,
processData: false,
data: data,
dataType: 'json',
cache: false,
success: function(data) {
//do something
},
error: function(){
alert('error handling here');
}
});
}
Here's the PHP
$success = 0;
$logo = "";
$logo_error = 0;
$sql = "update business set businessname=:bname, phone=:phone, email=:email where vendorid = :id";
$fields = array(
':bname'=>$_POST['businessname'],
':phone'=>$_POST['businessphone'],
':email'=>$_POST['businessemail'],
':id'=>$_POST['vendorid']
);
$q=$con->update_query($sql,$fields);
if($q)
{
//save logo
$businessid = $con->lastID;
if(!empty($_FILES['files']['tmp_name']))
{
$ext=pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
if(strcasecmp($ext, "jpeg") == 0 || strcasecmp($ext, "jpg") == 0 || strcasecmp($ext, "png") == 0)
{
$logo = "logo".$businessid;
move_uploaded_file($_FILES['files']['tmp_name'], UPLOADS_FOLDER.$logo);
}
else
{
$logo_error = 1;
}
}
$success = 1;
}
echo json_encode(array('success'=>$success, 'logo_error'=>$logo_error));
The serialized form appended is sent and inserted without issues but the uploaded file is not sent this way. Please what are my doing wrong and what's the better way.
Thank you so much.
You don't need to append files in FormData() just put Form tag selector in side FormData($("#businessform")[0]);
function save()
{
var datastring = FormData($("#businessform")[0]);
$.ajax({
type: "POST",
url: "../include/update_ajax.php",
contentType: false,
processData: false,
data: data,
dataType: 'json',
cache: false,
success: function(data) {
//do something
},
error: function(){
alert('error handling here');
}
});
}

Return a variable result of a function to an Ajax response

This is my Ajax call :
$("#cover-input").change(function(){
var file_data = $("#cover-input").prop("files")[0];
var form_data = new FormData();
form_data.append("cover_file", file_data);
//kaherdin
$.ajax({
url: 'update-cover',
type: 'POST',
dataType: 'script',
data: form_data,
contentType: false,
processData: false,
async: false,
success: function(resp){
console.log(resp);
},
error: function(err){
console.log('Likes error', err);
}
});
readURL_cover(this);
});
I've a function that basicly trim and upload a file on change.
public function updateCover(Request $request) {
$user = Sentinel::check();
$destinationPath = public_path('uploads/users');
if ($fileCover = $request->file('cover_file')) {
$input_cover = time().'.'.$fileCover->getClientOriginalExtension();
$img = Image::make($fileCover->getRealPath());
$img->fit(1920, 555, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath.'/'.$input_cover);
// $user->cover = $input_cover;
$response = $input_cover;
return $response;
}
But this get me an error. I just want to get "input_cover" back to my ajax call so I can show the updated picture.
If I change : $response = $input_cover to $response = [$input_cover]; it kinkds of work but the input is like : ["my_pic.jpg"] so it's not nice.
You should return a JsonResponse like so:
return response()->json(['input_cover' => $input_cover]);
Check this for responses in json and how they work https://laravel.com/docs/5.4/responses#json-responses

upload and save file through ajax

I new to this site as well as to ajax, before posting here, although I searched for, nut not get proper answer to my question.
I have form through which I can upload and than save file, all this happening through ajax.
$('#'+loader).fadeIn('fast');
var input = document.getElementById(fileid);
file = input.files[0];
var filename= $('#'+fileid).val();
var exts = ["pdf", "doc", "docx", "PDF", "DOC", "DOCX"];
if(file != undefined){
formData= new FormData();
if ( filename )
{
// split file name at dot
var get_ext = filename.split('.');
// reverse name to check extension
get_ext = get_ext.reverse();
// check file type is valid as given in 'exts' array
if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){ var found = true; } else { var found = false; }
}
if(found) {
formData.append("image", file);
$.ajax({
url: uri,
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
if(data.length!=0)
{
$('#'+loader).fadeOut('fast');$('#'+errorid).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+successid).fadeIn('fast');
$('#'+inputhidden).val(data);
$('#'+imgname).fadeIn('fast');
$('#'+filesavebtn).fadeIn('fast');
$('#'+imgname).html(data);
}else if(data.length==0)
{
$('#'+loader).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+successid).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+errorid).fadeIn('fast');
}
}
});
}
else{
$('#'+loader).fadeOut('fast');$('#'+errorid).fadeOut('fast');$('#'+successid).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+exerror).fadeIn('fast');
}
}else{
}
and getting saved through
var fileval= $('#'+fileid).val();
var fileuniqval= $('#'+fileuniqid).val();
$.ajax({
url: pageurl,
type: 'POST',
data: 'fileupload='+fileval+'&identi='+fileuniqval+'&uniqids=fileuploading',
success: function(data)
{
if(data=='FALSE'){
alert("Server Error, please try again.");
}if(data=='TRUE'){
$('#'+hide1).fadeOut('fast');$('#'+hide2).fadeOut('fast');$('#'+hide3).fadeOut('fast');
$('#'+inputid).val('');
$('#'+successmsg).fadeIn('fast');
$('#'+filearea).css({ 'border-color': '#008000', 'border-width':'2px', 'border-style':'solid' });
$('#'+filearea).animate({ 'backgroundColor': '#008000', 'color': '#fff'}, 1000);
$('#'+filearea).animate({ 'backgroundColor': '#fff', 'color': '#000'}, 3000);
}
}
});
Now my question is that I want to get this upload and save procedure in one go! Although I tried my to merge both function by nesting one in other but not working as per expectations.
$('#'+loader).fadeIn('fast');
var input = document.getElementById(fileid);
file = input.files[0];
var filename= $('#'+fileid).val();
var exts = ["pdf", "doc", "docx", "PDF", "DOC", "DOCX"];
var fileval= $('#'+inputhidden).val();
var fileuniqval= $('#'+fileuniqid).val();
if(file != undefined){
formData= new FormData();
if ( filename )
{
// split file name at dot
var get_ext = filename.split('.');
// reverse name to check extension
get_ext = get_ext.reverse();
// check file type is valid as given in 'exts' array
if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){ var found = true; } else { var found = false; }
}
if(found) {
formData.append("image", file);
$.ajax({
url: uri,
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
if(data.length!=0)
{
$('#'+loader).fadeOut('fast');$('#'+errorid).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+successid).fadeIn('fast');
$('#'+inputhidden).val(data);
$('#'+imgname).fadeIn('fast');
//$('#'+filesavebtn).fadeIn('fast');
$('#'+imgname).html(data);
$.ajax({
url: pageurl,
type: 'POST',
data: 'fileupload='+fileval+'&identi='+fileuniqval+'&uniqids=fileuploading',
success: function(data)
{
if(data=='FALSE'){
alert("Server Error, please try again.");
}if(data=='TRUE'){
$('#'+successid).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+errorid).fadeOut('fast');
$('#'+fileid).val('');
$('#'+hide1).fadeIn('fast');
$('#'+filearea).css({ 'border-color': '#008000', 'border-width':'2px', 'border-style':'solid' });
$('#'+filearea).animate({ 'backgroundColor': '#008000', 'color': '#fff'}, 1000);
$('#'+filearea).animate({ 'backgroundColor': '#fff', 'color': '#000'}, 3000);
}
}
});
}else if(data.length==0)
{
$('#'+loader).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+successid).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+errorid).fadeIn('fast');
}
}
});
}
else{
$('#'+loader).fadeOut('fast');$('#'+errorid).fadeOut('fast');$('#'+successid).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+exerror).fadeIn('fast');
}
}else{
}

How to upload multiple files using PHP, jQuery and AJAX

I have designed a simple form which allows the user to upload files to the server. Initially the form contains one 'browse' button. If the user wants to upload multiple files, he needs to click on the "Add More Files" button which adds another 'browse' button in the form. When the form is submitted, the file upload process is handled in 'upload.php' file. It works perfectly fine for uploading multiple files. Now I need to submit the form by using jQuery's '.submit()' and send a ajax ['.ajax()'] request to the 'upload.php' file to handle the file upload.
Here is my HTML form :
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" id="upload" value="Upload File" />
</form>
Here is the JavaScript :
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file' />");
});
});
Here is the code for processing file upload :
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
Any suggestions on how I should write my '.submit()' function will be really helpful.
Finally I have found the solution by using the following code:
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
HTML
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" value="Upload File" id="upload"/>
</form>
Javascript
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file'/>");
});
});
for ajax upload
$('#upload').click(function() {
var filedata = document.getElementsByName("file"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = filedata.files.length, img, reader, file;
for (; i < len; i++) {
file = filedata.files[i];
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("file", file);
}
}
if (formdata) {
$.ajax({
url: "/path to upload/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res) {
},
error: function(res) {
}
});
}
});
PHP
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
/**
Edit: $target_path variable need to be reinitialized and should
be inside for loop to avoid appending previous file name to new one.
*/
Please use the script above script for ajax upload. It will work
Using this source code you can upload multiple file like google one by
one through ajax. Also you can see the uploading progress
HTML
<input type="file" id="multiupload" name="uploadFiledd[]" multiple >
<button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
<div id="uploadsts"></div>
Javascript
<script>
function uploadajax(ttl,cl){
var fileList = $('#multiupload').prop("files");
$('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
var form_data = "";
form_data = new FormData();
form_data.append("upload_image", fileList[cl]);
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
$('#prog'+cl).text(percent+'%')
}, false);
}
return xhr;
},
success: function (res, status) {
if (status == 'success') {
percent = 0;
$('#prog' + cl).text('');
$('#prog' + cl).text('--Success: ');
if (cl < ttl) {
uploadajax(ttl, cl + 1);
} else {
alert('Done');
}
}
},
fail: function (res) {
alert('Failed');
}
})
}
$('#upcvr').click(function(){
var fileList = $('#multiupload').prop("files");
$('#uploadsts').html('');
var i;
for ( i = 0; i < fileList.length; i++) {
$('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
if(i == fileList.length-1){
uploadajax(fileList.length-1,0);
}
}
});
</script>
PHP
upload.php
move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);
My solution
Assuming that form id = "my_form_id"
It detects the form method and form action from HTML
jQuery code
$('#my_form_id').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var msg_error = 'An error has occured. Please try again later.';
var msg_timeout = 'The server is not responding';
var message = '';
var form = $('#my_form_id');
$.ajax({
data: formData,
async: false,
cache: false,
processData: false,
contentType: false,
url: form.attr('action'),
type: form.attr('method'),
error: function(xhr, status, error) {
if (status==="timeout") {
alert(msg_timeout);
} else {
alert(msg_error);
}
},
success: function(response) {
alert(response);
},
timeout: 7000
});
});

Categories