I want to save the screenshot to server when click on div on page. It's a few problems. I'm rookie. Please help.
1)The picture is being saved but also shown at the bottom of the page. just want to be saved.
2)This is the most important. page contains iframe and image files. my main goal is to take images of them. but I was not successful. please help.
my html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
<div id="mydiv">
here is iframe
</div>
<div>
bla bla bla
image
</div>
<script type="text/javascript" src="html2canvas.js"></script>
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var mydiv = document.getElementById('mydiv');
mydiv.style.cursor = 'pointer';
mydiv.onclick = function () {
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
// Get base64URL
var base64URL = canvas.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {image: base64URL},
success: function(data){
console.log('Upload successfully');
}
});
});
};
mydiv.onmouseover = function() {
this.style.backgroundColor = 'white';
};
mydiv.onmouseout = function() {
this.style.backgroundColor = '';
};
</script>
</body>
</html>
please edit the code for me. how it works the way I want.
ajaxfile.php I have no problem with this
<?php
$image = $_POST['image'];
$location = "upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
$filename = "screenshot_".uniqid().'.png';
$file = $location . $filename;
file_put_contents($file, $image_base64);
Related
As I asked here I would like to know how I could pass the data from a simple JS function to php, and log it there.
I found this answer and tried to follow it. This is my code right now (both in the same file)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getClientScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH)
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
<script type="text/javascript">
getScreenResolution();
</script>
</body>
</html>
<?php
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
if(isset($_POST['screenResolutionW'])) {
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH
."\r\n");
fclose($fh);
}
?>
However, this does not work.
I wouldn't know how to fix this, whenever I try to google this problem people use more advanced methods, that I wouldn't even know how to start with.
Edit: My PHP and HMTL are in the same file (index.php).
Edit 2: Removed old code for clarity.
This results in these error messages:
Notice: Undefined index: screenResolutionW in index.php on line 153
Notice: Undefined index: screenResolutionH in index.php on line 154
What you want to do with $.post is include your data like this:
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
where the first of the pair is the POST identifier (the ['screenResolutionW']) and the second of the pair is the variable value.
You will also want to change your POST identifiers to be quoted:
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
Otherwise, you will get a warning about constants. I have also corrected the spelling in these variables, to reflect what you're trying to write into your file.
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH ."\r\n");
EDIT
Part of the problem is that you never call the function to execute it. Here is your HTML with the additions I have suggested, plus calling the function:
EDIT TWO
Added an onload handler for the document:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
</body>
<script type="text/javascript">
$(function() {
getScreenResolution();
});
</script>
</html>
OTHER NOTES
You really should separate the PHP code and place it in a different file because when you run the page as it is now you should get one line logged that has no variables when the page initially runs, then one logged line when the JavaScript fires after the page loads.
Then once separated you should not run your PHP until you test for the existence of a variable, for example:
if(isset($_POST['screenResolutionW'])) {
// your code to write to the file here
}
EDIT THREE
I placed all of the JavaScript in the same script block in the head of the file and have tested again:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$(function() {
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("post_test.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
getScreenResolution();
});
</script>
</head>
<body>
</body>
</html>
Here you can see the variables are being posted:
Adapting the others answers.
try it:
function getScreenResolution() {
"http://example.com/index.php", screenResolutionW + screenResolutionH
$.ajax({
url: '/index.php',
method: 'POST',
data: {
screenResolutionW : screen.width,
screenResolutionH : screen.height
},
success: function(data) { console.log(data); }
});
}
And in your PHP
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
echo $screenResolutionW . " - " . $screenResolutionH;
you have to use serialize the array before doing post request.
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
var serializedArr = {
width: screenResolutionW,
height: screenResolutionH
};
$.post('/index.php', serializedArr, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
In the server end, you will get values in $_POST variable.
Apart of all those mistakes you have discovered thanks to other replies, you have these:
$screenResoltuionW = ...
Notice you wrote "ltuion" and in the fopen command you have it correct. screenResolutionW
Same thing with $screenResoltuionH...
That's why you don't get any value in the file, because those variables doesn't exists.
I am new to PHP-PDO and need some assistance. My application routes all controllers to the index.php though a routes.php file. For example, when my sign-up form is submitted the form is handled action=index.php?controller=signup&action=createuser. The routes.php computes this creates a new signupcontroller($_POST) object and calls createuser(). Once the user is created a welcome page is required_once, which, with javascript, I build a grid of check-boxes. After the check-boxes are built with jquery onchange that makes a ajax call, or supposed to create an ajax, but does not work.
The url is suppose to send params with it to change the controller and action in order to call an appropriate function, and store the check-box option. However, when I check the box nothing happens.
ajax call:
$('#interests').on('change', 'input', function (e){
e.preventDefault();
var str = $('#interests').serialize();
$.ajax({
type: 'POST',
url: 'index.php?controller=interest&action=set_user_interest',
async: true,
traditional: true,
data: str,
success: function (msg) {
console.log(msg);
}
});
});
routes.php
function call($controller, $action){
require_once('controllers/' . $controller . '_controller.php');
// create a new instance of the needed controller
switch($controller) {
case 'interest':
require_once 'models/interest.php';
$controller = new InterestController();
}
// call the action
$controller->{ $action }();
}
// just a list of the controllers we have and their actions
// we consider those "allowed" values
$controllers = array(
'interest'=>['set_user_interest', 'error']
);
// check that the requested controller and action are both allowed
// if someone tries to access something else he will be redirected to the error action of the pages controller
if (array_key_exists($controller, $controllers)) {
if (in_array($action, $controllers[$controller])) {
call($controller, $action);
} else {
call('landing', 'error');
}
} else {
call('landing', 'error');
}
index.php
<?php
session_start();
require_once('greenCupOfWater.inc');
if (isset($_GET['controller']) && isset($_GET['action'])) {
$controller = $_GET['controller'];
$action = $_GET['action'];
} else {
$controller = 'landing';
$action = 'landing_page';
}
require_once 'views/layout.php';
?>
layout.php
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1">
<title>Witit</title>
<link rel="icon" type="image/png" sizes="32x32" href="../images/icons/favicon-32x32.png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link href="https://fonts.googleapis.com/css?family=Work+Sans:100" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="stylesheets/master.css">
<link rel="stylesheet" href="stylesheets/welcome.css">
<link rel="stylesheet" href='stylesheets/<?php echo $controller ?>.css'>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<?php include 'routes.php'; ?>
<script src="scripts/main.js" charset="utf-8"></script>
<script src="scripts/modalHelper.js" charset="utf-8"></script>
</body>
</html>
javascript files:
function build_interest(it, src){
var intrst = it;
var htag = it+"-header";
//var chng = 'this.form.submit()';
var ctr = document.createElement('div');
ctr.setAttribute('class', 'interest_container');
var lbl = document.createElement('label');
lbl.setAttribute('for', intrst);
var img = document.createElement('img');
img.setAttribute('src', src);
var title = document.createElement('h2');
title.setAttribute('id', htag);
var inp_f =document.createElement('input');
inp_f.setAttribute('type', 'hidden');
inp_f.setAttribute('name', intrst);
inp_f.setAttribute('value', 0);
var inp = document.createElement('input');
inp.setAttribute('type', 'checkbox');
inp.setAttribute('id', intrst);
inp.setAttribute('name', intrst);
inp.setAttribute('value', 1);
lbl.appendChild(img);
ctr.appendChild(lbl);
ctr.appendChild(inp_f);
ctr.appendChild(inp);
ctr.appendChild(title);
var elem = document.getElementById('interests');
elem.appendChild(ctr);
document.getElementById(htag).innerHTML = it;
}
function myFunc(obj) {
var num = 0;
for (var src in obj) {
if ((obj.hasOwnProperty(src))&&(obj[num].Interests_Pix!==null)) {
build_interest(obj[num].Interests, obj[num].Interests_Pix);
}
++num;
}
}
The following code should add 100 to an existing number in a mysql table if the button gets clicked. If I click the button nothing happens, but if I reload the page the function adds 100 to the number. What is wrong with my code?
<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '123');
define('DBNAME', 'dbtest');
$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">
</head>
<body>
<a id="button" class="waves-effect btn deep-orange darken-1">Button 1</a>
</body>
<script>
$("#button").click(function(){
<?php
mysql_query("UPDATE users SET test = (test + 100) WHERE userId=1");
?>
});
</script>
</html>
You cant call PHP code from a jQuery function like that. All the php runs when the page loads and thats it. You can however use jQuery and Ajax to send a message to a php script that processes that message then returns a response. The script can even be in the same actual file like you have (or in a different file altogether) something like this would do:
<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '123');
define('DBNAME', 'dbtest');
$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);
if(isset($_POST['updateTest']){
$val = $_POST['test'];
$id + $_POST['userId'];
// validate inputs and such....
mysql_query("UPDATE users SET test = (test + 100) WHERE userId=1");
// send success or error response...
echo json_encode(['success'=>true]);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">
</head>
<body>
<a id="button" class="waves-effect btn deep-orange darken-1">Button 1</a>
</body>
<script>
$("#button").click(function(){
var count = 100;
var userId = 1;
var dataObject= {updateTest: true, test: 100, userId: 1};
$.ajax({
type: "POST",
// url: "page.php", // add this line to send to some page other than the this one
data: dataObject,
success: function(response) {
if(response.success){
alert('test worked');
}
else{
alert('there was an error')
}
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
});
</script>
</html>
As mentioned by the previous poster PHP is server side and Javascript client side so what is actually happening is the following.
When the page is returned back to the user your piece of javascript just looks like the below..
Your MySQL statement here has executed already it can not interact with client side code in this way
<script>
$("#button").click(function(){
// nothing here.. But your MYSQL statement has executed anyway
});
</script>
I am very new to javascript (jquery/json) I have written this code to render a chart of CanvasJS with a php/json data fetching script along with it.
However the chart won't show, when I implement my code in to it. When I used Console.log() in web browser to find the ReferenceError it says: Can't find variable: $ ...Chart.html:11
I have tried many things and I have read many [duplicate] question/answers saying that I didn't load the Jquery Library and a bunch of other options. I have tried implementing this line:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
And I have tried many variables, but I don't think I understand what I can use more in these two codes I have..
Any point into the right direction would be great.
Chart.html
<!DOCTYPE HTML>
<html>
<script type="text/javascript" src="canvasjs.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<head>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var dataPoints = [];
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
In the above code, it concerns this part:
$(document).ready(function () {
and my php for the JSON data fetching: data.php
<?php
//header('Content-Type: application/json');
$con = mysqli_connect("localhost","root","","WebApplication");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}
else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM info");
while($row = mysqli_fetch_array($result))
{
$point = array("x" => $row['id'] , "y" => $row['acceleration']);
array_push($data_points, $point);
}
$json = json_encode($data_points, 32); //define('JSON_NUMERIC_CHECK',32); // Since PHP 5.3.3
$json = str_replace("\"", "", $json); //replace all the "" with nothing
echo $json;
}
mysqli_close($con);
?>
I know that the stack overflow community always require more info, but for god sake, I don't know anymore, and I really want to learn this.
EDIT-1:
This is what I have know, yet no result.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<script type="text/javascript" src="canvasjs.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var dataPoints = [];
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
EDIT-2:DEFAULT CODE, WHICH WORKS:
This is the default code that doesn't use my data.php code and uses randomized data points as data-source. It's from Canvasjs and it works fine.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:600px;">
</div>
</body>
</html>
It looks like jQuery is being loaded after canvasJS. If Canvasjs needs to use jQuery, it will need to have jQuery loaded first. Try switching those lines so jQuery is loaded on top, and it will probably fix your error.
EDIT: Actually, it seems that the CDN that hosts your jQuery doesn't use $ as the name of your main jQuery object. If you change $ to "jQuery" that error should be resolved. For example:
$(document).ready
would become:
jQuery(document).ready
same with $.getJson
It looks like Jquery isn't being loaded properly, and I'm thinking it's because of your unconventional practice of including the external scripts directly after the element. Try moving them down to just before your own script, inside the head.
Edit: the post was updated and apparently this didn't help.
SOLVED IT
First include this line:
than include this line: BELOW the code, not above it.
Than go to my data.php and comment (or delete) this line: //$json = str_replace("\"", "", $json); //replace all the "" with nothing
why u ask? Well because CanvasJS requires Strings and not separate characters/integrers.
So that the output will be:
[{"x":"1","y":"5"},{"x":"2","y":"5"},{"x":"3","y":"4"},{"x":"4","y":"1"},{"x":"5","y":"8"},{"x":"6","y":"9"},{"x":"7","y":"5"},{"x":"8","y":"6"},{"x":"9","y":"4"},{"x":"10","y":"7"},{"x":"14","y":"7"},{"x":"15","y":"7"}]
Instead of:
[{x:1,y:5},{x:2,y:5},{x:3,y:4},{x:4,y:1},{x:5,y:8},{x:6,y:9}...etc.
I've searched most of the forums and can't find what I am looking for. I want to do the following:
XML file:
<vaardigheden>
<vaardigheid soort="techniek">HTML/CSS</vaardigheid>
<vaardigheid soort="techniek">PHP/MySQL</vaardigheid>
<vaardigheid soort="techniek">Javascript</vaardigheid>
<vaardigheid soort="Instrument">Drums</vaardigheid>
<vaardigheid soort="Instrument">Gitaar</vaardigheid>
</vaardigheden>
I would like to loop through the attributes and elements and get this result:
Techniek
HTML/CSS
PHP/MySQL
Javascript
Instrument
Drums
Guitar
Does anyone have an idea how to achieve this? Just need the basic understanding of looping through attributes and elements in this way with jQuery.
DEMO
Using parseXML and each - NOTE the script will work on either a string as here or an ajaxed file.
var xml = '<vaardigheden> <vaardigheid soort="techniek">HTML/CSS</vaardigheid> <vaardigheid soort="techniek">PHP/MySQL</vaardigheid><vaardigheid soort="techniek">Javascript</vaardigheid><vaardigheid soort="Instrument">Drums</vaardigheid><vaardigheid soort="Instrument">Gitaar</vaardigheid></vaardigheden>',
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$vaardigheden = $xml.find( "vaardigheid" );
var currentSoort = "", content = $("#content");
$.each($vaardigheden,function(i,item) {
var soort = $(this).attr('soort');
if (soort != currentSoort) {
content.append("<dt>"+soort+"</dt>");
currentSoort = soort;
}
content.append("<dd>"+$(this).text()+"</dd>");
});
Hope this helps :)
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>XML JQUERY Example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function(){
function parseXml(xml)
{
var titles = [];
var newL ;
$(xml).find("vaardigheid").each(function()
{
if (jQuery.inArray($(this).attr("soort"), titles)==-1){//append new title
newL = '<label>'+$(this).attr("soort")+'</label><br/>';
var newList = '<ul id="' + $(this).attr("soort") + '" \><li>'+$(this).text()+'</li></ul>';
$("#output").append($(newL));
$("#output").append($(newList));
titles.push($(this).attr("soort"));
}
else{
var newItem = '<li>'+$(this).text()+'</li>';
$("#"+$(this).attr("soort")).append($(newItem));
}
});
}
$.ajax({
type: "GET",
url: "myFile.xml",
dataType: "xml",
success: parseXml
});
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>