Getting the input box name when clicked - php

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
});

Related

How do I receive appended data using dropzone using PHP

I am trying to use dropzone to upload an image, and pass the folder to upload the image to.
My html form:
<form action="upload.php" class="dropzone" id="dropzoneFrom"></form>
<br>
<div align="center">
<button type="button" class="btn btn-info" id="submit-all">Upload</button>
My JS Script:
$(document).ready(function(){
Dropzone.options.dropzoneFrom = {
autoProcessQueue: false,
acceptedFiles:".png,.jpg,.gif,.bmp,.jpeg",
// Initiate the button
init: function(){
var submitButton = document.querySelector('#submit-all');
myDropzone = this;
submitButton.addEventListener("click", function(){
myDropzone.on("sending", function(file, xhr, formData) {
formData.append("folder", "04"); // Append the folder to upload to.
});
myDropzone.processQueue();
});
this.on("complete", function(){
if(this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
{
var _this = this;
_this.removeAllFiles();
}
});
},
};
I am appending the additional folder to upload to like this:
myDropzone.on("sending", function(file, xhr, formData) {
formData.append("folder", "04"); // Append the folder to upload to.
});
But in my upload.php page, how do I receive this information? I am currently receive the file and processing it like this:
if(!empty($_FILES)){
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
}
I found this page which gives a really good modelled example showing that you simply use the $_POST['folder'] request:
https://gist.github.com/kreativan/83febc214d923eea34cc6f557e89f26c

How to get database value in AJAX Script using PHP MySQL

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;

Create upload status for each file JQuery and AJAX

I have a AJAX upload working and all ready to go, there really isnt any information the user can see except a percent and a progress bar. what i want to do is create a div for each file and show progress for each. Do i have to use flash or can i do this all from jquery because i got the ajax part done all thats left is to make the divs for each file and show a progress bar for each. if i were to upload multiple files it would show 1 progress bar that is uploading all the files together, i want to do it seperate for each. so basicly have one form to select multiple files and create a div for each file to show the percent complete of each.
JavaScript:
$('#Submit').click(function(event)
{
if ( !("FormData" in window) ) {
$('#Wrapper').append('<div class="DMsg"><label class="DText">You Are Using An Outdated Browser, Please Upgrade To Google Chrome Or Firefox, If You Dont Most Features Will Not Work. Click Anywhere To Dismiss.</label></div>');
$('#Wrapper').find('.DMsg').hide().slideDown('slow');
var Close = setTimeout(function()
{
$('.DMsg').slideUp('slow', function()
{
$('.DMsg').remove();
});
}, 10000);
}
else
{
function Upload()
{
event.preventDefault();
event.stopPropagation();
var FInput = $('#Files').val();
if(FInput != '')
{
var Data = new FormData();
var Files = document.getElementById('Files');
for(var I = 0; I < Files.files.length; ++I)
{
var FilesName = Files.files[I].name;
Data.append('File[]', Files.files[I]);
}
var Request = new XMLHttpRequest();
Request.upload.addEventListener('progress', function(event)
{
if(event.lengthComputable)
{
Percent = event.loaded / event.total;
Progress = document.getElementById('Progress');
Loaded = Math.round(Percent * 100);
$('#Progress').progressbar({
value: Loaded
});
$('#Loaded').text(Loaded + '%');
}
else
{
$('#Progress').text('There Was An Error Getting The Percent');
}
});
Request.upload.addEventListener('load', function(event)
{
});
Request.upload.addEventListener('error', function(event)
{
alert('Upload Failed.');
});
Request.addEventListener('readystatechange', function(event)
{
if(this.readyState == 4)
{
if(this.status == 200)
{
$('#Wrapper').append('<div class="DMsg"><label class="DText">Your Files Have Finished Uploading. Click Anywhere To Dismiss.</label></div>');
$('#Wrapper').find('.DMsg').hide().slideDown('slow');
$('#Loaded').text('100%');
$('#Progress').progressbar({
value: 100
});
var Close = setTimeout(function()
{
$('.DMsg').slideUp('slow', function()
{
$('.DMsg').remove();
});
}, 10000);
}
else
{
$('#Wrapper').append('<div class="DMsg"><label class="DText">There Was An Error In Uploading Your Files. Click Anywhere To Dismiss.</label></div>');
$('#Wrapper').find('.DMsg').hide().slideDown('slow');
var Close = setTimeout(function()
{
$('.DMsg').slideUp('slow', function()
{
$('.DMsg').remove();
});
}, 10000);
}
}
});
Request.open('POST', 'Upload.php');
Request.setRequestHeader('Cache-Control', 'no-cache');
Progress.style.display = 'block';
Request.send(Data);
}
else
{
$('#Wrapper').append('<div class="DMsg"><label class="DText">Please Select A File / Files. Click Anywhere To Dismiss.</label></div>');
$('#Wrapper').find('.DMsg').hide().slideDown('slow');
var Close = setTimeout(function()
{
$('.DMsg').slideUp('slow', function()
{
$('.DMsg').remove();
});
}, 10000);
}
}
var EachFile = 0
$.each($('#Files')[0].files, function()
{
++EachFile;
Upload();
});
}
});
HTML:
<div id="UForm">
<form action="" method="post" enctype="multipart/form-data">
<input type="file" class="Files" id="Files" name="File[]" />
<input type="submit" name="Submit" class="AB" id="Submit" value="Upload!" />
<div id="Progress"></div>
<div class="Caption"><label id="Loaded"></label></div>
</form>
</div>
Sorry for lots of code.
It shows a big load bar because you are searching for elements with the DMsg class and jquery searches from top-down so it will always find the first loading bar you set.
You need a way to set a different id to each new bar or when you do the
$('#Wrapper').find('.DMsg').hide().slideDown('slow');
find a way to get the last result.

The uploaded image not displayed after ajax upload in chrome

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

Ajax call not working on enter keypress, works only for click function

I have a ajax method of calling data from php file, i learned it from one of a blog, now it works file for submit button click function, but when i press enter the variables get shown in address bar and ajax process is not executed, Can any one please help me doing it on a press enter method....
This is my code:-
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
I have tried it by taking an if condition along with keypress event still its not working:-
if (e.keyCode == 13) { // Do stuff }
else { // My above code }
//In this also it seems that i am doing something wrong.
Can anybody please enlighten me oh how to do it.
My input field is:-
<input type="text" name="searchuser_text" id="newInput" maxlength="255" class="inputbox MarginTop10">
My submit button is:-
<input class="Button" name="search_user_submit" type="button" value="Search">
You can try with event.preventDefault(); for enter keypress.
Thanks.
When you type enter there is executed default onSubmit handler for a form. You can use submit jquery function to handle both enter and click on submit button.
$("form").submit(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
return false;
});
return false in this function will prevent submit of the form.

Categories