How can I get it so that when the user clicks on the "Cancel" button, then in the cancel button function where it contains the variable var image_file_name, it retrieves the name of the file which was entered within the file input? Then hopefully the $GET method in the cancelimage.php page can be used to retrieve the file name from the function?
Below is my attempt but it is not retrieving a file name. It is just retrieving a blank.
Below is the form code and javascript function which controls the "Cancel" button:
var $fileImage = $("<form action='imageupload.php'
method='post'enctype='multipart/form-data' target='upload_target' onsubmit='return
startImageUpload(this);' class='imageuploadform' ><label>" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/>
<br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload'/>
</label>" +
"<input type='button' name='imageCancel' class='imageCancel' value='Cancel'/>
</label>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>")
...
var _cancelimagecounter = cancelimagecounter;
$(".imageCancel").click(function() {
var image_file_name = <?php echo json_encode($image_file_name); ?>;
jQuery.ajax("cancelimage.php?fileImage=" + image_file_name)
.done(function(data) {
$(".imagemsg" + _cancelimagecounter).html(data);
});
return stopImageUpload();
});
Below is the cancelimage.php script where it uses the $GET method to get the file name from the var image_file_name:
<?php
...
$image_file_name = $_GET["fileImage"];
echo "File Upload was Canceled";
$imagecancelsql = "DELETE FROM Image
WHERE ImageFile = 'ImageFiles/". mysql_real_escape_string($image_file_name)."'";
mysql_query($imagecancelsql);
mysql_close();
?>
Filename is far form the issue here.... But your fileName is not displaying because you are trying to use $_GET["fileImage"];
The Form was submitted via enctype='multipart/form-data and <input name='fileImage' type='file'
You should use $_FILES instead ...
Your file name would be
$image_file_name = $_FILES['fileImage']['name'] ;
Related
I'd like to upload a file in one click, so I tried to combine two click events in one, but the $_FILE variable does not load the image, here's my code :
<form target='_self' action='upload.php' method='post' enctype='multipart/form-data'>
<div class = 'testocentrato'>
<input style='display:none' type='file' accept='.jpg' name='file' id='file'/>
<input style='display:none' type='submit' id='caricaimmagine' name='caricaimmagine' />
<input class='inputfile' type='button' value='Scegli file da PC' onclick='document.getElementById('file').click(); document.getElementById('caricaimmagine').click();' />
<input style='display:none' type='submit' />
<input class='inputfile' type='submit' name='eliminaimmagine' onclick='document.getElementById('eliminaimmagine').click();' value='".$lang['TASTO_ELIMINA_FOTO']."' />
<input type='hidden' name='id_utente' value='".$user['id']."' />
</form>
It is possible to upload images with one click with ajax, check https://makitweb.com/how-to-upload-image-file-using-ajax-and-jquery/.
here is my html code I used the label tag so when I click the upload icon the select file windows will appear.
<form method="post" enctype="multipart/form-data">
<label class='foto' for="imgid">
<img id="photo" src="images/photo.png">
<p>Foto</p>
</label>
<input type="file" value="chosen File" id="imgid" name="img" accept="image/*">
<img class="previewimg" src="" width="100" height="100">
<span id="showImagePath" ></span>
<button class="btn btn-primary" id="toPost">Post</button>
</form>
mycss.
#imgid{
display:none;
}
.foto{
float:left;
}
.previewimg{
display:none;
background-color:grey;
}
#imgToPost{
display:none;
}
my Jquery:
I used setInterval() function to make my script run until the image is selected that way is going to be uploaded and the name and the image can be previewed.
$("#photo").click(function(){
setInterval(function(){
var fd = new FormData();
var files = $('#imgid')[0].files;
// Check file selected or not
if(files.length > 0 ){
$(".previewimg").show();
fd.append('file',files[0]);
$.ajax({
url: 'action.php?action=postcontentimage',
type: 'post',
data:fd,
contentType: false,
processData: false,
success: function(result){
var name ="";
if(result != 0){
$(".previewimg").attr("src", result).show();
for(var i=0; i < result.length;i++){
if(i>8){
name += result[i];
}
$("#showImagePath").html(name);
clearInterval();
}
}
}
})
}else{
alert("no image has been selected");
}
}, 2000);
})
my PHP:
<?php
if(isset($_FILES['file']['name'])){
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "uploads/".$filename;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
/* Valid extensions */
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
/* Check file extension */
if(in_array(strtolower($imageFileType), $valid_extensions)) {
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
$response = $location;
}
}
echo $response;
exit;
}else{
echo 0;
}
?>
Because you are directly clicking on submit before secting the file.
Remove
document.getElementById('caricaimmagine').click();
You need to click that button manually.
I have rendered an image via html2canvas and jquery:
<script>
function capture() {
console.log("function is running");
jQuery('#square').html2canvas({
onrendered: function(canvas) {
var url;
url = canvas.toDataURL("image/png");
//Set hidden field's value to image data (base-64 string)
jQuery('#img_val').val(canvas.toDataURL("image/png"));
//Submit the form manually
//var myImage = canvas.toDataURL("image/png");
window.open(url);
jQuery("#myForm").submit();
console.log(jQuery('#img_val').val());
}
});
}
</script>
The code works all fine, and I see the image via the window.opne.
The issue I have is when I submit my form holding the image value is NOT passed. I know it's set because I see that via console.
My form:
<input type="submit" value="Take Screenshot Of Div" onclick="capture();" />
<form method="POST" enctype="multipart/form-data" action="/save.php" id="myForm">
<input type="hidden" name="img_val" id="img_val" value="" />
</form>
My Save.php
<?php
//save.php code
//Show the image
var_dump($_POST['img_val']);
echo 'Billede:<br />';
echo '<img src="'.$_POST['img_val'].'" />';
//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
//Decode the string
$unencodedData=base64_decode($filteredData);
//Save the image
file_put_contents('img' . rand(0,10000) . '.png', $unencodedData);
?>
Why is the value of the renderend image not passed via my form - when I know I set it via jQuery ?
in the QandATable.php I have a form below which contains a file input and an iframe:
var $fileVideo = $("<form action='videoupload.php' method='post' enctype='multipart/form-data' target='upload_target_video' onsubmit='return videoClickHandler(this);' class='videouploadform' >" +
"Video File: <input name='fileVideo' type='file' class='fileVideo' /></label>" +
"<input type='submit' name='submitVideoBtn' class='sbtnvideo' value='Upload' /></label>" +
"<p class='listVideo' align='left'></p>" +
"<iframe class='upload_target_video' name='upload_target_video' src='/' style='width:0px;height:0px;border:0px;solid;#fff;'></iframe></form>");
Now below I have a jquery code which is triggered when the file has finished uploading.
function stopVideoUpload(success, videofilename){
var result = '';
videocounter++;
if (success == 1){
result = '<span class="videomsg'+videocounter+'">The file was uploaded successfully</span>';
$('.listVideo').eq(window.lastUploadVideoIndex).append('<div>' + htmlEncode(videofilename));
}
return true;
}
Now the result of the file upload and the file name is determined with the code below. But what my question is that how can I display the $id variable in a text input?
<script language="javascript" type="text/javascript">
window.top.stopVideoUpload(<?php echo $result; ?>,'<?php echo $id . $_FILES['fileVideo']['name'] ?>');
</script>
I might be misunderstanding your question, but if you change type='text' to type='hidden' on your input field, then the $id variable will be in a hidden input.
I have a cancel button where the user can cancel on a file upload and it will display a cancel message. Now what I want also to happen is that when the user clicks on the Cancel button, it will look up for the file name which has been cancelled in the database and delete the database row. Problem is that it is not deleting the database row at all. How can I get this to happen. At the moment I am using the jpuery.ajax method which you can see in code below.
Below is form code:
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><p class='imagef1_cancel' align='center'><label>" +
"<input type='button' name='imageCancel' class='imageCancel' cancel_image_file_name='" + imagefilename + "' value='Cancel' /></label></form>");
Below is the cancel button function:
$('.imagef1_cancel').eq(window.lastUploadImageIndex).find(".imageCancel").on("click", function(event) {
var cancel_image_file_name = $(this).attr('cancel_image_file_name');
jQuery.ajax("cancelimage.php?imagefilename=" + cancel_image_file_name)
return stopImageUpload(2, cancel_image_file_name);
});
Finally below is the cancelimage.php script where the jquery.ajax navigates to, to supposedly be able to delete the the database row containing the file name:
<?php
...
//I have connected to database
$cancel_image_file_name = $_GET["imagefilename"];
$imagecancelsql = "DELETE FROM Image
WHERE ImageFile = 'ImageFiles/". mysql_real_escape_string($cancel_image_file_name)."'";
mysql_query($imagecancelsql);
mysql_close();
?>
UPDATE:
Below is what it currently shows when I echo the delete query:
Notice: Undefined index: imagefilename in /web/stud/xxx/.../cancelimage.php on line 19
DELETE FROM Image WHERE ImageFile = 'ImageFiles/'
Below is the code of the delete function where when the Delete Button is pressed, it will navigate to the deleteimage.php script and delete the database row:
function stopImageUpload(success, imagefilename){
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>');
$('.listImage').eq(window.lastUploadImageIndex).find(".deletefileimage").on("click", function(event) {
var image_file_name = $(this).attr('image_file_name');
jQuery.ajax("deleteimage.php?imagefilename=" + image_file_name)
$(this).parent().remove();
});
return true;
}
Below is deleteimage.php script:
<?php
//connected to DB
$image_file_name = $_GET["imagefilename"];
$imagedeletesql = "DELETE FROM Image
WHERE ImageFile = 'ImageFiles/". mysql_real_escape_string($image_file_name)."'";
mysql_query($imagedeletesql);
mysql_close();
?>
Below is an UPDATE of what the cancel button function now looks like:
function startImageUpload(imageuploadform, imagefilename){
$('.imagef1_cancel').eq(window.lastUploadImageIndex).find(".imageCancel").on("click", function(event) {
var cancel_image_file_name_ = $(this).attr('css');
var cancel_image_file_name = '';
var style_array = cancel_image_file_name_.split(" ");
for(i=0;i<style_array.length;i++){
if(style_array[i].substr(0,2) == "__"){
cancel_image_file_name = style_array[i].slice(2,style_array[i].length-2);
}
}
jQuery.ajax("cancelimage.php?imagefilename=" + cancel_image_file_name)
return stopImageUpload(2, cancel_image_file_name);
});
return true;
}
I changed the button input tag to this for cancel button:
<input type='button' name='imageCancel' class='imageCancel __"+ imagefilename + "' value='Cancel' />
Try these changes:
on form:
<input type='button' name='imageCancel' class='imageCancel __"+ imagefilename + "' value='Cancel' /></label></form>
on cancel button function:
var cancel_image_file_name_ = $(this).attr('class');
var cancel_image_file_name = '';
var style_array = cancel_image_file_name_.split(" ");
for(i=0;i<style_array.length;i++){
if(style_array[i].substr(0,2) == "__"){
cancel_image_file_name = style_array[i].slice(2,style_array[i].length);
}
}
I have a a form which contains a file input and upload button
<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='stopImageUpload(this);' class='imageuploadform' >
<p class='imagef1_upload_form' align='center'><label>Image File: <input name='fileImage' type='file' class='fileImage' /></label>
<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>
</p>
<p><span class='list></span></p>
</form>
Now what I want is that if an image has finished uploading, at the bottom of this form (in the span tag 'list') I want the name(s) of the file that have been uploaded. So when a file is successfully uploaded, then it should display the name of the uploaded file. If a second file is successfully upoaded, then it displays the name of the uploaded second file below the name of the first file.
Is this possible in Javascript?
I have uploading of files all sorted out in php and javascript. Below is javascript function after uploading is complete:
function stopImageUpload(success) {
var result = '';
if (success == 1) {
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
};
return true;
}
This function is in the same page in the fomr but not in the same page as the uploading script but in the uploading script does call on this function using this javascript code below:
<script language="javascript" type="text/javascript">window.top.window.stopImageUpload(<?php echo $result; ?>);</script>
Below is part of the uploading php code where it uploads the file into the server:
move_uploaded_file($_FILES["fileImage"]["tmp_name"],"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
Your PHP callback should contain the name of the file currently uploaded, or even an array of all uploaded files.
Then, in the stopImageUpload function, read that second parameter and manipulate #list accordinly (update/add html):
<ul id="list"></ul>
function stopImageUpload(success, filename) {
var result;
if (success == 1)
result = '<li class="msg">The file '+filename+' was uploaded successfully!</li>';
else
result = '<li class="emsg">There was an error during upload of file '+filename+'!</li>';
$('#list').append(result);
return true;
}