I'm using as reference this code https://www.itsolutionstuff.com/post/jquery-html5-qr-code-scanner-using-instascan-js-exampleexample.html when i get the result of the QR y send it to a variable, what I try to do and I don't get a result is that when I want to send a function in the codebehing I never get a response result.
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="../Scripts/jquery-3.3.1.min.js"></script>
<script src="assets/js/instascan.min.js"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<video id="preview" class="col-lg-12"></video>
<script type="text/javascript">
let scanner = new Instascan.Scanner({ video: document.getElementById('preview') });
scanner.addListener('scan', function (content) {
var test = content.toString(); //here i get the variable
alert(test);
<%=SendToDB(content)%>;
});
Instascan.Camera.getCameras().then(function (cameras) {
if (cameras.length > 0) {
scanner.start(cameras[0]);
} else {
console.error('There is no camera');
}
}).catch(function (e) {
console.error(e);
});
</script>
</div>
</div>
</div>
</asp:Content>
Now in codebehind I have something like this
public void SendToDB(string content)
{
string variable = content;
//here I send it to the database
}
I know this is an older question but I was struggling with this too so I wanted to post an answer for anyone else. Try changing your html code to this:
<script type="text/javascript">
let scanner = new Instascan.Scanner({ video: document.getElementById('preview') });
scanner.addListener('scan', function (content) {
var test = content.toString(); //here i get the variable
alert(test);
var options = {};
options.url = "Default.aspx/SendToDB";
options.type = "POST";
options.data = JSON.stringify({ content });
options.dataType = "json";
options.contentType = "application/json";
options.success = function (result) { };
options.error = function (err) { };
$.ajax(options);
});
Instascan.Camera.getCameras().then(function (cameras) {
if (cameras.length > 0) {
scanner.start(cameras[0]);
} else {
console.error('There is no camera');
}
}).catch(function (e) {
console.error(e);
});
</script>
What is important here is the "options.url = "Default.aspx/SendToDB";". If the name of your page isn't Default.aspx then you need to change it to the correct page name.
Now in your C# code you need to add [WebMethod] above your function:
[WebMethod]
public void SendToDB(string content)
{
string variable = content;
//here I send it to the database
}
Related
I have an image URL in javascript extracted from a canvas in html and i want to create an image from that URL and upload it to my storage files in server.
i can send the Url in a ajax post request to my sendImagetoController function in controller or if there is a method from javascript to do that.My routes are all defined and tested.Please Help
my display.blade.php .
<html>
<head>
<title>HeatMap Display</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src='http://www.patrick-wied.at/static/heatmapjs/assets/js/heatmap.min.js'></script>
<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
<script src="{{ asset('js/jquery.js')}}" type="text/javascript"></script>
<script src="{{ asset('js/app.js') }}" defer></script>
<script src="{{ asset('js/heatmap.js' )}}" type="text/javascript"></script>
<script>
var coordinatesarray = #json($coordinates);
var finalcoordinatesarr=[];
var count=0;
var mapId={{$targetHeatMap->id}};
var mintime=10000000;
var maxtime=0;
var imgUrl="";
coordinatesarray.forEach(element => {
var cor={
'x' : coordinatesarray[count]['x'],
'y' : coordinatesarray[count]['y'],
'value' : coordinatesarray[count]['time_spent']
};
if(mintime>coordinatesarray[count]['time_spent']){
mintime=coordinatesarray[count]['time_spent'];}
if(maxtime<coordinatesarray[count]['time_spent'])
maxtime=coordinatesarray[count]['time_spent'];
finalcoordinatesarr.push(cor);
count++;
});
console.log(finalcoordinatesarr);
function load(){
renderCanvas();
}
function renderCanvas(){
var heatmapInstance = h337.create({
container: document.getElementById('heatMap')
});
var testData = {
min: mintime,
max: maxtime,
data:finalcoordinatesarr
};
heatmapInstance.setData(testData);
imgUrl = (document.getElementById("heatMap").childNodes[0]).toDataURL();
document.getElementById("heatMapPic").src=imgUrl;
}
sendImageToController();
function sendImageToController(){
formdata = new FormData();
if($('#heatMapPic').prop('files').length>0){
file = $('#heatMapPic').prop('files');
formdata.append("heatMapPic",file);
}
formdata.append('tagetHeatMap',$('#targetHeatMap').val());
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name="csrf-token"]').attr('content') }
});
$.ajax({
url: "{{route('HeatMap.moveToStorage')}}",
data: formdata,
type:'post',
// traditional:true,
success:function(response){
console.log("correct");
console.log(response);
},
error:function(e){
console.log("errrooooor");
console.log(e);
},
});
console.log("hi");
}
</script>
</head>
<body onload="load()">
<form id="form" enctype="multipart/form-data">
#csrf
<input type="file" id="heatMapPic" name="heatMapPic" src=""/>
<input type="text" id="targetHeatMap" value="{{$targetHeatMap}}"/>
</form>
<div id="heatMap" style="height:740px"></div>
<a-scene>
{{-- <a-sky radius=10 opacity="0.8" src="{{asset('uploads/heat_map_images/'.$targetHeatMap->heatmap_image)}}"></a-sky> --}}
{{-- <a-sky radius=10 src="{{asset('uploads/'.$imageName)}}"></a-sky> --}}
</a-scene>
</body>
</html>
my Controller method
public function moveToStorage(Request $request){
return 'hello';
}
I use this method in PHP, the fact that the file itself comes to php through the variable $_FILES() and is not visible in the main query.
<?php
putenv("upload_tmp_dir=/var/www/site.com/public_html/upload/");
$uploadDir = getenv("upload_tmp_dir");
$uploadFile = $uploadDir . basename($_FILES['userfile']['name']);
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadFile);
?>
Then you can open the file in the path in the $uploadFile variable
If you have url which is publicly accessible then you can use it like this
public function moveToStorage(Request $request){
$data = $request->all();
$url = $data['file_url'] ; //file url that you have in javascript
$contents = file_get_contents($url);
$name = substr($url, strrpos($url, '/') + 1);
Storage::put($name, $contents);
return 'hello';
}
OR if your file is posted as base64 then try this
public function moveToStorage(Request $request){
$data = $request->all();
$file = $data['file_url']; //base64 encoded image
$file = substr($file, strpos($file, ",")+1);
$imgeData = base64_decode($file);
$contents = file_get_contents($imgeData);
Storage::put("test.png", $contents);
return 'hello';
}
Looking at your code, it looks like you're trying to send the image before it is actually rendered. You need to move sendImageToController() inside your load function, after renderCanvas().
Also, no need for all the formData stuff. Just send the result of .toDataURL() as-is to the server, then use base64_decode() to turn it back into an image.
Here are the relevant changes:
function load() {
renderCanvas();
sendImageToController(); // send to server AFTER rendering
}
var imgUrl;
function renderCanvas() {
// ...
imgUrl = (document.getElementById("heatMap").childNodes[0]).toDataURL();
// ...
}
Shorter AJAX code:
function sendImageToController() {
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
$.post("{{route('HeatMap.moveToStorage')}}", {
heatmap: imgUrl // global var set in renderCanvas()!!
})
.done(function(response) {
console.log("correct");
console.log(response);
})
.fail(function(e) {
console.log("errrooooor");
console.log(e);
});
}
On the server, grab the heatmap parameter.
public function moveToStorage(Request $request){
$heatmap = $request->input('heatmap');
$base64 = explode(",", $heatmap)[1];
$binary = base64_decode($base64);
// store $binary data in PNG file
return 'image saved successfully';
}
EDIT:
I think i have found a solution for this one. Might be a little primitive but inserting it here until someone comes up with a better solution.
Thanks !
<html>
<body onload="makeShort()">
<p id="button" style=display:none; onclick="makeShort()">Click me.</p>
<span id="output" style=display:none; >Wait. Loading....</span>
</body>
<head>
</head>
<script type="text/javascript">
function makeShort()
{
var longUrl=location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str =""+response.id+"";
document.getElementById("output").innerHTML = str;
}
else
{
alert("error: creating short url n"+ response.error);
}
});
}
window.onload = makeShort;
function load()
{
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxx');
gapi.client.load('urlshortener', 'v1',function(){document.getElementById("output").innerHTML="";});
}
window.onload = load;
</script>
<script>
setTimeout(function(){
document.getElementById('button').click();
},1000);
</script>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script>
function SendLinkByMail(href) {
var subject= "Interesting Information";
var body = document.getElementById("output").innerHTML;
body += " Interesting Information";
var uri = "mailto:?subject=";
uri += encodeURIComponent(subject);
uri += "&body=";
uri += encodeURIComponent(body);
window.open(uri);
}
</script>
</head>
<body>
<p>Email link to this page</p>
</body>
</html>
Can some one suggest why this "auto-click" function is not working in my code below?
function makeShort() {
var longUrl = location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if (response.id != null) {
str = "<b>Long URL:</b>" + longUrl + "<br>";
str += "<b>Short URL:</b> <a href='" + response.id + "'>" + response.id + "</a><br>";
document.getElementById("output").innerHTML = str;
} else {
alert("error: creating short url n" + response.error);
}
});} window.onload = function() {
var button = document.getElementById('modal');
button.form.submit();}
function load() {
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxxxxx');
gapi.client.load('urlshortener', 'v1', function() {
document.getElementById("output").innerHTML = "";
});} window.onload = load;
<html>
<input type="button" id="modal" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output">Wait. Loading....</div>
<head>
</head>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
My basic aim is to insert a "share via email" button on the page which would shorten the url on the address bar and open user's email client/whatsapp app to share that url..
Obviously I could not find a way to combine these two functions in to one since I am not a very experienced js person. The primitive solution I found is to auto-click the first function, get the short url, and then find a different code to insert this in to the body of the "mailto" link, which will be my 2nd challenge.
To programmatically click a button on page load
If you are using jQuery:
$(function() {
$('#modal').click();
});
Plain javascript:
window.onload = function(){
var event = document.createEvent('Event');
event.initEvent('input', true, true);
document.getElementById("modal").dispatchEvent(event);
};
I am using PageMethods to call C# function from Javascript.
My C# function is return as String.
But after i called that function from Javascript it returned current page.
Here my code:
ASPX:
<form id="form1" runat="server" method="post">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<script>
function testPageMethods(){
var id = 45;
PageMethods.returnStr4Frontend(id, onSucess, onError);
}
function onSucess(result) {
console.log(result);
}
function onError(result) {
console.log(has error);
}
testPageMethods();
</script>
</form>
ASPX.CS
[WebMethod]
public static string returnStr4Frontend(string id)
{
string reStr = string.Empty;
reStr = "Your id is: " + id;
return reStr;
}
When i run my page on browser, i received wrong result was (all html code of current page):
<form id="form1" runat="server" method="post">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<script>
function testPageMethods(){
var id = 45;
PageMethods.returnStr4Frontend(id, onSucess, onError);
}
function onSucess(result) {
console.log(result);
}
function onError(result) {
console.log(has error);
}
testPageMethods();
</script>
</form>
Check this nugget
https://www.nuget.org/packages/HtmlAgilityPack
it will get the html code depending on the domain you entered
I have created a system where user selects files from their Google drive to be uploaded into Parse.
I have done so separately though, where I have one code that allows user to select an item from Google drive, and one that allows user to upload a file from their computer into parse.
Google drive (Using Google drive picker):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>eSnail Scan Upload Part 2</title>
<script type="text/javascript">
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'KEY';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
}
</script>
</head>
<body>
<div id="result"></div>
<div id="demo">
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>
That allows a user to upload a file into Parse (PDF):
<HTML>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.15.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// ***************************************************
// NOTE: Replace the following your own keys
// ***************************************************
Parse.initialize("ID", "ID");
function saveDocumentUpload(objParseFile)
{
var documentUpload = new Parse.Object("Scan");
documentUpload.set("Name", "");
documentUpload.set("DocumentName", objParseFile);
documentUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
$('#myForm').bind("submit", function (e) {
e.preventDefault();
var fileUploadControl = $("#documentFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
var user_id = $('#user_id').val();
var address = $('#address').val();
parseFile.set('UserId', user_id);
parseFile.set('Address', address);
parseFile.save().then(
function () {
saveDocumentUpload(parseFile);
},
function (error) {
alert("error");
}
);
});
});
</script>
<body><form id='myForm'>
<input type="file" id="documentFileUpload">
<br/>
<input type="text" placeholder="UserID" id="user_id">
<br/>
<input type="text" placeholder="Address" id="address">
<br/>
<input type="submit" value="submit">
</form>
</body>
</HTML>
I'm getting "Uncaught ReferenceError: refreshAgonas is not defined "
The players div is filled correctly. Do I need some kind of special define with the JS functions in the JS file?
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery-draw.js"></script>
<h2>Game</h2>
<div class="agonas">
<script>
setInterval(refreshAgonas, 5000);
var inRequesG = false;
</script>
</div>
<h2>Players</h2>
<div class="players">
<script>
setInterval(refreshPlayers, 5000);
var inRequest = false;
</script>
</div>
</html>
jquery-draw.js
function refreshPlayers() {
if (inRequest) {
return false;
}
inRequest = true;
var load = $.get('playersdata.php');
$(".players").html('Refreshing');
load.error(function () {
console.log("Mlkia kaneis");
$(".players").html('failed to load');
// do something here if request failed
});
load.success(function (res) {
console.log("Success");
$(".players").html('<table border="1"><tr><th>ID</th><th>Name</th><th>Email</th><th>League</th><th>Sex</th><th>Birthday</th></tr>' + res + '</table>');
});
load.done(function () {
console.log("Completed");
inRequest = false;
});
}
function refreshAgonas() {
if (inRequestG) {
return false;
}
inRequestG = true;
var load = $.get('playersdata.php');
$(".agonas").html('Refreshing');
load.error(function () {
console.log("Mlkia kaneis");
$(".agonas").html('failed to load');
// do something here if request failed
});
load.success(function (res) {
console.log("Success");
$(".agonas").html('<table border="1"><tr><th>ID</th><th>Name</th><th>Email</th><th>League</th><th>Sex</th><th>Birthday</th></tr>' + res + '</table>');
});
load.done(function () {
console.log("Completed");
inRequestG = false;
});
}
Now I saw the problem:
Replace
var inRequesG = false;
With
var inRequestG = false;
You forgot the "t"
Try defining the functions like this:
var refreshPlayers = function () {};
var refreshAgonas = function () {};
Try this and respond with the results.
EDIT: didn't mean to include the parenthesis.
Try replacing:
setInterval( refreshAgonas, 5000);
With this:
setInterval(function(){ refreshAgonas()}, 5000);