i want to upload image into mysql but filename get empty - javascript

addcategory.php
<div class=col-md-12>
<div class="form-group">
<label for="image">Background Image</label>
<input type="file" id="uploadedimage" name="uploadedimage"
placeholder="Background Image" class="file" data-preview-file-type="text">
</div></div>
<div class=col-md-2><div class="form-group">
<button class="btn btn-large btn-primary" name="add" id="add" type="button"
onclick="newsubject();">Add</button>
</div></div>
**subject.js**
function newsubject()
{
var xmlhttp;
var subject=document.frmsubject.subject.value;
var uploadedimage=document.getElementById("uploadedimage").files[0].name;
var x="frm=nsubject&subject="+subject+"&uploadedimage="+uploadedimage;
xmlhttp.open("GET","ajax/newsubject.php?"+x,true);
xmlhttp.send();
}
**newsubject.php**
function nsubject()
{
$sub=$_GET['subject'];
$img=$_GET['uploadedimage'];
echo $img;
if(!empty($_FILES[$img]["name"]))
{
echo "hello";
$file_name=$_FILES[$img]["name"];
$temp_name=$_FILES[$img]["tmp_name"];
$imgtype=$_FILES[$img]["type"];
$ext= GetImageExtension($imgtype);
$imagename=date("d-m-Y")."-".time().$ext;
$target_path = "adminImage/".$imagename;
if(move_uploaded_file($temp_name, $target_path))
{
$query_upload="INSERT into tblcategory(categname,bimage)
VALUES('$sub','$target_path')";
$res=mysql_query($query_upload);
}
}
by clicking on button, newsubject will be called from js file. subject name and img will be passed to newsubject.php file and then image will be uploaded.but whie doing so m getting $_FILES[$img]["name"] empty. please help.

Related

Dynamic Form Post Method on html with array in ASP.NET MVC

I'm building a view that with a modal opens a barcode scanner and every time that I scan a barcode I call a function startScanning() dynamically I'm building inputs inside a form.
When I click submit button I would like to send an array with all the barcodes the problem is that I'm not sure how to call the controller or what I should add in the Action in order to send the array or I if I need to change something in the elements.
My Modal Footer View
<div class="modal-footer">
(What I should write here to pass the array in the action)?
<form action="~/PurchaseOrder/ReceivedFromBarCode" method="post">
<label for="fname">Barcode:</label>
<div id="scanned-result" style="margin-bottom: 25px;"></div>
<div class="box-footer">
<button type="submit" class="btn btn-primary pull-right">
<i class="fa fa-paper-plane">
</i> Submit</button>
</div>
</form>
</div>
Javascript Function
function startScanning(facingMode) {
console.log(facingMode)
var results = document.getElementById('scanned-result');
var lastMessage;
var codesFound = 0;
function onScanSuccess(qrCodeMessage) {
if (lastMessage !== qrCodeMessage) {
lastMessage = qrCodeMessage;
++codesFound;
results.innerHTML += '<br><input placeholder="' + qrCodeMessage +']" name="barcode[' + codesFound + ']" type="text" id="barcode' + codesFound + '" value="' + qrCodeMessage + '" >';
}
}
Controller
[HttpPost]
public async Task<ActionResult> ReceivedFromBarCode(string[] barcode)
{
try
{
return RedirectToAction($"Details");
}
catch (VTHIS.CommunicationException cex)
{
throw cex;
}
}
Elements Console
<div class="modal-footer">
<form action="/secure/specialapp/admin/PurchaseOrder/ReceivedFromBarCode" method="post">
<label for="fname">Barcode:</label>
<div id="scanned-result" style="margin-bottom: 25px;">
<br>
<input placeholder="https://www.kwch.com" name="barcode[1]" type="text" id="barcode1" value="https://="www.kwch.com"><br>
<input placeholder="http://www.qrstuff.com" name="barcode[2]" type="text" id="barcode2" value=" http://www.qrstuff.com">
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary pull-right"><i class="fa fa-paper-plane"></i> Submit</button>
</div>
</form>
</div>

Controller method is not detecting any parameter

I'am trying to send an id in my url but my controller doesn't get that value
$("#ChangeSlideForm").on("submit", function(){
$.ajax({
type: "POST",
url: base_url + "Visualiser/ChangeSlide/21",
success: function (response) {
alert(response);
// $("#deleteConfirm").modal('hide');
// jQuery(function RefreshPageAdd($){
// $('#deleteConfirm').on('hidden.bs.modal', function (e) {
// location.reload();
// });
// });
}
});
});
My View
<div id="bodyChange" class="modal-body">
<form id = "ChangeSlideForm" action="<?php echo base_url() ?>Visualiser/ChangeSlide" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<label class="btnSlide btn btn-outline-success">
Zip <input class="file" name="file[]" type="file" hidden>
</label>
<label class="btnSlide btn btn-outline-success">
Csv <input class="file" name ="file[]" type="file" hidden>
</label>
</div>
<div class="modal-footer">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary col-md-6">Ajouter</button>
</div>
</form>
My controller header :
public function ChangeSlide($id){
print_r($id);
}
When I a put the id in the url directly then the parameter is accessible otherwise when I pass with ajax, It doesn't detect the parameter.
Try this:-
The HTML
<form id="ChangeSlideForm" action="<?php echo base_url() ?>Visualiser/ChangeSlide/21" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div id="bodyChange" class="modal-body">
<label class="btnSlide btn btn-outline-success"> Zip
<input class="file" name="file[]" type="file" hidden>
</label>
<label class="btnSlide btn btn-outline-success"> Csv
<input class="file" name="file[]" type="file" hidden>
</label>
</div>
<div class="modal-footer">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary col-md-6">Ajouter</button>
</div>
</div>
</form>
The Script:
<script type="text/javascript">
$(document).ready(function(){
$("#ChangeSlideForm").on("submit", function(e){
e.preventDefault();
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serializeArray(),
success : function(data)
{
console.log(data)
},
error: function (xhr)
{
console.log(xhr)
}
});
});
})
</script>
Try this
public function ChangeSlide(){
print_r($this->uri->segment(3));
}
You missing parameter data in $.ajax(). So your ajax didn't send any data to your controller
When you pass value with ajax then controller method get that value as $this->input->post('id'); not as parameter.
So you have to add following to method
public function ChangeSlide($id = "")
{
}

