Problem with uploading a image via Ajax Call in php? - javascript

I want to upload an image via Ajax call but I am not able to upload the image. Kindly check my code what I am doing wrong:
HTML File:
<input class="form-control" type="file" name="photo1" id="photo1" accept="image/*" onchange="loadFile2(event)">
<button type="button" class="btn btn-secondary btn-lg btn-block" onclick="createDocsVerify()">Update Details</button>
Ajax Call:
<script>
function createDocsVerify () {
var data = {
'photo1' : jQuery('#photo1').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/myproject/adminseller/sellerdocsverify.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
});
}
</script>
Php File: sellerdocsverify.php
if (isset($_POST['photo1'])) {
$photo1 = sanitize($_POST['photo1']);
// var_dump Output: string(20) "C:\fakepath\0553.jpg"
}
$errors = array();
$required = array(
'photo1' => 'Please select Photo 1',
);
// check if all required fileds are fill out
foreach ($required as $field => $display) {
if (empty($_POST[$field]) || $_POST[$field] == '') {
$errors[] = $display.'.';
}
}
$allowed = array('png', 'jpg', 'jpeg', 'gif');
$photoNameArray = array();
$tmpLoc = array();
$uploadPath = array();
**// Here is the problem**
$name1 = $_FILES['photo1']['name']; // Here is the problem
Var_dump($name1); // OUTPUT: NULL
**// Here is the problem**
$nameArray = explode('.',$name1);
$fileName = $nameArray[0];
$fileExt = $nameArray[1];
$mime = $_FILES['photo1']['type'];
$mimeType = $mime[0];
$mimeExt = $mime[1];
$tmpLoc = $_FILES['photo1']['tmp_name'];
$fileSize = $_FILES['photo1']['size'];
$uploadName = md5(microtime().$j).'.'.$fileExt;
$uploadPath = BASEURL.'images/products/'.$uploadName;
if ($mimeType != 'image') {
$errors[] = 'The file must be an image.';
}
if (!empty($errors)) {
echo display_errors($errors);
}else{
echo 'passed';
// upload file and insert into database
if ($photoCount > 0) {
move_uploaded_file($tmpLoc1, $uploadPath1);
}
$insertSql = "INSERT INTO docTable (`photo1`)
VALUES ('$photo1')";
$db->query($insertSql);
$_SESSION['success_flash'] = '<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
}
?>
Kind check my code and suggest what I am doing wrong, am I doing something wrong in Ajax call or in php, I am getting the value in $photo1.
Any idea or suggestion would be welcome.

