Bootstrap checkbox with Canvas - php

I am using library https://github.com/flatlogic/awesome-bootstrap-checkbox for adding pretty checkboxes/radiobuttons to my site and it looks well on it. But when I am trying to do a screenshot of a div block with html2canvas library, then I get some weird things on the generated image .
HTML code:
<div class="checkbox checkbox-warning checkbox-circle">
<input type="checkbox" id="checkbox5" class="test-checkbox" checked="checked">
<label for="checkbox5"></label>
</div>
JS code:
var element = $('#body-details');
html2canvas(element, {
onrendered: function(canvas) {
var img = canvas.toDataURL();
var url = $('#image-url').val();
$.post(url, {data: img}, function () {});
}
});
PHP code:
$data = Yii::$app->request->post('data');
$file = time() . '.jpg';
$dirPath = './' . Yii::$app->session->get('userFolder') . '/';
// remove "data:image/png;base64,"
$uri = substr($data, strpos($data, ",") + 1);
// save to file
if (!file_exists($dirPath)) {
mkdir($dirPath, 0777, true);
}
file_put_contents($dirPath . '/' . $file, base64_decode($uri));
Maybe there are other ways how to do screenshot of the div without canvas but I did not find them.
Thanks everyone in advance

There was only one solution that I found.
I have to remove bootstrap style from checkboxes before making screenshot with html2canvas. After screenshot was made and request was sent to server I set the style back. It is not so nice as it could be but I did not find any better solution.

Related

How to call an image alt by an onclick event using php?

I want to open a new page and transfer data from an array. Using the name of the image seemed like the easiest way so that's what i want to do.
on the page i want to call it
function meghiv($img)
{
$be=$img.alt;
echo $be;
session_start();
$_SESSION['kod'] = $be;
}
for($j=0;$j<4;$j++)
{
echo ' <img src="'.$nevek[$i].'.png" class="card-img-top " alt="'.$i.'" onclick="meghiv(this)"> ';
$i++;
}
on the new page
<?php
session_start();
echo $_SESSION['kod'];
?>
I don't know if it answers your question but try using javascript to load the image name into your php file
let images = document.querySelectorAll('.card-img-top'); // returns NodeList
let img_list = [...images]; // converts NodeList to Array
img_list.forEach(div => {
div.addEventListener("click", function(e){
e.preventDefault()
let alt = div.getAttribute("alt")
window.open(`https://link.here/?alt=${alt}`, "_blank");
})
});
Then in your php file
$image_name = $_GET['alt'];

How correctly refresh included PHP file?

I'm just a persistent beginner and I've met another obstacle in my way, so I hope that you'll help me one more time... :) I've got that HTML:
<div class='hold'><?php include 'image.php'; ?></div>
<div class='refresh'>Get new image</div>
And that PHP code:
<?php
$dir = 'images/';
$img = array();
if(is_dir($dir)) {
if($od = opendir($dir)) {
while(($file = readdir($od)) !== false) {
if(strtolower(strstr($file, '.'))==='.jpg') {
array_push($img, $file);
}
}
closedir($od);
}
}
$id = uniqid();
$smth = array_rand($img, 1);
echo '<img src=' . $dir.$img[$smth] . '?' . $id . ' width="200px" height="50px" />';
echo '<input type="hidden" value=' . $id . ' />';
?>
So now when I'm looking at my page I see in the <div class='hold'></div> my img from the folder images, and it's allright. BUT when I click on the <div class='refresh'></div> I obviously want to get another img from my folder, but I dunno how to accomplish that trick correctly.
I know that first answer will be USE AJAX, and I know that I can do something like
function loadGraphic() {
$('.hold').load('image.php');
};
loadGraphic();
and then $('.refresh').click(loadGraphic); but when I'm trying to do that in response from server I get TWO THINGS: image.php and, of course, something like car.jpg?573c4e010c7f6... But I very-very wanna get just ONE looking like
car.jpg?573c4e010c7f6
or
image.php?573c4e010c7f6 - I don't care...
So... I hope you've got my concept... maybe I'm asking for miracle - I dunno! Any, absolutely any help will be appreciated :)
Try it the following way:
JS function:
function loadGraphic() {
$.get("image.php", function(data) {
$(".hold").html(data);
});
};
Html:
<div class='refresh' onclick='loadGraphic()'>Get new image</div>