Uploading digital signature to folder and submitting to database

I have been trying to manage that the signature image gets submitted to upload to a folder and add to
the database at the same time but having a tough time. Everything is working except uploading the signature image to a folder and submitting it to the database with the same record.
I am using the digital signature from this jquery code : https://www.jqueryscript.net/mobile/Simpe-Mobile-Signature-Pad-with-jQuery-Html5-Canvas.html
Current example of what I have : http://dev.teqcube.com/signin-test/signin.php
This is for the 'New Visitor' Section
This is the form
<form method="post" action="">
<!-- VISITOR FIRST NAME -->
<div class="form-group">
<input type="text" class="form-control" name="visitor_first_name" id="visitor_first_name" placeholder="First Name" required>
</div>
<!-- VISITOR LAST NAME -->
<div class="form-group">
<input type="text" class="form-control" name="visitor_last_name" id="visitor_last_name" placeholder="Last Name" required>
</div>
<!-- VISITOR COMPANY NAME -->
<div class="form-group">
<input type="text" class="form-control" name="visitor_company_name" id="visitor_company_name" placeholder="Company Name" required>
</div>
<!-- VISITING PURPOSE -->
<div class="form-group">
<select class="custom-select form-control" name="visitor_visiting_purpose" id="visitor_visiting_purpose" style="width:100%;" required="required">
<option value="" selected>Visiting Purpose</option>
<option value="Visiting">Visiting</option>
<option value="Cleaning">Cleaning</option>
<option value="Delivery">Delivery</option>
<option value="Maintanance">Maintanance</option>
</select>
</div>
<!-- APARTMENT NUMBER -->
<div class="form-group">
<input type="text" class="form-control" name="visitor_visiting_apartment_number" id="visitor_visiting_apartment_number" placeholder="Apartment Number" required>
</div>
<!-- FORM SUBMIT FOR NEW REGISTRATION -->
<div class="submitBtnContainer">
<button type="button" data-toggle="modal" data-target="#digitalSignatureModal" class="btn my-2 my-sm-0 submitTakePhoto"><i class="fa fa-pencil" aria-hidden="true"></i>Signature</button>
<button type="submit" name="sign_visitor_in" class="btn btn-success my-2 my-sm-0 signoutVisitorFormOption1"><i class="fa fa-sign-in" aria-hidden="true"></i> Sign In</button>
</div>
<!-- #### MODAL TO APPLY DIGITAL SIGNATURE #### -->
<div class="modal fade" id="digitalSignatureModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<!-- MODAL BODY LOGO -->
<div class="col-md-12">
<div id="signinSuccessModalLogo">
<img src="img/Excellent-visitor-signin-small.png" alt="">
</div>
</div>
<!-- MODAL BODY CONTENT -->
<div class="col-md-12">
<div class="modal-body" id="signinSuccessModalContent">
<!-- DISPLAY IMAGE AFTER SIGNED -->
<div id="signaturePad" data-role="content"></div>
<!-- DIGITAL SIGNATURE SECTION -->
<div id="divPopUpSignContract">
<div class="ui-content popUpHeight">
<div id="div_signcontract">
<!-- CANVAS TO DRAW SIGNATURE -->
<canvas id="canvas">Canvas is not supported</canvas>
<!-- SUBMIT SIGNATURE OR CLEAR -->
<div class="col-md-12">
<!-- <input id="btnSubmitSign" type="button" class="btn btn-success" data-dismiss="modal" data-inline="true" data-mini="true" data-theme="b" value="Submit Signature" onclick="fun_submit()" style="border-radius: 5px; padding: 15px;" /> -->
<input id="btnSubmitSign" type="button" class="btn btn-success" data-inline="true" data-mini="true" data-theme="b" value="Submit Signature" onclick="fun_submit()" style="border-radius: 5px; padding: 15px;" />
<input id="btnClearSign" type="button" class="btn btn-warning commentbtn" data-inline="true" data-mini="true" data-theme="b" value="Clear" onclick="init_Sign_Canvas()" style="border-radius: 5px; padding: 15px;" />
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /MODAL BODY CONTENT -->
</div>
</div>
</div>
<!-- #### MODAL TO APPLY DIGITAL SIGNATURE #### -->
</form>
This is the php code to add the info to the database.
I am getting an error with $visitor_signature. I have tried different methods but not succeeding.
// ### SUBMIT SIGNIN FORM FOR NEW VISITOR REGISTRATION ###
if(isset($_POST['sign_visitor_in'])) {
date_default_timezone_set('Asia/Dubai');
$currentTime = date("H:i:s");
// *** RETREIVE SUBMITTED INFORMATION ON SUBMIT FOR NEW VISITOR REGISTRATION ***
$visitor_first_name = $_POST['visitor_first_name'];
$visitor_last_name = $_POST['visitor_last_name'];
$visitor_company_name = $_POST['visitor_company_name'];
$visitor_visiting_purpose = $_POST['visitor_visiting_purpose'];
$visitor_visiting_apartment_number = $_POST['visitor_visiting_apartment_number'];
//$visitor_visit_status = $_POST['visitor_visit_status'];
$visitor_signin_date = date("Y-m-d");
$visitor_signin_time = date("H:i:s");
$visitor_signout_date = date("H:i:s");
$visitor_signout_time = date("H:i:s");
$visitor_signature = $_FILES['visitor_signature']['name'];
$visitor_signature_tmp = $_FILES['visitor_signature']['tmp_name'];
move_uploaded_file($visitor_signature_tmp, "img/sign-in-signatures/$visitor_signature");
exit();
// *** I added exit() for testing purpose and once it works I remove it.
// *** ADD NEW VISITOR SIGNIN RECORD TO DATABASE ***
$query = "INSERT INTO visitors(visitor_first_name, visitor_last_name, visitor_company_name, visitor_visiting_purpose,
visitor_visiting_apartment_number, visitor_visit_status, visitor_signin_date, visitor_signin_time, visitor_signout_date, visitor_signout_time, visitor_signature)";
$query .= "VALUES('{$visitor_first_name}', '{$visitor_last_name}', '{$visitor_company_name}',
'{$visitor_visiting_purpose}', '{$visitor_visiting_apartment_number}', 'Signed In', '{$visitor_signin_date}', '{$visitor_signin_time}', '', '', '{$visitor_signature}')";
$result = mysqli_query($connection, $query);
// *** GENERAL CONFIM QUERY ***
if(!$result) {
die("QUERY FAILED. " . mysqli_error($connection));
}
}
The below code is part of the js file where the signature takes place
function fun_submit() {
if(isSign) {
var canvas = $("#canvas").get(0);
var imgData = canvas.toDataURL();
jQuery('#signaturePad').find('p').remove();
jQuery('#signaturePad').find('img').remove();
jQuery('#signaturePad').append(jQuery('<p>Your Signature:</p>'));
jQuery('#signaturePad').append($('<img/ name="visitor_signature">').attr('src',imgData));
// I BELIEVE THIS IS WHERE THE PROCESS HAPPENS TO UPLOAD THE IMAGE TO THE FOLDER
// I HAVE BEEN TRYING WITH DIFFERENT CODES IN THIS SECTION BUT NOT SUCCEEDING
closePopUp();
} else {
alert('Please sign');
}
}
Any help would be gladly appreciated.
Regards
I think that you should :
change your HTML code with adding a hidden field in your form, like this :
<input type=hidden name="visitor_signature" id="visitor_signature">
change your JS code in the fun_submit() function with adding : jQuery('#visitor_signature').val(imgData)
and finally change your PHP code from :
$visitor_signature = $_FILES['visitor_signature']['name'];
$visitor_signature_tmp = $_FILES['visitor_signature']['tmp_name'];
move_uploaded_file($visitor_signature_tmp, "img/sign-in-signatures/$visitor_signature");
to
$visitor_signature = $_POST['visitor_signature'];
// we receive something like : data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAvcAAADICAYAAABszM7qAAAZc0lEQVR4Xu3da4hVVRsH8GVeS
// we remove the "data:image/png;base64,"
$visitor_signature = preg_replace('#^data:image/\w+;base64,#i', '', $visitor_signature);
$visitor_signature = base64_decode($visitor_signature);
file_put_contents("img/sign-in-signatures/visitor_signature.png",$visitor_signature);
as the signature image isn't anymore a uploaded file, but a base64 string put in the textfield "visitor_signature"
thank you so much for your time, I appreciate it.
I did as you pointed out to me and started getting an sql error : You have an error in your SQL syntax; check the manual that corresponds to your SQL server version for the right syntax to use near
I then had a look around and added base64_encode before it inserts into the db and then it worked. Without the base64_decode the image won't open in the folder but without the encode afterwards it doesn't upload to the db. Code looks like this now :
$visitor_signature = $_POST['visitor_signature'];
// we receive something like : data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAvcAAADICAYAAABszM7qAAAZc0lEQVR4Xu3da4hVVRsH8GVeS
// we remove the "data:image/png;base64,"
$visitor_signature = preg_replace('#^data:image/\w+;base64,#i', '', $visitor_signature);
$visitor_signature = base64_decode($visitor_signature);
file_put_contents("img/sign-in-signatures/" . $visitor_first_name . "_" . $visitor_last_name . "_signature_" . $visitor_company_name . ".png",$visitor_signature);
$visitor_signature = base64_encode($visitor_signature);
Inside the db it still add a huge string but in the backend I am calling the image :
// VISITOR SIGNATURE IMAGE
echo "
<td style='text-align:center;'>
<img src='../img/sign-in-signatures/{$visitor_first_name}_{$visitor_last_name}_signature_{$visitor_company_name}.png' width='125px'>
</td>";
Once again thank you for your time, I hope you have a great upcoming 2019.
Regards