You need to do some special "things" to upload files via AJAX. You need to create a FormData object and manually add the file data to it, and also set the contentType, processData and cache options of your AJAX call to false. Your javascript should look like this:
<script>
function createDocsVerify() {
var formdata = new FormData();
var file = jQuery('#photo1').prop('files')[0];
formdata.append('photo1', file);
//Ajax call Start Here
jQuery.ajax({
url: '/myproject/adminseller/sellerdocsverify.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
That should upload the photo.

Related

how to upload image from codeigniter to mysql

I am new in CodeIgniter. I am not getting how to update form data in the database. Insertion and showing data from database is done but can't understand how to update data in the database.
I've tried researching this link but data not successfully uploaded.
This is my Controller
//npwp
$temp1 = explode(".", $_FILES['file_npwp']['name']);
$new_name1 = time().'.'.end($temp1);
$config1['upload_path'] = APPPATH.'/file_npwp/';
$config1['file_name'] = $new_name1;
$config1['overwrite'] = TRUE;
$config1['allowed_types'] = 'jpg|jpeg|png|pdf';
$this->load->library('upload',$config1);
$this->upload->initialize($config1);
if(!$this->upload->do_upload('file_npwp')){
$this->data['error'] = $this->upload->display_errors();
}
$media1 = $this->upload->data('file_npwp');
This is my Model
$data_service['file_npwp']= $file_lampiran1;
$data_service['file_ktp']= $file_lampiran2;
$data_service['file_po']= $file_lampiran3;
$data_service['file_registrasi']= $file_lampiran4;
$this->db->where('id_service',$this->input->post('id_service'));
$this->db->update('service_sis', $data_service);
This is my View
<div class="form-group">
<label for="">File NPWP</label>
<input type="file" name="file_npwp" id="file_npwp" class="form-control">
</div>
<br>
<div id="hasilloadfoto"></div>
<br>
<p>*Pastikan semua form sudah terisi dengan benar</p>
<button id="SaveAccount" class="btn btn-success">Simpan</button>
This is my Javascript in my view
$( function() {
var $signupForm = $( '#myForm' );
$signupForm.validate({errorElement: 'em'});
$signupForm.formToWizard({
submitButton: 'SaveAccount',
nextBtnName: 'Selanjutnya',
prevBtnName: 'Sebelumnya',
nextBtnClass: 'btn btn-primary btn-flat next',
prevBtnClass: 'btn btn-default btn-flat prev',
buttonTag: 'button',
validateBeforeNext: function(form, step) {
var stepIsValid = true;
var validator = form.validate();
$(':input', step).each( function(index) {
var xy = validator.element(this);
stepIsValid = stepIsValid && (typeof xy == 'undefined' || xy);
});
return stepIsValid;
},
progress: function (i, count) {
$('#progress-complete).width(''+(i/count*100)+'%');
}
});
});
function filePreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#hasilloadfoto + img').remove();
$('#hasilloadfoto').after('<img src="'+e.target.result+'" width="450" height="300"/>');
}
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function(){
$("#file_npwp").change(functio () {
filePreview(this);
});
Need help in update operation. I appreciate any help.
you can do in two ways,
You can upload the image to any cloud storage(Aws, Azure, etc) then update the link on your Db
Convert the image into base64 and update it as the string on your DB.
I will prefer to go with step one, I have the sample where I have uploaded it to Azure and update my DB
// This is on Js , Using ajax , I will send to controller
function uploadImage() {
var base_url = '<?php echo BASEURL ?>';
// call ajax to upload image
//event.preventDefault();
var file_data = $('#post-image').prop('files')[0];
var form_data = new FormData();
form_data.append('uploaded_file', file_data);
$.ajax({
url: base_url + "dashboard/uploadImage",
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (aData) {
},
error: function (data) {
alert(data);
}
});
}
On Controller ,
public function uploadImage() {
// get the 'api-key' key from Request Headers
$data = array();
if (isset($_FILES ['uploaded_file']['name']) && !empty($_FILES ['uploaded_file']['name'])) {
$userId = $this->input->post("userId");
$file_name = $userId . "_" . uniqid() . ".jpg";
$S3ImgUrl = uploadImageToS3($_FILES ['uploaded_file']['tmp_name'], "app_feed_images", $file_name);
$data = array(
'code' => 555,
'message' => 'Image has been uploaded successfully',
'url' => $S3ImgUrl
);
} else {
$data['code'] = -111;
$msg = "failed to upload image to s3";
$data ['status'] = $this->failed_string;
}
// var_dump($data);
echo json_encode($data);
}
Helper Class
function uploadImageToS3($tmp, $bucket, $file_name) {
$connectionString = "DefaultEndpointsProtocol=https;AccountName=" . azure_bucket_name . ";AccountKey=" . azure_bucket_key;
$blobClient = MicrosoftAzure\Storage\Blob\BlobRestProxy::createBlobService($connectionString);
$containerName = "app-image/" . $bucket;
$containerUrl = "https://hbimg.blob.core.windows.net/";
$content = fopen($tmp, "r");
$options = new MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions();
$content_type = $_FILES['uploaded_file']['type'];
$options->setContentType($content_type);
$blobClient->createBlockBlob($containerName, $file_name, $content, $options);
return $containerUrl . $containerName . "/" . $file_name; }
On the controller side, I have just uploaded the image, you can call you model class with the uploaded image link and update on your DB.
Happy coding :)
All you need is to send the name of the photo in database right then in model you have to add
$this->input->post('databse_column_name')=$variable_name_which_content_file_name

How to reload a img attr "src" after ajax call without knowing the file name from the image tag?

I have this html:
<div class="d-inline-flex">
<img id="reloadIMG" class="p-3 mt-5 imgP" onDragStart="return false" <?php echo htmlentities($avatar, \ENT_QUOTES, 'UTF-8', false); ?>>
<input type="file" id="uploadAvatar" name="uploadedAvatar">
</div>
the value of $avatar:
$pathFolderAvatar = 'user/'.$folder.'/avatar/*';
$imgUserPastaAvatar = glob($pathFolderAvatar)[0] ?? NULL;
if(file_exists($imgUserPastaAvatar)){
$avatar = 'src='.$siteURL.'/'.$imgUserPastaAvatar;
}else{
$avatar = 'src='.$siteURL.'/img/avatar/'.$imgPF.'.jpg';
}
and the script to send a ajax call to my file that process the file upload request:
$(function () {
var form;
$('#uploadAvatar').change(function (event) {
form = new FormData();
form.append('uploadedAvatar', event.target.files[0]);
});
$("#uploadAvatar").change(function() {
$("#loadingIMG").show();
var imgEditATTR = $("div.imgP").next().attr("src");
var imgEdit = $("div.imgP").next();
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime());
}
});
});
});
i tried to force the browser to reload the img on success ajax call $(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime()); but the selector from the var imgEdit and imgEditATTR is not working:
console.log(imgEdit); result: w.fn.init [prevObject: w.fn.init(0)]
console.log(imgEdit); result: undefined;
Why is it happening, and how to fix?
I know that there's a bunch of questions about reload img, but on these questions there's not a method to reload a image without knowing the file name. I checked so many questions and this is what the answears say:
d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
On my case i don't know the file name, because it's generated randomly on profileForm.php with mt_rand():
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
You can return file name in response to your AJAX request and use it in success block to update src attribute of img tag
So your profileForm.php will look something like
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000).'_'.time();
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo $newname // you can also send a JSON object here
// this can be either echo or return depending on how you call the function
and your AJAX code will look like
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data);
}
});
Let profileForm.php return the generated filename:
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo json_encode(['filename' => $folderPFFetchFILE]);
Then in the callback of your POST request:
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data.filename);
}