Pretty Photo load image via ajax frame

I have an angular app that will display some images. I am opening a prettyPhoto ajax window and passing the pathname to the URL. My script is loading the image fine, however, it isn't displaying the image how prettyPhoto traditionally displays a photo.
What do I need to do so it behaves like it is displaying a photo? i.e: has the fullscreen button, resizes the lightbox to the photo etc.
Is that even possible?
I am opening the lightbox via:
$scope.openLightbox = function()
{
if (typeof $.prettyPhoto.open !== "function")
{
$.fn.prettyPhoto({
social_tools:false,
deeplinking: false,
keyboard_shortcuts: false
});
$.prettyPhoto.open('resources/php/view/lightbox.php?ajax=true&path=' + $base64.encode($scope.currentFile));
return;
}
$.prettyPhoto.open('resources/php/view/lightbox.php?ajax=true&path=' + $base64.encode($scope.currentFile));
}
$scope.currentFile would be something like: data/39/my_image_name.jpg
and I am parsing the PHP like so:
$path = base64_decode($_GET['path']);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path);
$mimeExt = explode('/', $mime);
if ($mimeExt[0] == 'image')
{
echo '<img width="100%" height="100%" src="data:image/' . $mimeExt[1] . ';base64,' . base64_encode(file_get_contents($path)) . '">';
}
elseif ($mimeExt[0] == 'video')
{
}
finfo_close($finfo);
Like I said above, the image is displaying just fine, I just want it to be displayed with the standard prettyPhoto image behavior. I understand this may not be possible.
EDIT
So turns out I didn't need AJAX afterall:
$scope.openLightbox = function()
{
if (typeof $.prettyPhoto.open !== "function")
{
$.fn.prettyPhoto({
social_tools:false,
deeplinking: false,
keyboard_shortcuts: false
});
$.prettyPhoto.open('resources/php/view/lightbox.php?path=' + $base64.encode($scope.currentFile));
return;
}
$.prettyPhoto.open('resources/php/view/lightbox.php?path=' + $base64.encode($scope.currentFile));
}
and finally my php which I am outputting the image directly to the browser so prettyPhoto thinks it is just loading an image
<?php
require("../config.php");
require("../connect.php");
session_start();
if (isset($_SESSION['ds_level']))
{
$path = base64_decode($_GET['path']);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path);
$mimeExt = explode('/', $mime);
if ($mimeExt[0] == 'image')
{
header('Content-Type: image/' . $mimeExt[1]);
echo file_get_contents($path);
}
elseif ($mimeExt[0] == 'video')
{
//do other stuff to display video
}
finfo_close($finfo);
}
else
{
//-- no access
}
?>
What do I need to do so it behaves like it is displaying a photo? i.e: has the fullscreen button, resizes the lightbox to the photo etc.
Is that even possible?
Yes, it is possible. You need to create a dedicated directive, as specified in this Gist:
.directive('prettyp', function(){
return function(scope, element, attrs) {
$("[rel^='prettyPhoto']").prettyPhoto({deeplinking: false, social_tools: false});
}
})
To apply it, specify rel="prettyPhoto" in the anchor, like so:
<a prettyp ng-href="{{image.url}}" rel="prettyPhoto[main]" target="_blank" title="{{image.title}}">
HOW IT WORKS
The directive looks for a rel attribute starting with prettyPhoto, and applies the prettyPhoto magic to it.
EXAMPLE
I made a Plunk you can play around with: check the Plunk
IN YOUR CODE
To apply the directive in your code, you could replace:
echo '';
with:
echo '<img width="100%" height="100%" src="data:image/' . $mimeExt[1] . ';base64,' . base64_encode(file_get_contents($path)) . '">';
EDIT AFTER CHAT SESSION
As your images are protected with .htaccess, you have opted to work with a base64 version of your image, and why not?
However, it seems that if you wait until the user clicks the 'view' button in your app, it takes too long to go fetch the protected image and encode it, before passing it on to prettyPhoto:
I recommend you go fetch your image before the user clicks the view button, when the user selects the image in the list.
The long process of:
make an ajax call to php server;
have php app fetch image;
have php app encode image;
have angularjs/javaScript app store the base64 string
can then be done automatically, preventively, in the background.
The user experience would then be optimised.
So when the user does click the view button, the base64 version of the image can be passed to prettyPhoto straight away, without any server call: this would produce the same result as displayed in the plunkr I provided, when the button is pressed.

