Tried to upload the image using ajax with out page refresh . For uploading a file need to click the button on several times. any one plz fix this issue
<script language="javascript">
var loadImageWhite = '<img src="images/loader_small_white.gif" alt="Loading.."/>';
function imageUpload(id,upload_dir) {
var loadImg = loadImageWhite;
var imgVal = $('#hid_img_val'+id).val();
if(imgVal)
{
removeImage(imgVal,id);
imgVal = '';
}
var uploader = document.getElementById('uploader'+id);
upclick(
{
element: uploader,
dataname: 'Filedata'+id,
action: 'ajaximage.php?file_name=Filedata'+id+'&file_path=registration_images/'+upload_dir+'/',
onstart:
function(filename)
{
//$('#save_btn'+id).attr('disabled','disabled');
$('#hid_img'+id).html(loadImg);
},
oncomplete:
function(response_data)
{
$('#hid_img_val'+id).val(response_data);
$('#hid_img'+id).html('<div id="hid_img" style="height:30px;"><div style="float:left;padding-right:10px;"><img width="30" height="30" src="registration_images/'+upload_dir+'/'+response_data+'"></div><div style="padding-top:10px;">Remove</div></div>');
//$('#save_btn'+id).removeAttr('disabled');
}
});
$('#Filedata'+id).attr("onClick","imageUpload('"+id+"');");
}
Related
I have uploaded the image and crop it with croppie, the image successfully updates the database and successfully enters the directory.
but the new image overwrites the old image with the same name, it was intentionally done. but the image displayed again by php remains the old image (the image has been overwritten with the new one)
Initially there was no problem but when I didn't open the project for more than 2 week there was a problem like the one above
HTML tag
<div class="col-sm-3">
<h4>Profile Picture</h4>
<hr>
<form action="" id="form" method="post">
<label class="cabinet center-block">
<figure><img src="" class="gambar img-responsive img-thumbnail" id="item-img-output" />
<figcaption><i class="fa fa-camera"></i></figcaption>
</figure>
<input type="file" class="item-img file center-block" name="file_photo"/>
</label>
</form>
</div>
JS with CROPPIE
<script type="text/javascript">
// Start upload preview image
$(".gambar").attr("src", "../profile/pictures/img/<?=$profile['profile']?>");
var $uploadCrop,
tempFilename,
rawImg,
imageId;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.upload-demo').addClass('ready');
$('#cropImagePop').modal('show');
rawImg = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Desculpe, seu navegador não suporta o FileReader API.");
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 230,
height: 230,
},
enforceBoundary: false,
enableExif: true
});
$('#cropImagePop').on('shown.bs.modal', function(){
// alert('Shown pop');
$uploadCrop.croppie('bind', {
url: rawImg
}).then(function(){
console.log('jQuery bind complete');
});
});
$('.item-img').on('change', function () { imageId = $(this).data('id'); tempFilename = $(this).val();
$('#cancelCropBtn').data('id', imageId); readFile(this); });
$('#cropImageBtn').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'base64',
format: 'jpeg',
size: {width: 270, height: 270}
}).then(function (resp) {
$('#item-img-output').attr('src', resp);
//$('#cropImagePop').modal('hide');
$.ajax({
url: "../lib/proses/upload.php",
type: "POST",
data: {"image":resp},
success: function (data) {
html = '<img src="' + resp + '" />';
$("#upload-image-i").html(html);
$('#cropImagePop').modal('hide');
swal.fire(
'Berhasil !',
'Profile berhasil diubah',
'success'
)
}
});
$('#cropImagePop').modal('hide');
});
});
// End upload preview image
</script>
Upload Process
<?php
session_start();
require "../koneksi.php";
$username = $_SESSION['username'];
$croped_image = $_POST['image'];
list($type, $croped_image) = explode(';', $croped_image);
list(, $croped_image) = explode(',', $croped_image);
$croped_image = base64_decode($croped_image);
$image_name = $username.'.png';
// insert name to database
$sql = "UPDATE users SET profile = '$image_name' WHERE username = '$username'";
$query = mysqli_query($conn, $sql);
// upload cropped image to server
file_put_contents('../../profile/pictures/img/'.$image_name, $croped_image);
?>
I want the newly uploaded image to appear to replace the old image in
the file that displays the image (ex. index file, etc.)
Have you checked your browser cache? Maybe try adding a random param to image path, like myimage.jpg?c=[randomNumber], this will force the browser to download the image again.
Clear your cache, are you using a PHP framework?
I have a code here
<h2>Click blue button</h2>
<button id="open_btn" class="btn btn-primary">Open dialog</button>
<div id="output"></div>
<script src="src/bootstrap.fd.js"></script>
<script type="text/javascript">
$("#open_btn").click(function() {
$.FileDialog({multiple: true}).on('files.bs.filedialog', function(ev) {
var files = ev.files;
var text = "";
files.forEach(function(f) {
text += f.name + "<br/>";
});
$("#output").html(text);
}).on('cancel.bs.filedialog', function(ev) {
$("#output").html("Cancelled!");
});
});
</script>
its a drag and drop upload using jquery and boostrap layout from http://www.jqueryscript.net/demo/Drag-Drop-File-Upload-Dialog-with-jQuery-Bootstrap. Its working, but the problem is, I don't know how to pass the data uploaded to php for processing and put the file into the server.
Anyone can help me with this?
you can try using ajax. Setup ajax in your project from tons of tutorials available on the net.
After that in your javascript function i suppose you want to pass variable text to php. So here's what you can do when you get a little hang about ajax by going through the tutorials
<script type="text/javascript">
$("#open_btn").click(function() {
$.FileDialog({multiple: true}).on('files.bs.filedialog', function(ev) {
var files = ev.files;
var text = "";
files.forEach(function(f) {
text += f.name + "<br/>";
});
$.ajax({
url: "'your php function name'?name ="+text,
success: function( data ) {
if(data == "retn value") { //return value of the php function
// alert("");
} else {
}
}
});
$("#output").html(text);
}).on('cancel.bs.filedialog', function(ev) {
$("#output").html("Cancelled!");
});
});
</script>
create a function in php which will take your data as an argument.
hope this helps.
Below i have mentioned AJAX script, I wanted to append id from database for each photo when I upload.But when using "var m='_'+x;" in the below script it doesnt get the database id for the record(WHen i print it,It appears blank).So how to retrieve database id for a row and append in AJAX script?The photo gets uploaded and stores in the mentioned folder with the id.But in that page while i check page source it shows .The Id doesnt get loaded in middle.
$(function(){
var btnUpload=$('#me');
var mestatus=$('#mestatus');
var files=$('#files');
new AjaxUpload(btnUpload, {
action: 'uploadPhoto.php',
name: 'uploadfile',
onSubmit: function(file, ext)
{
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
// extension is not allowed
mestatus.text('Only JPG, PNG or GIF files are allowed');
return false;
}
mestatus.html('<img src="ajax-loader.gif" height="16" width="16" align="left">');
},
onComplete: function(file, response){
// alert(response)
//On completion clear the status
mestatus.text('');
//On completion clear the status
files.html('');
//Add uploaded file to list
if(response==="success")
{
var x=file;
var m='<?=$data44[id]?>_'+x;
document.getElementById('img_name').value=x;
$('<li></li>').appendTo('#files').html('<img src="photo/demophoto_'+m+'" alt="" height="110px" width="95px" /><br />').addClass('success');
} else{
$('<li></li>').appendTo('#files').text(file).addClass('error');
}
}
});
});
Uploadphoto.php
include_once("db.php");
$sel="select usnno from usn where id='$_SESSION[lgkey]'";
$qry=mysql_query($sel) or die(mysql_error());
$row=mysql_fetch_array($qry);
$sel44=mysql_query("select * from reg_form where usn='$row[usnno]' ");
$data44=mysql_fetch_array($sel44);
$uploaddir = './photo/';
$file = $uploaddir ."demophoto_".$data44['id'].'_'.basename($_FILES['uploadfile']['name']);
$file_name= "demophoto_".$data44['id'].'_'.$_FILES['uploadfile']['name'];
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
echo "success";
} else {
echo "error";
}
Please change your code from:
var m='<?=$data44[id]?>_'+x;
to the following:
var m='<?=$data44["id"]?>_'+x;
Just add double quotation marks between the "id".
Ttry this
var m="<?php echo $data44['id']; ?>_"+x; or var m='<?php echo $data44[id]; ?>_'+x;
instead of var m='<?=$data44[id]?>_'+x;
I did an ajax upload with php.Everything wiil be perfect in firefox.
But when i test it in chrome browser its not working correctly.
That means it displays this :
This is my ajax upload code:
$(function(){
var cntUp = 0;
var btnUpload=$('#upload0');
var status=$('#status');
var state='left_front';
new AjaxUpload(btnUpload, {
action: 'upload-file.php',
data: {saleid: $("#hid_saleid").val(),imag_state:state,custom:$('#custom').val()},
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
// extension is not allowed
alert('Only JPG, PNG or GIF files are allowed');
return false;
}
this.setData({
'saleid': $("#hid_saleid").val(),
'imag_state':'left_front',
'custom':$('#custom').val()
});
status.text('Uploading...');
},
onComplete: function(file, response){
var array_data=response.split('***');
var fname= array_data[1];
var rand=Math.floor((Math.random()*10)+1);
var saleid = $("#hid_saleid").val();
var custom = $('#custom').val();
//On completion clear the status
status.text('image uploaded');
cntUp++;
//console.log(cntUp);
//Add uploaded file to list
if (response.toLowerCase().indexOf("success") >= 0 ) {
var image='<img src="uploads/'+saleid+'/'+fname+'" alt="" width="131px" height="125px"/>';
$("#img0").html(image);
} else{
$('<li></li>').appendTo('#files').text(file).addClass('error');
//alert('error');
}
}
});
});
This is the html code:
<div class="brwse_box">
<div style="float:left;" id="upload0">
<h3>Left Front</h3>
<img src="images/upload.gif" />
</div>
<div style="float:right; width:131; height:125" id="img0">
<?php if($l_ft==''||$l_ft==NULL) { ?>
<img src="images/no-photo-lft-frnt.jpg" id="bg"/>
<?php } if($l_ft!=''||$l_ft!=NULL){?>
<img src="uploads/<?php echo $var_sid;?>/<?php echo $l_ft;?>" id="bg" width="131px" height="125px"/>
<?php }?>
</div>
</div><!--browse_box ENDS-->
How can i solve this?
It displaying image in firefox.but in chrome not displaying image instead of that displaying html of image tag.
EDIT:
This is the value return in fname variable:
left_front.jpg<div id=isChromeWebToolbarDiv" style="display:none"></div>
It seems you have a problem in the src string.
Check it for escape characters...
I'd say it's possible that fname contains quotes...
EDIT:
What "isChromeWebToolbarDiv"?
fname = fname.replace(new RegExp("<div id=isChromeWebToolbarDiv(.*)</div>"),'');
or simply
fname = fname.replace(new RegExp("<div(.*)</div>"),'');
after your EDIT on question, it came to know that
is coming in src
This is caused by a Chrome extension called DVDvideosoftTB. It appears to append the above HTML to file upload requests. You can easily disable it:
Click on the Wrench icon
Click "Tools"
Click "Extensions"
Disable DVDvideosoftTB
In my site I use 10 file upload boxes. I want to get a file upload box name when I click on the box.
That means first upload box, second upload box, third upload box etc...
So if I click on the first upload box then I want to get name of that file upload box.
How can i get the upload button name in ajax function.
This is my ajax code:
$(function(){
var countfile = 10;
var strfileid = '';
for(i=1;i<=countfile;i++){
var btnUpload=$('#browse'+i);
var adinfoid=$('#adinfoid').val();
new AjaxUpload(btnUpload, {
action: '<?php echo base_url()?>index.php/post/upload_editgalleryimage/'+adinfoid,
name: 'uploadfile',
onSubmit: function(file, ext){
alert(btnUpload.Name);
var photoplancnt=$('#photoplancnt').val();
var hidcountimg=$('#hidcountimg').val();
if(parseInt(hidcountimg)>=parseInt(photoplancnt)){
$("#photoerror").html('maximum '+photoplancnt +' files are allowed');
$("#photoerror").css('display','block');
return false;
}
if (! (ext && /^(jpg|png|jpeg|gif|JPG|PNG|JPEG|GIF)$/.test(ext))){
$("#photoerror").html('Only JPG, PNG, GIF, files are allowed');
$("#photoerror").css('display','block');
return false;
}
},
onComplete: function(file, response){
if(response){
$(".upload_main_div").html('');
$(".upload_main_div").html(response);
var insid = $("#hiddengalidnow").val();
calltoloadimage(insid);
/*$("#galimageicon").attr("src",response);
$("#galimageicon").attr("width",55);
$("#galimageicon").attr("height",55);*/
//$("#mainimageicon1").attr("src",response);
}else{
alert("error");
}
}
});
}
});
It will alert 'browse12' at all time.
Html code:
<?php
for($i=1;$i<=10;$i++){
?>
<input type="button" id="browse<?php echo $i;?>" name ="browse<?php echo $i;?>" class="browse_media" value="Browse">
<?php
}
?>
Finally
alert(this._button.name);
Generally:
$('input[type=file]').on('click', function() {
var name = $(this).attr('name'); // or this.name
});
for you case:
btnUpload.attr('name');
Maybe this will help
$("input[id^=browse]").click(function(){
var strBrowseName = $(this).attr('name');
// Or no var, if it has already been defined
});