html2 canvas unable to click button - javascript

I am unable to click the approve button to save the signature into database. .Please help! I have refer to this link to do but they are not working.
https://www.aspsnippets.com/Articles/Convert-Export-HTML-DIV-or-Table-to-Image-using-HTML-Canvas-in-ASPNet-using-C-and-VBNet.aspx
Code under approve button
<asp:Button ID="ProcesssOwner1" Visible="true" data-action="save" Text="Approve" CssClass="btn btn-success btn-sm" UseSubmitBehavior="false" OnClientClick="return ConvertToImage(this)" runat="server" OnClick="ProcesssOwner1_Click" />
Javascript
<script type="text/javascript">
function ConvertToImage(ProcesssOwner1) {
if (signaturePad.isEmpty()) {
alert("Please provide signature first.");
return false;
} else {
//document.getElementById("hfSign").value = signaturePad.toDataURL();
html2canvas($("#drawing")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(ProcesssOwner1.name, "");
});
return false;
}
}
</script>
Code under button click
Here I tried to save the signature in the path and folder.
protected void ProcesssOwner1_Click(object sender, EventArgs e)
{
if (Session["loggedUserID"] == null && Session["loggedRoleID"] == null)
{
Response.Redirect("Login.aspx");
}
else
{
int loggedUserID = Convert.ToInt32(Session["loggedUserID"]);
List<BOL.UserInfo> userslist = new UserInfos().List();
BOL.UserInfo loggeduser = userslist.Where(x => x.UserID == loggedUserID).FirstOrDefault();
string app_type = "";
string dcr = Request.QueryString["r_id"].Replace("/", "_") + DateTime.Now.ToString("yyyy-MM-dd HHmmtt");
string myID = loggeduser.EmployeeNo;
string path1 = "/Web/";
//System.Diagnostics.Debugger.Launch();
if (Request.QueryString["STAT"] == "S_7")
{
app_type = "A";
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
//write the bytes to file:
File.WriteAllBytes(path1 + dcr + "_" + myID + app_type + ".jpg", bytes); //write to a temp location.
File.Copy(path1 + dcr + "_" + myID + app_type + ".jpg", #"D:\IntranetPortal\IntranetPortal\Web\signature\" + dcr + "_" + myID + app_type + ".jpg");//here we grab the file and copy it. //EDIT: based on permissions you might be able to write directly to the share instead of a temp folder first.
}
else if (Request.QueryString["STAT"] == "S_9")
{
app_type = "C";
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
//write the bytes to file:
File.WriteAllBytes(path1 + dcr + "_" + myID + app_type + ".jpg", bytes); //write to a temp location.
File.Copy(path1 + dcr + "_" + myID + app_type + ".jpg", #"D:\IntranetPortal\IntranetPortal\Web\signature\" + dcr + "_" + myID + app_type + ".jpg");//here we grab the file and copy it.
}
DAL.DMSS insertdata = new DMSS();
insertdata.APP_PROCESS(Request.QueryString["r_id"], app_type, chatt.Text, path1 + "signature" + "/" + dcr + "_" + myID + app_type + ".jpg", dcr + "_" + myID + app_type + ".jpg", loggeduser.EmployeeNo, DATEE.Text);
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Approved.Thank you.');window.location ='Dms_app.aspx';", true);
}
}

Related

Hosted Website loads with errors in <body> that are not in the code

Ahoi,
I am hosting a small debug-website with my "Olimex ESP-32 POE". The goal is to send some internal data via JSON there to not have to use the Serial-Output from the Arduino IDE (The reasons behind that do not matter).
#include "Arduino.h"
#include <WiFiClient.h>
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
#include <string>
const char* ssid = "SSID";
const char* password = "password";
int looper = 0;
int looperSpeed = 0;
int looperMode = 0;
int looperDestination = 0;
int looperETC = 0;
WebServer webserver(80);
void initWebServer();
void getSettings() {
String response = "{";
response+= "\"speed\": \""+(String) looperSpeed+"\"";
response+= ",\"mode\": \""+(String) looperMode+"\"";
response+= ",\"dest\": \""+(String) looperDestination+"\"";
response+= ",\"etc\": \""+(String) looperETC+"\"";
if (webserver.arg("signalStrength")== "true"){
response+= ",\"signalStrengh\": \""+String(WiFi.RSSI())+"\"";
}
response+="}";
webserver.send(200, "text/json", response);
}
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += webserver.uri();
message += "\nMethod: ";
message += (webserver.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += webserver.args();
message += "\n";
for (uint8_t i = 0; i < webserver.args(); i++) {
message += " " + webserver.argName(i) + ": " + webserver.arg(i) + "\n";
}
webserver.send(404, "text/plain", message);
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
initWebServer();
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Set not found response
webserver.onNotFound(handleNotFound);
// Start server
webserver.begin();
Serial.println("HTTP server started");
}
void loop() {
webserver.handleClient();
//Some test values are changed here periodically (looperXYZ)
}
}
And the part which creates the website:
std::string online_output = "Test";
const char* serverIndex() {
const char* o = online_output.c_str();
const char* r =
(std::string("") +
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>" +
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>" +
"<input type='file' name='update'>" +
"<input type='submit' value='Update'>" +
"</form>" +
"<div id='prg'>Progress: 0%</div>" +
"<div id='output' style=\"font-family: monospace; border: 1px solid black; width: 350px;min-height:398px;\">" +
"</div>" +
"<script>" +
"var id = 0;" +
"var removeId = 0;" +
"setInterval(function(){" +
/*"var xhReq = new XMLHttpRequest();" +
"xhReq.open('GET', '/JSON', false);" +
"xhReq.send(null);" +
"var jsonObject = JSON.parse(xhReq.responseText);" +*/
"var data = {};" +
"$.ajax({" +
"type: 'GET'," +
"url: '/JSON'," +
"data: data," +
"async: true," +
"beforeSend: function (xhr) {" +
"if (xhr && xhr.overrideMimeType) {" +
"xhr.overrideMimeType('application/json;charset=utf-8');" +
"}" +
"}," +
"dataType: 'json'," +
"success: function (data) {" +
"document.getElementById('output').innerHTML = \"<p id=\" + id + \" style='margin:0;padding:0px;'>\" + \"Mode: \" + fill(data.mode,2) + \" | Speed: \" + fill(data.speed,4) + \" | Dest: \" + fill(data.dest,4) + \" | ETC: \" + fill(data.etc,5) + \"</p>\" + document.getElementById('output').innerHTML;" +
// "if (document.getElementById('output').offsetHeight > 400) document.getElementById('output').innerHTML = \"<p style='margin:0;padding:0px;'>\" + data.name + \"</p>\";" +
"if (document.getElementById('output').offsetHeight > 400) { document.getElementById(removeId).remove(); removeId++;}" +
"id++;" +
"console.log(data);" +
"}" +
"});" +
"}, 50);" +
"function fill(n,m) { " +
"var pre=\"\";" +
"var dec=10;" +
"for(var i=1;i<m;i++) { if(n<dec) { pre+=\".\"; } dec*=10; }" +
"pre = pre + n;" +
"return pre; }" +
"$('form').submit(function(e){" +
"e.preventDefault();" +
"var form = $('#upload_form')[0];" +
"var data = new FormData(form);" +
" $.ajax({" +
"url: '/update'," +
"type: 'POST'," +
"data: data," +
"contentType: false," +
"processData:false," +
"xhr: function() {" +
"var xhr = new window.XMLHttpRequest();" +
"xhr.upload.addEventListener('progress', function(evt) {" +
"if (evt.lengthComputable) {" +
"var per = evt.loaded / evt.total;" +
"$('#prg').html('progress: ' + Math.round(per*100) + '%');" +
"}" +
"}, false);" +
"return xhr;" +
"}," +
"success:function(d, s) {" +
"console.log('success!')" +
"}," +
"error: function (a, b, c) {" +
"}" +
"});" +
"});" +
"</script>").c_str();
return r;
}
const char* host = "esp32";
void initWebServer() {
if (!MDNS.begin(host)) { //http://esp32.local
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
/*return index page which is stored in serverIndex */
webserver.on("/", HTTP_GET, []() {
webserver.sendHeader("Connection", "close");
webserver.send(200, "text/html", serverIndex());
});
webserver.on("/JSON", HTTP_GET, []() {
getSettings();
});
/*handling uploading firmware file */
webserver.on("/update", HTTP_POST, []() {
webserver.sendHeader("Connection", "close");
webserver.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
}, []() {
HTTPUpload& upload = webserver.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %s\n", upload.filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
Update.printError(Serial);
}
}
});
webserver.begin();
}
This is testing code, so there might be left-overs from previous tests - FYI.
When loading the website (currently I am using Chrome) it sometimes works, sometimes nothing is loaded (THIS SITE IS NOT WORKING, and then an empty page) and sometimes I get a result like: xV­ºùÿý?øÿý?;"> which is the only output on the screen.
In detail it shows the following:
<html><head></head><body>xV­ºùÿý?øÿý?;"><script>var id = 0; [...the rest of the <script> part is loaded properly...]
I just noticed that in front of these strange characters are 364 centered points (·) but I cannot actually copy them, no editor is displaying them besides the Chrome->Inspect->"Sources"-Tab.
So basically the body is broken and these characters appear, they also do not change currently.
Can someone point me into a direction to solve this on my own, so that the website is always correctly loaded or knows what the error is?
The error seems to be on the following line:
const char* r = (std::string("") + “...”).c_str();
You are creating and std::string which allocates the raw c string on the heap. You then get the c representation of the string with .c_str(). The issue is that the string is freed since you have not assigned the string to a variable of type std::string. As a result, you were accessing memory that was not yours. When its memory wasn’t yet reused, it worked, but want is was reused by another program, it failed since you got basically random bytes from memory.
You can solve the issue by adding the following:
auto my_str = std::string("") + “...”;
Because you don’t need the raw pointer.
For the server index function, it should look like:
std::string serverIndex() {
For your init web server function:
webserver.on("/", HTTP_GET, []() {
webserver.sendHeader("Connection", "close");
auto r = serverIndex();
webserver.send(200, "text/html", r.c_str());
});
Disclaimer: this code wasn’t tested as it was only written in the app.

Select local files with input type:file (pdf) and convert them to base64 string

how to get base64 string from selected files with input type: file (multiple .pdf) in javascript.
I need a base64 string in a variable.
function handleFileSelect(e) {
console.dir(e);
if (!e.target.files) return;
selDiv.innerHTML = "";
var files = e.target.files;
for (var i = 0; i < files.length; i++) {
var base64;
var fileToLoad = document.getElementById("files").files[i]
var fileReader = new FileReader();
fileReader.onload = function (fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
console.log(base64);
};
fileReader.readAsDataURL(fileToLoad);
var f = files[i];
var TmpPath = URL.createObjectURL(e.target.files[i]);
var name = f.name;
var extencion = f.name.split('.')[1];
selDiv.innerHTML += f.name + " <a href='#' onclick=verdetalle(" + i + ",'" + extencion + "','" + name + "','" + base64 + "','" + TmpPath + "')>Ver Detalle</a>" + "<br/>";
}
}
but I do not respect the value for my base64 variable, only if I debuge it from the browser.
in this line of my code I create a link for each selected file, where I assign an onchange and pass the variables i, extension, name, base64, TmpPath, but I am missing the base64 variable
selDiv.innerHTML += f.name + " <a href='#' onclick=verdetalle(" + i + ",'" + extencion + "','" + name + "','" + base64 + "','" + TmpPath + "')>Ver Detalle</a>" + "<br/>";
Try below code snippet,
var base64String;
function handleFileSelect(callback) {
var file = document.getElementById('filePicker').files[0];
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
base64String = btoa(binaryString);
// alert(base64String);
// Do additional stuff
callback(base64String);
};
reader.readAsBinaryString(file);
};
<div>
<div>
<label for="filePicker">Choose file:</label><br>
<input type="file" id="filePicker" onchange="handleFileSelect(function(base64String){alert(base64String)})">
</div>
<br>
</div>
You need to put the functionality that depends on base64 inside the filereader.onload callback. Also, make sure to always use const or let when dealing with asynchronous loops. var gets hoisted and has function scope, not block scope, so it's easy to run into problems if you use it. Or, even better, use forEach, which gives you better abstraction, doesn't require manual iteration, and has function scope:
function handleFileSelect(e) {
console.dir(e);
const files = e.target.files;
if (!files) return;
selDiv.innerHTML = "";
files.forEach((file, i) => {
const { name } = file;
const extencion = f.name.split('.')[1];
const fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
const base64 = fileLoadedEvent.target.result;
console.log(base64);
const TmpPath = URL.createObjectURL(file);
selDiv.innerHTML += f.name + " <a href='#' onclick=verdetalle(" + i + ",'" + extencion + "','" + name + "','" + base64 + "','" + TmpPath + "')>Ver Detalle</a>" + "<br/>";
};
fileReader.readAsDataURL(file);
});
}

