Lightweight Signature Pad With jQuery And Canvas - Drawpad - php

There is a brand new drawing pad (pen tool) plugin from Jquery found in that link:
https://www.jqueryscript.net/other/signature-draw-pad.html.
As it is new I cannot see how to transform it into image to save it to database with php.
I cannot find any explanation on how to use this plugin for that purpose.
Anyone has information on how to do that ?
Thank you !!

A little inspect/devtools shows that the doodle/image/drawing is stored in html canvas element.
You can get the content of html canvas element with toDataURL() function.
Here is MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
Example: var base64Image = $("#target canvas").get(0).toDataURL();
You can then post it (example: via ajax, via form post, etc) to your backend and store the base64 in database.
Here is example snippet
$(document).ready(function() {
// set background
var urlBackground = 'https://picsum.photos/id/100/500/400';
var imageBackground = new Image();
imageBackground.src = urlBackground;
//imageBackground.crossorigin = "anonymous";
imageBackground.setAttribute('crossorigin', 'anonymous');
$("#target").drawpad();
var contextCanvas = $("#target canvas").get(0).getContext('2d');
imageBackground.onload = function(){
contextCanvas.drawImage(imageBackground, 0, 0);
}
// post the base64 image to some endpoint
$("#saveToDatabase").click(function() {
var base64Image = $("#target canvas").get(0).toDataURL();
console.log(base64Image);
$("#outputBase64FormInput").val(base64Image);
$("#outputBase64").html(base64Image);
});
// form submit
$("#myform").submit(function() {
var base64Image = $("#target canvas").get(0).toDataURL();
console.log(base64Image);
$("#outputBase64FormInput").val(base64Image);
$("#outputBase64").html(base64Image);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.css" />
<style>
body {background-color:rgb(248, 255, 227)}
#target {
width:500px;
height:400px;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.js"></script>
</head>
<body>
<button id="saveToDatabase">Save Drawing</button>
<div id="target" class="drawpad-dashed"></div>
<div id="outputBase64"></div>
<form id='myform' method="POST">
value1 <input id='value1' name='myvalue1' />
value2 <input id='value2' name='myvalue2' />
<input type='hidden' id='outputBase64FormInput' name='mybase64image'>
<input type='submit'>
</form>
</body>
</html>
Edit:
the OP asked to add image in canvas (and also posted the image to endpoint)

Related

How to write JSONdata to the html element in phonegap application?

I am trying receive the JSON data using PhoneGap application. I am using server xampp php server. On this server I have server code api.php for receiving data from database. My laptop's IP address is 192.168.1.4 so the URL of this local server is http ://192.168.1.4/Experiements/webservices/api.php".
I am able to receive the data using
alert(JSON.stringify(response));
but I want to add this _email_id_ information to
<div id="email">Email_id< /div >
which is defined in index.html.
From my Android phone I want to just log in and and receive the email_id of that user. Please see the image of my database and and data receive on my phone using
alert(JSON.stringify(response)).
My server code is api.php
<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","1234");
mysql_select_db("demo");
if(isset($_GET['type']))
{
if($_GET['type']=="login"){
$username=$_GET['UserName'];
$Password=$_GET['Password'];
$query="Select * from registration where UserName='$username' and Password='$Password'";
$result=mysql_query($query);
$totalRows=mysql_num_rows($result);
if($totalRows>0){
$recipes=array();
while($recipe=mysql_fetch_array($result, MYSQL_ASSOC)){
$recipes[]=array('User'=>$recipe);
}
$output=json_encode(($recipes));
echo $output;
}
}
}
else{
echo "Invalid format";
}
My PhoneGap application code is in index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="format-detection" content="telephone=no"/>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<title> Database Application</title>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, width=device-width">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, target-densitydpi=medium-dpi, user-scalable=0" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
<script>
$(document).ready(function(){
$("#btnLogin").click(function(){
var userId = document.getElementById('id').value;
var userPassword = document.getElementById('password').value;
$.ajax({
url:"http://192.168.0.106/Experiements/webservices/api.php",
type:"GET",
dataType:"json",
data:{type:"login", UserName:userId,Password:userPassword},
ContentType:"application/json",
success: function(response){
alert(JSON.stringify(response));
console.log(JSON.stringify(response));
var userEmail = response[0].User.email; // Find the email from the JSON
var emailDiv = $("div#email"); // Find the div for email with jQuery selector
emailDiv.text(userEmail); // Put user's email as text to that div
},
error: function(err){
alert(JSON.stringify(err));
}
})
});
});
</script>
<script type="text/javascript">
document.addEventListener("deviceready",OnDeviceReady,false);
function OnDeviceReady(){
//alert("cordova is loaded");
}
</script>
</head>
<body>
User ID : <input type="text" id="id" name="user" />
User Password : <input type="text" id="password" name="password" />
<input type="button" id="btnLogin" name="btnLogin" value="Login"/>
<div id="email">Email_id</div>
</body>
</html>
DataBase: demo, user: root, password: 1234, table: registration
Screen shot of my phone:
So if I understood you correctly, what you want to do is to get the email_id from the response and put the content into the div called email.
What you need to do is to first get the user's email from the JSON object which is in your case Array with just one item. This first item of array again is Object which contains field called email which is exactly what we want. After that we need to locate the div from the DOM with jQuery element selector and insert the user's email in it. Example is found below.
var userEmail = response[0].User.email; // Find the email from the JSON
var emailDiv = $("div#email"); // Find the div for email with jQuery selector
emailDiv.text(userEmail); // Put user's email as text to that div

Saving tinymce textarea content to file

I have been trying to save tinymce editor textarea content to a .txt file for a while but without success yet.
This is my html file code:
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>TinyMCE example</title>
<meta name="description" content="HTML5 Basic template">
<meta name="author" content="R Dickinson">
<link rel="stylesheet" href="css/styles.css?v=1.0">
<script src="js/scripts.js"></script>
<script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
// General options
mode : "textareas",
});
</script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<header>
<h1>test tinymce save</h1>
</header>
<nav>
</nav>
<section>
<form method="post" action="test.php">
<p>
<textarea name="content" style="width:50%"></textarea>
<input type="submit" value="Save" />
</p>
</form>
</section>
<aside>
</aside>
<footer>
</footer>
</body>
</html>
Now test.php
<?php
/*
* test.php
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>test tiny mce</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 0.21" />
</head>
<body>
<?php
echo(stripslashes($_POST['content']));
?>
<?php
$file = "data.txt";
$fp = fopen($file, 'w');
$data =(stripslashes($_POST['content']));
fwrite($fp, $data);
fclose($fp);
?>
</body>
</html>
I'm grateful for helpful replies to fix this-many thanks :-)
Update
Following the first answer below I have added triggerSave as:
<script language="Javascript">
function submitForm() {
tinyMCE.triggerSave();
document.forms[0].submit();
}
</script>
and
<form method="post" action="test.php">
<p>
<textarea name="content" style="width:50%"></textarea>
<!--<input type="submit" value="Save" />-->
Submit Form
</p>
but still no success...More help gratefully received
UPDATE 2
Here is my jQuery TinyMCE version:
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample WebPage</title>
<meta name="description" content="HTML5 Basic template">
<meta name="author" content="R Dickinson-see sitepoint etc">
<link rel="stylesheet" href="css/styles.css?v=1.0">
<script src="js/scripts.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3");
</script>
<!-- Load jQuery build -->
<script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
mode : "textareas"
});
</script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<header>
<h1>Enter the main heading, usually the same as the title.</h1>
</header>
<nav>
</nav>
<section>
<!-- OF COURSE YOU NEED TO ADAPT ACTION TO WHAT PAGE YOU WANT TO LOAD WHEN HITTING "SAVE" -->
<form method="post" action="show.php">
<p>
<textarea name="content" cols="50" rows="15">This is some content that will be editable with TinyMCE.</textarea>
<input type="submit" value="Save" />
</p>
</form>
</section>
<aside>
</aside>
<footer>
</footer>
</body>
</html>
The question itself comes down to :
How to save HTML content of TinyMCE into a file.
Well, first of all, you need:
1) Get content of editor
2) Send this content to PHP script
3) Implement some function that would save that content into a file
Getting content
Make sure you are getting it the way it should work.
For example,
<script type="text/javascript">
window.onload = function(){
var btn = document.getElementById('SubmitBtn');
btn.onclick = function(){
//This MUST alert HTML content of editor.
alert( tinyMCE.activeEditor.getContent() );
}
}
</script>
<input type="button" id="SubmitBtn" value="Get HTML content"/>
Sending content to PHP script
All you need to do is to send value of the method tinyMCE.activeEditor.getContent() to PHP script.
Well, you should use Jquery-AJAX for that.
Assume that you included jquery.js into script tag in the head section, the next step would be sending JavaScript variable to PHP script
It would be similar to this one:
<script type="text/javascript">
$(function(){
var url = "path_to_your_php_script.php";
$("#SomeSubmitButton").click(function(){
//"content" will PHP variable
$.post(url, { "content" : tinyMCE.activeEditor.getContent() }, function(respond){
if ( respond == ){
alert('Content saved to file');
return;
} else {
//Error message assumed
alert(respond);
}
});
});
});
</script>
PHP script
Since we were sending "content" this one will be populated in $_POST superglobal
<?php
if ( isset($_POST['content']) ){
//This is what you want - HTML content from tinyMCE
//just treat this a string
if ( save_html_to_file($_POST['content'], '/some_file.html') ){
//Print 1 and exit script
die(1);
} else {
die('Couldnt write to stream');
}
}
/**
*
* #param string $content HTML content from TinyMCE editor
* #param string $path File you want to write into
* #return boolean TRUE on success
*/
function save_html_to_file($content, $path){
return (bool) file_put_contents($path, $content);
}
So after execution this you should get back alert with message of success.
You should update your TinyMCE instances before submitting your form. Use this javascript:
tinyMCE.triggerSave();
I usually put this in a function and call it on onsubmit event of form.
There is already different questions around this topic in Stackoverflow.

Passing Googlemap latitude and longitude as javascript to HTML form

Hi I am currently using GoogleMaps API v3 and I am trying to get the variables for the latitude and longitude and place them in a hidden form as html variables and pass them through a form to a php page. The latitude and longitude are printing out on my page as the span but I cant get them to print in the form.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<!-- google maps -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<!-- jquery -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<!-- jquery UI -->
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<!-- our javascript -->
<script type="text/javascript" src="gmaps.js"></script>
<link rel="stylesheet" type="text/css" href="style4.css" />
</head>
<body>
<input id='gmaps-input-address' type='text'/>
<div id='gmaps-error'></div>
<div id='gmaps-canvas'></div>
<br/>
<br/>
Latitude: <span id='gmaps-output-latitude'></span>
<br/>
Longitude: <span id='gmaps-output-longitude'></span>
<br/>
<script type="text/javascript">
function doSomething()
{
var lat = document.getElementById('#gmaps-output-latitude');
lat_element.value = google_maps_api_variable;
var lon = document.getElementById('#gmaps-output-longitude');
lon_element.value = google_maps_api_variable;
document.getElementById("lat").value=lat;
document.getElementById("lon").value=lon;
}
</script>
<form action="join.php" method="post" onSubmit="doSomething">
<input type="hidden" name="lat" id="lat"/>
<input type="hidden" name="lon" id="lon"/>
<input type="submit" value="Confirm Address"/>
</form>
</body>
</html>
In the Googlemaps API there is a javascript function which holds the latitude and longitude as follows:
function update_ui( address, latLng ) {
$('#gmaps-input-address').autocomplete("close");
$('#gmaps-input-address').val(address);
$('#gmaps-output-latitude').html(latLng.lat());
$('#gmaps-output-longitude').html(latLng.lng());
}
I am very green with Javascript and would really appreciate any help, I have searched other questions to get as far as I am but I am stuck here.
just add this after the code you already have(to work before the form submits as a click handler of the form submittal buon or something):
$('#lat').val($('#gmaps-output-latitude').html());
$('#lon').val($('#gmaps-output-longitude').html());
gmaps.js is your js which populates span in your html file. This should be happening through a callback function which i probably think is update_ui. This function might be populating the spans afterwards and your script for populating hidden fields might have already executed. So places the code for populating hidden fields after the callback function call or may be in update_ui itself.
so edit your update_ui function and add
$('#lat').val(latLng.lat());
$('#lon').val(latLng.lng());
these lines in the function body in end.

Pass global javascript variables to php

I have a index.php file where I have canvas game. This game is loaded from separate game.js file where I have variable: ballsCought. I want this wariable and name inputet to text input pass on click to another php file. my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Simple Canvas Game</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
function score(){
$('#score').fadeIn(1000);
$('#score').load("load_players.php");
};
setInterval(score , 1000);
var nam = $("#name").val();
$('#submit').keyup(function(e){
if(e.keyCode == 13){
$.post('upload_score.php','n=' +nam, 'score=' +ballsCought);
}
});
$('#submit').click(function(e){
$.post('upload_score.php','n=' +nam, 'score=' +ballsCought);
});
});
</script>
</head>
<script src="game.js"></script>
<body>
<canvas id="canvas" width="525" height="525"></canvas>
<br /><p><span id="points"></span><input type="text" id="name" placeholder="Name..."/><input type="submit" id="submit" value="Submit"/></p>
<br /><span id="score"></span>
</body>
</html>
But this post function is not working any idea? THank you...
Looks like your $.post method is not correct. If you want to pass data to the PHP page you need to use the JavaScript object notation like so:
$.post('upload_score.php', {n: nam, score: ballsCought});
You can read more about the various ways to call $.post from the jQuery Docs page
Now there could still be problems with your PHP page. You should use something like Firebug to see the Ajax request and any errors that might be returned.