Uploading image using ajax to submit form taking a lot of time

Basically I am using html form for uploading image on server. Below is my code for form:
<div class="modal modal-fixed-footer" id="modal-image">
<div class="modal-content">
<h3>Upload Image</h3>
<form id="uploadimg" enctype="multipart/form-data">
<input type="hidden" name="entity" value="order">
<input type="hidden" name="orderId" value="<?php echo $orderId; ?>">
<input type="hidden" name="status" value="<?php echo $json->response->body->order->status; ?>" />
<input type="hidden" name="url" value="order-details.php?order=<?php echo $orderId; ?>&e=0">
<div class="form-inputs p-l-r-0">
<div class="row">
<div class="col s12">
<div class="file-field input-field" style="display:none">
<div class="btn accent-color">
<span>File</span>
<input type="file" id="fileToUpload" name="fileToUpload[]" multiple="multiple">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Upload one or more images">
</div>
</div>
</div>
</div>
<div id="dvPreview" class="row"></div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn-flat modal-action modal-close" id="uploadimg-submit">Submit</button>
<button class="btn-flat modal-action modal-close">Close</button>
</div>
Now when the #uploadimg-submit is clicked below jquery code is executed:
$('#uploadimg-submit').on('click', function(e) {
e.preventDefault();
$("form#uploadimg").submit();
});
and form submit function:
$("form#uploadimg").submit(function(e2) {
var smoothState = $('#main').smoothState().data('smoothState');
e2.preventDefault();
var formData = new FormData($(this)[0]);
// console.log(formData);
$.ajax({
url: 'processors/process-upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
beforeSend: function() {
ajaxindicatorstart();
},
success: function(rsp) {
if (rsp == '200') {
Materialize.toast('Image Uploaded Successfully', 2000, 'green');
smoothState.clear('/order-details.php');
smoothState.load('/order-details.php?order=' + $('#order_id').val());
} else {
Materialize.toast('Image Uploaded Failed', 2000, 'red');
smoothState.clear('/order-details.php');
smoothState.load('/order-details.php?order=' + $('#order_id').val());
}
},
error: function() {
Materialize.toast('Image Uploaded Failed', 2000, 'red');
smoothState.clear('/order-details.php');
smoothState.load('/order-details.php?order=' + $('#order_id').val());
}
});
return false;
});
The file process-upload.php takes less than a second to process the image which i debugged using microtime(true). But total time take by sending request and recieving response is nearly 11 secs, majority of which (about 9 secs) is taken in sending request. Below are timeline analytics from chrome dev tools.
I want to reduce this time else it will be unfeasible to wait so long for uploading image. Is there any way I can optimize it further?