Php Upload File With JavaScript

I Try to upload with javascript I send ajax but I can't find problem my code not work where is problem ?
index.php
<input type="file" id="photoUploadFile"/>
script js
var full_photo_name = document.getElementById('photoUploadFile').value;
var photo_name = full_photo_name.substr(full_photo_name.lastIndexOf("\\")+1, full_photo_name.length);
$.ajax({
type: "POST",
url: "register_photo.php",
data: { photo_name : photo_name },
success: function(data) {
}
});
register_photo.php
upload_photo($_POST['photo_name']); // i upload with this function but show me error: Sorry!
function upload_photo($file_name) {
global $Root_Directory;
$target_dir = $Root_Directory. 'uploads/';
$target_file = $target_dir. $file_name;
$uploadOk = 1;
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($file_name, $target_file)) {
echo 'File: '. $file_name. ' has been uploaded.';
} else {
echo 'Sorry !';
}
}
}
change your ajax like this
var formdata = new FormData();
formdata.append( 'file', input.files[0] );
$.ajax({
url: 'register_photo.php',
data: formdata,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
In register_photo.php Use move_uploaded_file to save
In your ajax request you can use something like this.
var file_data = $('#photoUploadFile').prop('files')[0];
var form_data = new FormData();
form_data.append('file_name', file_data);
$.ajax({
url: "register_photo.php",
cache: false,
data: form_data,
type: 'post',
success: function(result){
alert(result);
}
});
In your PHP code
upload_photo($_FILES['file_name']); // i upload with this function but show me error: Sorry!
function upload_photo($file_name) {
global $Root_Directory;
$target_dir = $Root_Directory. 'uploads/';
$target_file = $target_dir. $file_name;
$uploadOk = 1;
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($file_name['tmp_name'], $target_file)) {
echo 'File: '. $file_name. ' has been uploaded.';
} else {
echo 'Sorry !';
}
}
}
The best way to send the file is to submit it using a form and then receiving it on server and then processing it with php or what ever language you are using.
You have to understand that the client and the server are two different entities and sending the file name in ajax will not help.
put the input element in form.
<form id="frmsendfile" method="post" target="fileprocess.php">
<input type="file" id="photoUploadFile"/>
</form>
Now we write a javascript function that will submit the form to your server after you have browsed the file. you can add validation. I am just going to give you an idea how you can do this.
<script type="text/javascript">
var submitFile = function(){
var frm = document.forms[0];
if(frm)
{
frm.submit();
}
};
you need to call submitFile() function to send the file.