How do I hyperlink JSON API return values with variable URL addresses?

I have an HTML/CSS search bar where people can type a keyword and, on click, my Open States JSON API code returns New Jersey state bills that match that keyword.
Search Bar Screenshot
Screenshot of a Result
I want the bill titles that are returned to be hyperlinked to their page on the New Jersey state legislature site, but I can only find instructions for how to hyperlink a return with a static site.
Here is my JavaScript code so far (with API key removed):
e.preventDefault();
// console.log($("#billID").val());
var billSearchValue = $("#billID").val();
if(billSearchValue=='')
{
alert("Enter Desired Query Parameters");
} else{
// console.log(billSearchValue);
}
var searchQuery = "&q=" + billSearchValue;
var baseUrl = "http://openstates.org/api/v1/bills/?state=nj";
var apiKey = "";
var apiKeyParam = "&apikey=";
var apiKeyParams = apiKeyParam + apiKey;
var urlJSON = baseUrl + searchQuery + apiKeyParam + apiKey;
// console.log(urlJSON);
$.getJSON(urlJSON, function (data) {
var billsVar = [];
$.each(data, function(key, val) {
billsVar.push(val);
});
for (var i = 0; i < billsVar.length; i++) {
var billList = "<li>Bill <ul class=\"ul-sub\">"
var billTitle = "<li><strong>Bill Title</strong>: " + billsVar[i]['title'] + "</li>";
var billCreatedAt = "<li><strong>Bill Created</strong>: " + billsVar[i]['created_at'] + "</li>";
var billUpdatedAt = "<li><strong>Bill Updated</strong>: " + billsVar[i]['updated_at'] + "</li>";
var billID = "<li><strong>ID</strong>: " + billsVar[i]['id'] + "</li>";
var billChamber = "<li><strong>Bill Chamber</strong>: " + billsVar[i]['chamber'] + "</li>";
var billState = "<li><strong>Bill State (Probably Don't Want/Need This)</strong>: " + billsVar[i]['state'] + "</li>";
var billSession = "<li><strong>Bill Session</strong>: " + billsVar[i]['session'] + "</li>";
var billType = "<li><strong>Bill Type</strong>: " + billsVar[i]['type'] + "</li>";
var billSubjects = "<li><strong>Subjects</strong>: " + billsVar[i]['subjects'] + "</li>";
var billBillID = "<li><strong>Bill ID</strong>: " + billsVar[i]['bill_id'] + "</li>";
var billOutput = billList + billTitle + billCreatedAt + billUpdatedAt + billID + billChamber + billState + billSession + billType + billSubjects + billBillID + "</ul></li>";
$("#jsonlist").append(billOutput);
}
});
})
});
After a bit of research I see that a bill hyperlink is like this:
http://openstates.org/nj/bills/{Bill Session}/{Bill ID}/
I can't test my code because I have no API key, but the solution could be something like:
var billTitle = '<li><strong>Bill Title</strong>: '
+ '<a href="http://openstates.org/nj/bills/' +
billsVar[i]['session'] + '/' + billsVar[i]['bill_id'].split(' ').join('') + '/">'
+ billsVar[i]['title'] + '</a></li>';