google custom search can't work

Here is the test.html file code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-hans" xml:lang="zh-hans">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
</head>
<body>
<div class="fr_search">
<form action="cse.php" accept-charset="UTF-8" method="post"
id="search-theme-form">
<input type="text" maxlength="128" name="search_theme_form"
id="edit-search-theme-form-1" size="15" value="" class="form-text" />
<input type="image" name="submit" id="edit-submit"
class="form-submit" src="images/search_btn_top.gif" /></div>
</form>
</div>
</body>
</html>
I put the code which generated by the http://www.google.com/cse/manage/create?hl=en. The
"Sites to search" I entered that was http://stackoverflow.com. When I put the generated code into the cse.php. Then put the cse.php and test.html into my local php enviroment. When I entered the text "php" into the search textbox and click the search button. But there is no any result on my search result page. What's wrong with my steps and code? thank you.
Here is the cse.php file code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>test search</title>
</head>
<body>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'en'});
google.setOnLoadCallback(function()
{
var customSearchControl = new google.search.CustomSearchControl ('011247711644571852159:xe2ytn1hwsa');
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');
}, true);
</script>
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css"
type="text/css" />
<?php echo 'test'; ?>
</body>
</html>
I'm not sure where to start with your code, but with a fresh code snippet from the Custom Search code generator, you can pass a query string to the CustomSearchControl. With code borrowed from here, something like this should work:
<div id="cse">Loading…</div>
<script src="http://www.google.com/jsapi"></script>
<script>
// Extract user's query from the URL
function getQuery() {
var url = '' + window.location;
var queryStart = url.indexOf('?') + 1;
if (queryStart > 0) {
var parts = url.substr(queryStart).split('&');
for (var i = 0; i < parts.length; i++) {
if (parts[i].length > 2 && parts[i].substr(0, 2) == 'q=') {
return decodeURIComponent(parts[i].split('=')[1].replace(/\+/g, ' '));
}
}
}
return '';
}
google.load('search', '1', {language:'en' });
google.setOnLoadCallback(function() {
var cseControl = new google.search.CustomSearchControl('ID_GOES_HERE');
cseControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
cseControl.draw('cse');
// Execute a query based on the query string
cseControl.execute(getQuery());
}, true);
</script>
So, for example that would go in your cse.php page (although there's no PHP in there at this stage) and your initial page's form something like:
<form action="cse.php" method="get">
<input name="q"> <input type="submit">
</form>
Get rid of the http:// in the sites to search bit.

Categories