Codeigniter: Uploading image through Ajax and storing in db

I am using CI 3.0.1 was uploading and inserting image to db successfully before i used ajax, i guess trying to do it with ajax i'm missing something which isn't even sending data to upload maybe because we have to use multipart() in form while in ajax we are just sending data direct to controller, another thing i don't know how to receive the variable in response
my Ajax request function is:
<script type="text/javascript">
$(document).ready(function() {
alert("thirddddddddd");
$('#btnsubmit').click(function()
{
alert("i got submitted");
event.preventDefault();
var userfile = $("input#pfile").val();
alert("uploading");
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload', //how to receive var here ?
type: 'POST',
cache: false,
data: {userfile: userfile},
success: function(data) {
alert(data);
$('.img_pre').attr('src', "<?php echo base_url().'uploads/' ?>");
$('.dltbtn').hide();
},
error: function(data)
{
console.log("error");
console.log(data);
alert("Error :"+data);
}
});
});
});
And my controller Upload's function do_upload is:
public function do_upload()
{
$config['upload_path'] = './uploads/'; #$this->config->item('base_url').
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('layouts/header');
$this->load->view('home_page', $error);
$this->load->view('layouts/footer');
}
else
{
$data = array('upload_data' => $this->upload->data());
$imagedata = $this->input->post('uerfile');
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$result = $this->model_edit->update_dp($id, $imagedata);
$image_name = $result->images;
$this->session->set_userdata('image', $image_name);
echo json_encode($name = array('image' => $image_name));
// $image_name = $this->upload->data('file_name');
// $data = array('upload_data' => $this->upload->data());
// redirect("account");
}
}
Now image is not even going to uploads folder, if any other file is needed tell me i'll post it here. Thanks
You cannot send file data using $("input#pfile").val();
var len = $("#pfile").files.length;
var file = new Array();
var formdata = new FormData();
for(i=0;i<len;i++)
{
file[i] = $("input#pfile").files[i];
formdata.append("file"+i, file[i]);
}
and send formdata as data from ajax
Hope it helps !
Try with the below ajax code
var formData = new FormData($('#formid'));
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload',
data: formData ,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
The file contents may not send through ajax as per your code. Try with the attributes mentioned in above code.

Reading response text in Ajax using JQuery

function upload_file(){
var file =document.getElementById('computer_image').files[0];
if(file!==null){
if(file.type==='image/jpeg' ||
file.type==='image/png' ||file.type==='image/jpg'){
$('#progressbar').show();
var formData = new FormData();
formData.append("file1", file);
$.ajax({
url: 'file_upload/ImageUpload',
type: 'POST',
headers: {"abc": "aaaaaaaaa"},
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandler, false);
}
return myXhr;
},
success: function( request,data, textstatus){
alert(textstatus.getResponseHeader('abc'));
},
error:errorHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
}
else {
alert('sorry we are not accepting file other than PNG , JPEG and JPG');
}
}
}
I am using CodeIgniter Framework .Below is my PHP code to Process a file .
function ImageUpload(){
$status="";
if (empty($_FILES["file1"]))
{
$status = "sorry Something went wrong";
$this->output->set_status_header('400');
echo "sorry Something went wrong";
}
if ($status !== "sorry Something went wrong")
{
//call a function to get path name
$path="./upload";
$config['upload_path'] = $path;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size' ] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['remove_spaces']=TRUE;
$config['overwrite'] = FALSE;
$this->load->library('upload', $config);
/* If directory doesn't exist than create a new .*/
if (!file_exists($path) && !is_dir($path)) {
mkdir($path);
}
/* If there is any error during upload */
if ( ! $this->upload->do_upload('file1')){
$this->output->set_status_header('400');
echo "sorry Something went wrong";
}
/*Image has been successfully Uploaded */
else{
$var = $this->upload->data('','');
echo $path.'/'.$var["file_name"].'='.$var["image_width"].
'='.$var["image_height"];
}
}
I have tried multiple flavor to get Response text but didn't success . What should be after complete to read response text .
getting null as output .
In $.ajax()'s success method first parameter will give response
Example:
$.ajax({
success: function(response, textStatus, jqXHR ){
console.log(response);
alert(response.getResponseHeader('abc'));
},
});
Check this link. It will be useful to understand $.ajax() more clearly.

Categories

Resources