I have a QR code scanner that already works using Instascan and Vue.js libraries. Now what I want to do is to automatically post the scanned content to a php file and redirect to that php file after scanning, but I can't seem to pass the value. Here is my HTML code:
<div class="form-group" id="app">
<label v-for="scan in scans" class="disptext" style="font-size: 30px; top: 73%; left: 45%;">Welcome, </label>
<input v-for="scan in scans" :key="scan.date" :title="scan.content" class="form-control" id="qr_user" name="qr_user" placeholder="Scan User QR Code" :value="scan.content" style="width: auto; font-size: 30px; left: 37%; text-align: center; position: absolute; top: 80%; border: 0; background: transparent;">
<input type="hidden" name="qr" id="qr" :key="scan.date" />
</div>
I tried posting it through my js file like this:
mounted: function () {
var self = this;
self.scanner = new Instascan.Scanner({ video: document.getElementById('preview'), scanPeriod: 5 });
self.scanner.addListener('scan', function (content, image) {
self.scans.unshift({ date: +(Date.now()), content: content });
$.post("scanquery.php", {qr: content});
window.location.assign("scanquery.php");
});
But php executes first so "qr" is always undefined. How can I do this?
Edit
Here is the php code, I just posted it by calling the "qr":
$user = $_POST['qr'];
if(!empty($user)){
echo $user;
}
You can defer execution of window.location.assign() until after the post completes by using a callback in $.post:
$.post("scanquery.php", {qr: content}, () => {
window.location.assign("scanquery.php");
});
I think you have a mismatch in your payload types. $.post is formatting your object as JSON, and $_POST is not made available for JSON posts.
This source (https://davidwalsh.name/php-json) notes how to process incoming data as JSON:
# Get JSON as a string
$json_str = file_get_contents('php://input');
# Get as an object
$json_obj = json_decode($json_str);
Someone more of an expert on PHP can correct me on this part.
Related
I'm following through the PDF version on this URL: https://www.neodynamic.com/articles/Print-PDF-from-PHP-directly-to-default-printer-without-print-dialog/
I have managed to have it running. However, I noticed that it can only print one PDF file that is saved, using the $filePath = 'files/LoremIpsum.pdf'; under the PrintPDFController.php file. Is there a way of dynamically getting contents from a database that is output on say a table as follows:
<table id="WebClientPrint">
<tr><td>ONLY PRINT THIS PART AUTOMATICALLY</td></tr>
</table>
<input type="button" onclick="How to call Table ID i.e. WebClientPrint and the default printer" value="Print" />
This means that at button click, only the contents of the table should be printed out.
Hello I once used this type of printing and it helped me, only the window for choosing a printer will pop up.
function PrintDiv() {
var contents = document.getElementById("dvContents").innerHTML;
var frame1 = document.createElement('iframe');
frame1.name = "frame1";
frame1.style.position = "absolute";
frame1.style.top = "-1000000px";
document.body.appendChild(frame1);
var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
frameDoc.document.open();
frameDoc.document.write('<html><head><title>DIV Contents</title>');
frameDoc.document.write('</head><body>');
frameDoc.document.write(contents);
frameDoc.document.write('</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
document.body.removeChild(frame1);
}, 500);
return false;
}
Use it like this
<body>
<form id="form1">
<span style="font-size: 10pt; font-weight: bold; font-family: Arial">Sample code</span>
<hr />
<div id="dvContents" style="border: 1px dotted black; padding: 5px; width: 300px">
<span style="font-size: 10pt; font-weight: bold; font-family: Arial">Hello,
<br />
This is <span style="color: #18B5F0">Mateo</span>.<br />
Hoping that you are enjoying my articles!</span>
</div>
<br />
<input type="button" onclick="PrintDiv();" value="Print" />
</form>
</body>
I hope it helps you.
I'm currently developing a simple web page that enables the user to: upload an image and a corresponding caption to a DB, let the user view the images and delete them.
I have already accomplished the first two with the following code:
<?php
#include_once("connection.php");
$db = new mysqli("192.168.2.2", "root", "", "proyectoti");
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo "Información de servidor: ";
echo $db->host_info . "\n";
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); #$_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$sql = "INSERT INTO images (image, image_text) VALUES ('{$image}', '{$image_text}')";
// execute query
mysqli_query($db, $sql);
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
<!DOCTYPE html>
<html>
<head>
<title>Proyecto TI | Sube imágenes</title>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<h1>Proyecto TI | <a> Interfaz </a></h1>
<div id="content">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
#echo "<img src='images/".$row['image']."' >";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
<form method="POST" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea
id="text"
cols="40"
rows="4"
name="image_text"
placeholder="Di algo de esta imagen ^^"></textarea>
</div>
<div>
<button type="submit" name="upload">Publicar</button>
</div>
</form>
</div>
</body>
</html>
It looks like this:
Now, the only part I'm missing is being able to delete an image (basically I only echo each image), how would you suggest for me to accomplish this, to make each item clickable and let's say, pop up a dialog or button to perform an action (delete from DB).
I really don't know much about PHP or CSS/HTML, any help would be much appreciated, Thank you!
Within this loop:
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
#echo "<img src='images/".$row['image']."' >";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
Personally I would add an element to click on - like an 'x' or whatever - with a unique data attribute:
https://www.abeautifulsite.net/working-with-html5-data-attributes
You have to add the unique id of the image obviously, so you can let SQL know which row to delete... Like this:
echo "<div class='delete-image' data-id='" . $row['id'] . "'>x</div>';
Then I would link this class to an AJAX call to make an asynchronous request to the server and delete the image without reloading the page. It's not very hard.
An easier solution would be to create a new form in the loop, so you create multiple forms per image, add a hidden field with the image id in the form and make a submit button with the valeu 'delete' or simply 'x'.
The same way you created the check:
if (isset($_POST['upload'])) { ... }
You can create something like this:
if (isset($_POST['delete-image'])) { ... }
You will be carrying the image id value like a normal form input. And you can do whatever you want with it.
I would HIGHLY suggest you to look into how to work with jquery and ajax calls though.
Opening a dialogue and ask the user before he deletes an item will require that you either go another page for deletion or use javascript for this.
In both cases, you should somehow set an identifier for your image in your html-code.
I would suggest you give every image an id
'<img ... id="'.$yourImageId.'">'
or a data-attribute
'<img ... data-identifier="'.$yourImageId.'" >'
with that identifier.
First variant:
...
echo '<a href="/path/to/delete/view/page.php?image=yourImageId">'
echo '<img ... id="'.$yourImageId.'"/>'
echo '</a>'
...
and on this delete-view-page, you just have a form that triggers your delete-code
<form action="/path/to/delete/view/page.php" method="POST">
<input type="hidden" name="id" value="<?php echo $yourImageId ?>">
</form>
<!-- after this, react with $_POST['id'] --> to the id sent to the server side and delete the image in your database -->
The other way is not server side rendered.
You should give your Elements some class like "my-clickable-image".After that, you have a script on your page, that looks something like the following
<script>
/* get your images with querySelectorAll, the . stands for class and after that your name */
var clickables = document.querySelectorAll(".my-clickable-image");
clickables.foreach(function(image){
// say that for each image, when clicked the generated function is called image.addEventListener('click',generateShowDialogueFunc(image.getAttr("id")));
});
// generate a function(!) that reacts to an image being clicked
function generateShowDialogueFunc(imageIdentifier){
// return a function that adds a Pop Up to the page
// the Pop Up has approximately the code of the first options second page
// except that now, it must create and remove elements in javascript
return function createPopUp(){
removePopUp();
var popup = document.createElement("div");
popup.setAttribute("id","deletePopUp");
var deleteForm = document.createElement("form");
deleteForm.setAttr("action","/path/to/file/that/deletes/given/query.php?id="+imageIdentifier);
var deleteContents = '<p> Do you want to delete this image? </p>'
+ '<button type="submit"> yes </button>'
+ '<button onclick="removePopUp()"> no </button>'
deleteForm.innerHTML = deleteContents;
document.body.appendChild()
}
}
// remove the Pop Up that can be used to delete an image from the page
function removePopUp(){
var existingPopUp = document.getElementById("deletePopUp");
if(existingPopUp) document.body.removeChild(existingPopUp);
}
</script>
<!-- just add some styling to make the popup show on top of the page -->
<style>
#deletePopUp{
width: 50vw;
height: 50vh;
position: absolute;
z-index: 1;
padding: 1em;
}
</style>
In this case, you just call the server to delete the image, not to show the delete form.
I would suggest the second one but stack overflow is not made for opinion based answers.
Regarding simple security:
It looks like your users could give titles or texts to images.
try what happens if a user gives a title like <bold>some title</title>
and guess what would happen if the title is <script>window.location.href="google.com"</script>
(XSS * hint hint *)
Regarding code structure:
If you want to do something like web development more often, think about separating your database accessing code, and your logic code from your php page template code, this is called 3 tier architecture and standard for bigger projects but i guess this is really just a first, short prototype or test.
I want to create console.
I have textarea:
<textarea style="width: 100%; height: 300px; resize: none;" id="console_output" readonly></textarea>
And using this code to insert more text:
else echo "<script>$('#console_output').append('Some text.\n');</script>";
But nothing happened, textarea is empty.
Your code should work as you can check JsFiddle
$('#console_output').append('Some text.\n');
Will not work if
you are not into your else statement
textarea is not there yet if dynamically created
you have no jquery included
You can try with pure js:
echo '<script>document.getElementById("console_output").value += "Some text.\n";</script>';
How should I retrieve the uploaded file details from uploadify after the completion of the upload process.
I want to do a process in the uploaded file.
But when I use the uploadify it simply uploads the file to a location through the uploadify.php which I customized.
I want this uploadify process to redirect to a page after completed with the details of the file such as filename and the targeted location where I will proceed with my second operation on the file uploaded
Updates
This is what my code as of now
<style type="text/css">
body {
font: 0.8em/1.6em Arial, Helvetica, sans-serif;
}
fieldset {
width: 500px;
}
#sample {
display:table;
}
#sampleFile {
float: left;
display:table-cell;
margin-right: 15px;
}
#download {
margin-top: 15px;
display: table;
}
.dlImage {
display: table-cell;
float: left;
margin-right: 10px;
}
.dlText {
float: left;
display: table-cell;
}
.fileDetails {
color: red;
}
.releaseDate{
margin-top: -3px;
color: gray;
}
</style>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Uploadify scriptData Sample</title>
<link rel="stylesheet" href="uploadify/uploadify.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.uploadify.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#fileUpload").fileUpload({
'uploader': 'uploadify/uploader.swf',
'cancelImg': 'uploadify/cancel.png',
'script': 'uploadify/upload.php',
'folder': 'files',
'multi': false,
'displayData': 'speed',
'onComplete' : function(event, queueID, fileObj, reponse, data) {
location.href="complete.php";
}
});
});
</script>
</head>
<body>
<div id="sample">
<div id="sampleFile">
<fieldset style="border: 1px solid #CDCDCD; padding: 8px; padding-bottom:0px; margin: 8px 0">
<legend><strong>Sélectionner l'image à imprimer :</strong></legend>
<div id="fileUpload">You have a problem with your javascript</div>
Start Upload <p></p>
</fieldset>
</div>
</body>
</html>
on the second page I do want to echo the file name that is uploaded
I have there in the second page complete.php
<?php
print_r($_FILES);
echo $_FILES['type'];
echo $_FILES['tmp_name'];
echo $_FILES['name'];
echo $_FILES['size'];
?>
Do you know that you can get the filename, filpath inside the onComplete event like this:-
onComplete: function(event, queueID, fileObj, reponse, data)
{
alert fileObj.name; //The name of the uploaded file
alert fileObj.filePath; //The path on the server to the uploaded file
location.href= "complete.php?filename="+fileObj.name+"&filepath="+fileObj.filePath; //Here you can do a javascript redirect
}
Check the documentation for further details http://www.uploadify.com/documentation/events/oncomplete-2/
Are you looking for those values? If not let me know
Updates
As per your question updates, you have 2 options.
Either to do the "some process" after the file upload in the uploadify.php. You can see the file uploadify.php which comes with the uploadify plugin. There you have the $_FILES['Filedata'] array containing all the file info. You may do the post processing here itself (by calling a function better instead of writing lots of code in uploadify's core code)
in uploadify.php
$_FILES['Filedata']['name'] //file name
Or like I said, get the file name and path inside the onComplete event. Then pass these params like this :-
location.href= "complete.php?filename="+fileObj.name+"&filepath="+fileObj.filePath;
I think this is better. You may send an ajax request instead to do the entire process (file upload + your "some process") without loading the page again.
Write a $.post() request inside the onComplete event with those parameters and post to "complete.php"
Getting parameters inside onComplete which are not available by default
You have to use the response parameter available inside onComplete
I worked on uploadify version 2.1.0 so my solution will work for sure on that version.
If you want only one parameter, you can echo that at the end of uploadify.php
I did the following thing:-
In my uploadify.php changed (this was in the original uploadify.php):-
move_uploaded_file($tempFile,$targetFile);
echo "1";
to this:-
move_uploaded_file($tempFile,$targetFile);
echo $tempFile;
and then inside the onComplete event did an explode -
var tmpName = reponse;
If however, you want to get more than one parameter inside onComplete, this is a trick I can give (this is not a good approach, but I was not able to return multiple params by any other way - I tried returning json array etc.):-
move_uploaded_file($tempFile,$targetFile);
echo $param1.'%%__%%'.$param2;
and then inside the onComplete event did an explode -
var paramsArray = explode('%%__%%',reponse);
param1 = paramsArray[0];
param2 = paramsArray[1];
you can get all the details of the uploaded file by echoing below line;
print_r($_FIELS);
OR you can echo all the fields of uploded files.
echo $_FIELS['type'];
echo $_FIELS['tmp_name'];
echo $_FIELS['name'];
echo $_FIELS['size'];
i m right if i understood you what you want to saying. but please do comment if you searching for anything else.
Thanks.
can someone tell me how to create a nice small tooltip like ajax pop-up ?
the situation is like this,
I am pulling the $row->title from the db, and then I presented it as a link like this
<?php foreach($task->result() as $row): ?>
<tr>
<td><a href=#><?php echo $row->title; ?></a></td>
</tr>
<?php endforeach; ?>
when a random user clicks that link, I want it to produce a small pop-up or tooltip like stuff that contains the title's description $row->description , and when user moves mouse from it,it closes. i know its possible, but i just don't know how to do it.
You need jQuery. Add stylesheet into <head></head> and javascript to any place in your page.
Sample style:
<style type="text/css">
.description {
visible: hidden;
position: absolute;
left: 0px;
top: 0px;
/* View */
font-family: Arial,Tahoma,Verdana;
font-size: 8pt;
color: #bbb;
background-color: #444;
padding: 5px 7px;
border: 1px solid #222;
}
</style>
Javascript:
<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Add listener to links
$(".some_class").click(function(e) {
var description = $('<div class="description">'+ $(this).attr("description") +'</div>');
$(this).append(description);
description.css("left", e.pageX-4);
description.css("top", e.pageY-4);
description.animate({ opacity: 'toggle' }, 400, 'linear');
// Remove description, if user moved the mouse cursor out description
description.mouseout(function() {
$(this).remove();
});
return false;
});
});
</script>
Change your code:
<?php foreach($task->result() as $row): ?>
<tr>
<td><?php echo $row->title; ?></td>
</tr>
<?php endforeach; ?>
But the better way is to check out some good jQuery plugin..
Check out this jQuery plugin: http://www.w3avenue.com/2010/01/11/coda-bubble-jquery-plugin/
something like the following?
AJAX to get the description and when you're received the response create the description 'box'
var tipel = document.createElement('div');
tipel.innerHTML = descr;`
add it to the page
var bodyel = document.getElementsByTagName('body').item(0);
bodyel.appendChild(tipel);`
and position it like:
tipel.style.position = "absolute";
tipel.style.top = newfntogetabsolutecoord_top(document.getElementById("mytitleelement"));
tipel.style.left = newfntogetabsolutecoord_left(document.getElementById("mytitleelement"));`
getting absolute coords of an element can be tricky, look for a fn online.
for closing the tip, a suggestion would be placing tipel just under the mouse pointer (you already know it's over the link "mytitleelement", just shift the tip a little in the lines above), and then add an onmouseout event function to tipel that:
tipel.style.display = "none"; //hides or
tipel.parentNode.removeChild(tipel); //removes it from the page
(you might get away with using this instead of tipel in those 2 lines)