How to get specific content from cross-domain http request

There is a Dutch news website at: nu.nl
I am very interested in getting the first url headline which is resided over her:
<h3 class="hdtitle">
<a style="" onclick="NU.AT.internalLink(this, event);" xtclib="position1_article_1" href="/buitenland/2880252/griekse-hotels-ontruimd-bosbranden.html">
Griekse hotels ontruimd om bosbranden <img src="/images/i18n/nl/slideshow/bt_fotograaf.png" class="vidlinkicon" alt=""> </a>
</h3>
So my question is how do I get this url? Can I do this with Jquery? I would think not because it is not on my server. So maybe I would have to use PHP? Where do I start...?
Tested and working
Because http://www.nu.nl is not your site, you can do a cross-domain GET using the PHP proxy method, otherwise you will get this kind of error:
XMLHttpRequest cannot load http://www.nu.nl/. Origin
http://yourdomain.com is not allowed by Access-Control-Allow-Origin.
First of all use this file in your server at PHP side:
proxy.php (Updated)
<?php
if(isset($_GET['site'])){
$f = fopen($_GET['site'], 'r');
$html = '';
while (!feof($f)) {
$html .= fread($f, 24000);
}
fclose($f);
echo $html;
}
?>
Now, at javascript side using jQuery you can do the following:
(Just to know I am using prop(); cause I use jQuery 1.7.2 version. So, if you are using a version before 1.6.x, try attr(); instead)
$(function(){
var site = 'http://www.nu.nl';
$.get('proxy.php', { site:site }, function(data){
var href = $(data).find('.hdtitle').first().children(':first-child').prop('href');
var url = href.split('/');
href = href.replace(url[2], 'nu.nl');
// Put the 'href' inside your div as a link
$('#myDiv').html('' + href + '');
}, 'html');
});
As you can see, the request is in your domain but is a kind of tricky thing so you won't get the Access-Control-Allow-Origin error again!
Update
If you want to get all headlines href as you wrote in comments, you can do the following:
Just change jQuery code like this...
$(function(){
var site = 'http://www.nu.nl';
$.get('proxy.php', { site:site }, function(data){
// get all html headlines
headlines = $(data).find('.hdtitle');
// get 'href' attribute of each headline and put it inside div
headlines.map(function(elem, index){
href = $(this).children(':first-child').prop('href');
url = href.split('/');
href = href.replace(url[2], 'nu.nl');
$('#myDiv').append('' + href + '<br/>');
});
}, 'html');
});
and use updated proxy.php file (for both cases, 1 or all headlines).
Hope this helps :-)
You can use simplehtmldom library to get that link
Something like that
$html = file_get_html('website_link');
echo $html->getElementById("hdtitle")->childNodes(1)->getAttribute('href');
read more here
I would have suggested RSS, but unfortunately the headline you're looking for doesn't seem to appear there.
<?
$f = fopen('http://www.nu.nl', 'r');
$html = '';
while(strpos($html, 'position1_article_1') === FALSE)
$html .= fread($f, 24000);
fclose($f);
$pos = strpos($html, 'position1_article_1');
$urlleft = substr($html, $pos + 27);
$url = substr($urlleft, 0, strpos($urlleft, '"'));
echo 'http://www.nu.nl' . $url;
?>
Outputs: http://www.nu.nl/buitenland/2880252/griekse-hotels-ontruimd-bosbranden.html
Use cURL to retrieve the page. Then, use the following function to parse the string you've provided;
preg_match("/<a.*?href\=\"(.*?)\".*?>/is",$text,$matches);
The result URL will be in the $matches array.
If you want to set up a jQuery bot to scrape the page through a browser (Google Chrome extensions allow for this functionality):
// print out the found anchor link's href attribute
console.log($('.hdtitle').find('a').attr('href'));
If you want to use PHP, you'll need to scrape the page for this href link. Use libraries such as SimpleTest to accomplish this. The best way to periodically scrape is to link your PHP script to a cronjob as well.
SimpleTest: http://www.lastcraft.com/browser_documentation.php
cronjob: http://net.tutsplus.com/tutorials/php/managing-cron-jobs-with-php-2/
Good luck!