Saving and displaying uploaded image

I have an already existing picture and I want to upload a new one and replace the old picture, but this code is not working. (I have a button whose onclick attribute is photoSave().) Can someone tell what's wrong with this Javascript code and maybe write a possible solution?
This is the important part of the code:
<div class="row">
<div class="col-md-12">
<div class="profilePic" id="profilePic">
<img src="prof.jpg" id="pictureToShow" />
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<div id="photoButton">
<label class="btn btn-default btn-file" style="width:220px" onclick="photoChange()">
Profilkép megváltoztatása <input type="file" accept="image/*" style="display: none" id="newPhoto">
</label>
</div>
</div>
</div>
<script type="text/javascript">
function photoChange() {
document.getElementById("photoButton").innerHTML = '<button type="button" style="width:110px" class="btn btn-success btn-s" onclick="photoSave()">Mentés</button><button type="button" style="width:110px" class="btn btn-danger btn-s" onclick="photoSave()">Mégse</button>'
}
function photoSave() {
document.getElementById("photoButton").innerHTML = '<label class="btn btn-default btn-file" style="width:220px" onclick="photoChange()">Profilkép megváltoztatása<input type="file" accept="image/*" style="display: none"></label>'
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#pictureToShow').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
When you're uploading a file via input type="file", the file is not yet saved in your server.
Two solutions:
So you need to put this file in your resources repo on your web
server.
Or you can preview the image, see
Preview an image before it is uploaded
Add the following js in your function:
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#pictureToShow').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
Moreover, your image does not have an ID attribute, so you need to change <img src="prof.jpg" /> for <img src="prof.jpg" id="pictureToShow" />.

Categories