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;
Related
Here is my code. i want to upload the image file using ajax, php. when the image file is uploaded it should show the preview. The image file is successfully uploading but the ajax success is not showing the preview.
Here is my form code:
<form method="post" enctype="multipart/form-data">
<div class='preview'>
<img src="" id="photo_disp" width="100" height="100">
</div>
<input type="file" name="file1" id="file1" accept=".jpeg,.jpg" required/>
<button type="submit" id="btn_photo" name="submit">Upload Photo</button>
</form>
Here is the ajax i have used. The ajax is successfully posting the file to php code but the success response is not working.
<script>
$(document).on('click','#btn_photo',function(){
var fd = new FormData();
var files = $('#file1')[0].files;
// Check file selected or not
if(files.length > 0 )
{
fd.append('file',files[0]);
$.ajax({
url:'ajax_photo.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response)
{
alert(response);
if(response != 0)
{
$("#photo_disp").attr("src",response);
}
else
{
alert('File not uploaded');
}
}
});
}
else
{
alert("Please select a file.");
}
});
</script>
Here is my php code using on click
<?php
if(isset($_FILES['file']['name']))
{
session_start();
$filename = $_FILES['file']['name'];
$roll=$_SESSION['name'];
$imageFileType = pathinfo($filename,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
$valid_extensions = array("jpg","jpeg");
$response = 0;
if(in_array(strtolower($imageFileType), $valid_extensions))
{
$location = "upload/".$roll.".".$imageFileType;
if(move_uploaded_file($_FILES['file']['tmp_name'],$location))
{
$response = $location;
}
}
echo $response;
exit;
}
echo 0;
?>
Please find out where i did the mistake. The image is successfully uploading to the given path but the image is not showing in the preview. i have written an alter in the success. But the alert is also not working.
If the response refers to a fully qualified resource path (https:example.com/upload/cat-dancing.jpg) on the server, you can assign it directly to the image's src attribute just like you've done in your question.
$("#photo_disp").attr("src",response);
If the returned resource path doesn't contain the domain name (upload/cat-dancing.jpg), prepend it with a forward slash to indicate that the path starts from the document root of the website. I.e:
$("#photo_disp").attr("src", "/" + response);
Otherwise, if the response is an actual File or Blob, you could set the image's src attribute using:
const img = $("#photo_disp").get(0);
img.src = URL.createObjectURL(response);
img.height = 60;
img.onload = function() {
URL.revokeObjectURL(this.src);
}
Set the image's source to a new object URL representing the file, using
URL.createObjectURL()
to create the blob URL.
Set the image's height to 60 pixels.
Set up the image's load event handler to release the object URL since it's no longer needed once the image has been loaded. This is
done by calling the
URL.revokeObjectURL()
method and passing in the object URL string as specified by img.src.
Resource:
Example: Using object URLs to display images
I am using dropzoneJS in my form. The form also record user input. Below code shows what I am doing in simple. Everything is working fine but php variable is not getting its value. It is somewhat like this
if (!empty($_FILES)) {
$imgID = submitData()//This functions upload image and write image url in database and then return ID of the affected row
}
When submit button in form is clicked, redirection is happening but $imgID is not getting its value
Here is the Javascript
Dropzone.options.myAwesomeDropzone = {
autoProcessQueue: false,
etc.. etc ..
init: function() {
var myDropzone = this;
$("#submit-all").click(function (e) {
e.preventDefault();
e.stopPropagation();
if (myDropzone.files.length) {
myDropzone.processQueue(); // upload files and submit the form
} else {
$('#my-awesome-dropzone').submit(); // submit the form
}
});
// Refresh page when all images are uploaded
myDropzone.on("complete", function (file) {
if (myDropzone.getUploadingFiles().length === 0 && myDropzone.getQueuedFiles().length === 0) {
var idvar = '<?php $imgID; ?>';
window.location.replace("/preview.php?id="+ idvar);
}
});
}
}
Suggest me where I am doing wrong. Is there any alternative available.
You can send the id back to the browser as response and take it with dropzone on success event like this.
php: (If this file is used to handle other requests a possible structure can be like this)
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' && !empty($_FILES))
{
$imgID = submitData();
echo $imgID;
}
else
{
// The rest of your php file shoul go in here.
}
js:
Dropzone.options.myAwesomeDropzone = {
// .........
init: function() {
// ........
// On success refresh
this.on("success", function (file) {
var idvar = $.trim(file.xhr.response);
window.location.replace("/preview.php?id=" + idvar);
}
}
}
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+"');");
}
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
});