javascript return function's data as a file

I have a function in javascript called "dumpData" which I call from a button on an html page as **onlick="dumpData(dbControl);"* What it does is return an xml file of the settings (to an alert box right now). I want to return it to the user as a file download. Is there a way to create a button when click will open a file download box and ask the user to save or open it? (sorta of like right-clicking and save target as)...
Or can it be sent to a php file and use export();? Not sure how I would send a long string like that to php and have it simple send it back as a file download.
Dennis
I don't think you can do that with javascipt, at least not with a nice solution.
Here's how to force a download of a file in PHP:
$file = "myfile.xml";
header('Content-Type: application/xml');
header("Content-Disposition: attachment; filename='$file'");
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
Instead of using readfile to output your file, you could also directly display content using echo.
/EDIT: hell, someone was faster :).
EDITED:
just a proof of concept.. but you get the idea!
instead of
<a onlick="dumpData(dbControl); href="#">xml file</a>
you can have like this:
xml file
then like this:
// Assuming your js dumpData(dbControl); is doing the same thing,
// retrieve data from db!
$xml = mysql_query('SELECT * FROM xml WHERE id= $_GET['id'] ');
header("Content-type: text/xml");
echo $xml;
I eneded up going this route:
The HTML code
<script type="text/javascript">
$(document).ready(function() {
$("#save").click(function(e) { openDialog() } );
});
</script>
<button id="save" >Send for processing.</button>
The javascript code:
function openDialog() {
$("#addEditDialog").dialog("destroy");
$("#Name").val('');
$("#addEditDialog").dialog({
modal: true,
width: 600,
zIndex: 3999,
resizable: false,
buttons: {
"Done": function () {
var XMLname = $("#Name").val();
var XML = dumpXMLDocument(XMLname,geomInfo);
var filename = new Date().getTime();
$.get('sendTo.php?' + filename,{'XML':XML}, function() {
addListItem(XMLname, filename + ".XML");
});
$(this).dialog('close');
},
"Cancel": function () {
$("#Name").val('');
$(this).dialog('close');
//var XMLname = null;
}
}
});
}
PHP Code, I just decided to write the file out to a directory. Since I created the filename in the javascript and passed to PHP, I knew where it was and the filename, so I populated a side panel with a link to the file.
<?php
if(count($_GET)>0)
{
$keys = array_keys($_GET);
// first parameter is a timestamp so good enough for filename
$XMLFile = "./data/" . $keys[0] . ".kml";
echo $XMLFile;
$fh = fopen($XMLFile, 'w');
$XML = html_entity_decode($_GET["XML"]);
$XML = str_replace( '\"', '"', $XML );
fwrite($fh, $XML);
fclose($fh);
}
//echo "{'success':true}";
echo "XMLFile: ".$XMLFile;
?>
I don't know why, but when I send the XML to my php file it wrote out the contents withs escape charters on all qoutes and double quotes. So I had to do a str_replace to properly format the xml file. Anyone know why this happens?
POST the XML via a form to a php script that writes it back to the client with a Content-Disposition: attachment; filename=xxx.xml header.
<form name="xml_sender" action="i_return_what_i_was_posted.php" method="POST">
<input type="hidden" name="the_xml" value="" />
</form>
Then with js
function dumpData(arg) {
var parsedXML = ??? //whatever you do to get the xml
//assign it to the the_xml field of the form
document.forms["xml_sender"].the_xml.value = parsedXML;
//send it to the script
document.forms["xml_sender"].submit();
}
Can't remember if this loses the original window, if so, post to an iframe.

Categories