Elfinder 2.0 decode filename

$("#elfinder").elfinder({
url: 'https://localhost/elfinder',
handlers: {
dblclick: function(event, elfinderInstance) {
var file = event.data.file; //l1_dGVzdC9iYW5uZXJfYmdfaG9yaXpvbnRhbC5qcGc
}
}
});
How to decrypt l1_dGVzdC9iYW5uZXJfYmdfaG9yaXpvbnRhbC5qcGc into banner_bg_horizontal.jpg (real filename) ?
For elFinder you'll need to modify the base64 keyStr values + / = to - _ .
var keyStr = "ABCDEFGHIJKLMNOP" +
"QRSTUVWXYZabcdef" +
"ghijklmnopqrstuv" +
"wxyz0123456789+/" +
"=";
change to...
var keyStr = "ABCDEFGHIJKLMNOP" +
"QRSTUVWXYZabcdef" +
"ghijklmnopqrstuv" +
"wxyz0123456789-_" +
".";
then strip the prefix "l1_" before decoding
because you do not use Base64
I use it and it works well
example Base64

How update data by Javascript

How can I, on the OnChange event, update data in my database ?
I have a WebMethod, that returns a HTML, so I can't see those elements, so I think he solution will be a javascript function.
A textarea catch the text from the database, if the user alter this, the database field has to be updated.
[WebMethod]
public static object ListAdvertise(string transaction)
{
StringBuilder retorno = new StringBuilder(160000);
Utilidade.QuebraToken tk2 = new Utilidade.QuebraToken();
string Credenciada = tk2.CarregaToken(1, HttpContext.Current.Request.Cookies["token"].Value);
string select3 = "SELECT * FROM San_Imovel WHERE Status_Id = 1 AND Credenciada_Id = " + Credenciada + " AND Transacao_Id IN (" + transacao + ") ORDER BY NomeCidade, NomeBairro, Imovel_Id ASC";
Utilidade.Conexao c3 = new Utilidade.Conexao();
SqlConnection con3 = new SqlConnection(c3.Con);
SqlCommand cmd3 = new SqlCommand(select3, con3);
con3.Open();
SqlDataReader r3 = cmd3.ExecuteReader();
while (r3.Read())
{
Imovel_Id = r3["Imovel_Id"].ToString();
Endereco = r3["Descricao"].ToString() + " " + r3["Logradouro"].ToString() + " " + r3["Numero"].ToString() + "/" + r3["DscComplemento"].ToString() + " " + r3["Complemento"].ToString() + " - " + r3["NomeBairro"].ToString();
TextoAnuncio = r3["TextoAnuncio"].ToString();
if (count % 2 == 0)
{
classe = "EstiloDalinhaGrid";
}
else
{
classe = "EstiloDalinhaAlternativaGrid";
}
retorno.Append("<tr class='" + classe + "'>");
retorno.Append("<td>");
retorno.Append(Imovel_Id);
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append(Endereco);
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append("<textarea id='txtArea'>");
retorno.Append(TextoAnuncio);
retorno.Append("</textarea>");
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append("<input type='checkbox' class='imoveisMarcados' id='" + Imovel_Id + "' />");
retorno.Append("</td>");
retorno.Append("</tr>");
count++;
}
retorno.Append("</table>");
con3.Close();
return new
{
retorno = string.Format(retorno.ToString())
};
i think you have to use Ajax for you to be able to update your data base .
check this link to learn more about ajax with Php (you chose whatever server side langage you'd like)
Ajax with PHP

Categories