I am trying to implement QuaggaJS in a static file way, but clearly I am missing something.
I am very new to javascript and as such hoping I am missing something very simple.
Assuming i have a .jpg file in the same directory as this code , named 123456.jpg,
I want the code to simply return the barcode value as an alert.
Any help greatly appreciated (and totally ready to be blasted for my lack of understanding of javascript!)
My code is below:
<script src="http://www.myserver.com/v3/javascripts/jquery-2.0.0.min.js" type="text/javascript"></script>
<script src="js/quagga.min.js" type="text/javascript"></script>
<script>
Quagga.decodeSingle({
decoder: {
readers: ["code_39_reader"] // List of active readers
},
locate: true, // try to locate the barcode in the image
src: '123456.jpg' // or 'data:image/jpg;base64,' + data
}, function(result){
if(result.codeResult) {
console.log("result", result.codeResult.code);
alert(result.codeResult.code);
} else {
console.log("not detected");
alert("not detected");
}
});
</script>
Maybe clumsy...but I got the following to decode a Code_39 barcode in a static .jpg file located in same directory, on page load:
<div>
<div id="resultdiv">scanning... </div>
</div>
<script src="../js/quagga.js" type="text/javascript"></script>
<script type="text/javascript">
var Quagga = window.Quagga;
var App = {
_scanner: null,
init: function() {
this.decode();
},
decode: function(file) {
Quagga
.decoder({readers: ['code_39_reader']})
.locator({patchSize: 'x-small'})
.fromSource('converted.jpg', {size: 1920})
.toPromise()
.then(function(result) {
document.getElementById("resultdiv").innerHTML=result.codeResult.code;
})
.catch(function() {
document.getElementById("resultdiv").innerHTML= "Not Found";
})
}
};
App.init();
</script>
Related
I'm new to SvelteKit and trying to find out how to load the Google client library for Javascript.
Google tells me to do it like this:
<head>
<script src="https://apis.google.com/js/api.js"></script>
<script>
function start() {
// Initializes the client with the API key and the Translate API.
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/translate/v2/rest'],
}).then(function() {
// Executes an API request, and returns a Promise.
// The method name `language.translations.list` comes from the API discovery.
return gapi.client.language.translations.list({
q: 'hello world',
source: 'en',
target: 'de',
});
}).then(function(response) {
console.log(response.result.data.translations[0].translatedText);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
};
// Loads the JavaScript client library and invokes `start` afterwards.
gapi.load('client', start);
</script>
</head>
The problem is that SvelteKit doesn't allow 2 or more script tags on a page (I don't want it to be the layout page).
<script src="https://apis.google.com/js/api.js"></script>
<script>
import { onMount } from 'svelte';
gapi.client.init({...
</script>
This results in follwing error message:
A component can only have one instance-level <script> element
As my intention is to create a progressive web app (PWA) using Workbox I don't want to import the Google library as described here because the package containing this library would become too heavy.
Any ideas how to load the Google client library? Maybe there's a Workbox way to do it? Couldn't find a SvelteKit example on Google or YouTube.
Thanks in advance
The svelte:head tag allows you to add resources to the document head when a component is loaded. This example should work:
<script>
const start = async () => {
// Initializes the client with the API key and the Translate API.
// #ts-ignore
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/translate/v2/rest'],
}).then(function() {
// Executes an API request, and returns a Promise.
// The method name `language.translations.list` comes from the API discovery.
return gapi.client.language.translations.list({
q: 'hello world',
source: 'en',
target: 'de',
});
}).then(function(response) {
console.log(response.result.data.translations[0].translatedText);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
};
const initializeGapi = async () => {
gapi.load('client', start);
}
</script>
<svelte:head>
<script src="https://apis.google.com/js/api.js" on:load={initializeGapi}></script>
</svelte:head>
I've made something like this.
Save it as GoogleMap.svelte to your lib folder. and use it like this;
<GoogleMap
{map}
globally
on:load={() => {
console.log('MAP SAYS IM LOADED');
}}
/>
Map is a reference object
globally defines it to window.map
<script>
import { onMount } from 'svelte';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
//import mapStyles from './map-styles'; // optional
export let globally = false;
export let map;
let src = '';
const key = '';
// #ts-ignore
let container;
let zoom = 8;
let center = { lat: 37.5742776, lng: 43.7260158 };
onMount(() => {
Object.assign(window, {
mapLoaded: () => {
// #ts-ignore
map = new google.maps.Map(container, {
zoom,
center
// styles: mapStyles
});
dispatch('load', true);
if (globally) {
Object.assign(window, { map });
}
}
});
//Assign
src = `https://maps.googleapis.com/maps/api/js?key=${key}&callback=mapLoaded`;
});
</script>
<!-- This is tailwind css class change with whatever fits to your case. -->
<div class="w-full h-full" bind:this={container} />
<svelte:head>
{#if src}
<script {src}></script>
{/if}
</svelte:head>
I would like to send a post request to my API. It works with jQuery :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",
url: "api.php?option=inscription",
data: {lol : "mess"}
});
</script>
But it doesn't with AngularJS :
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
{{1+1}}
<script>
$http.post('api.php?option=inscription', {lol : "mess2"})
.success(function(){alert('cool');});
</script>
If someone can help me. Thank you !
UPDATE :
Thank for your answers, I wanted to simplify but it wasn't clear anymore. So with your help, this is my new code, and the problem is the same. The data in the backend is empty ;
frontend :
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<div ng-controller="MainCtrl"></div>
{{data}}
<script>
var app = angular.module('myApp', []);
app.service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {
var back = $http.post(dataUrl, dataTobePosted);
back.success(function(data){
console.log(data);
return data;
}).error(function(data, status, headers, config) {
return status;
});
}
});
app.controller('MainCtrl', function($scope, $http, SomeService){
$scope.readData = function(url) {
var dataTobePosted = {"lol": "mess"};
$scope.data = SomeService.readData(url, dataTobePosted);
}
$scope.readData('api.php?option=inscription');
});
</script>
</html>
For clarity, I am suggesting a simple implementation. However, further reading may needed in order to understand the behaviour precisely.
angular.module('myApp').service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {
// read data;
return $http.post(dataUrl, dataTobePosted)
.then(function(res) {
return res.data;
}, function(res) {
return res;
}
}
return this;
});
angular.module('myApp').controller('MyController', function($scope, SomeService) {
$scope.readData = function(url) {
var dataTobePosted = {"lol": "mess"};
SomeService.readData(url, dataTobePosted)
.then(function(res) {
$scope.data = res;
}, function(res) {
// Display error
}
}
$scope.readData('api.php?option=inscription');
}
Usage in the HTML page
<div ng-controller="MyController">
{{data}}
</div>
You're using AngularJS as if it's jQuery. It's not. AngularJS works with dependency injection, so you need to wrap your $http call inside a controller.
You should probably read up on AngularJS. A few useful links:
https://docs.angularjs.org/guide/introduction
https://docs.angularjs.org/guide/controller
https://docs.angularjs.org/guide/di
"Thinking in AngularJS" if I have a jQuery background?
My bad, my problem came from my backend in the php I just get my data with :
$data = json_decode(file_get_contents("php://input"));
and not with $_POST
Why Marionette events are not triggered when I access a URL?
When I access the URL it suppose to call the function API.goHome()
but it doesn't! I don't understand why?
Here is my Code:
App.js
var PatientPortal = new Marionette.Application();
PatientPortal.addRegions({
'headerRegion': '#header',
'bodyRegion': '#body',
'footerRegion': '#footer'
});
PatientPortal.on("before:start", function () {
console.log("Started");
});
PatientPortal.navigate = function (route, options) {
options || (options = {});
Backbone.history.navigate(route, options);
};
PatientPortal.getCurrentRoute = function () {
return Backbone.history.fragment
};
PatientPortal.on("start", function(){
if (Backbone.history) {
Backbone.history.start();
}
if(PatientPortal.getCurrentRoute() == ""){
PatientPortal.navigate('home');
}
});
PatientPortal.start();
and Router Code:
PatientPortal.module("Portal", function (Portal, PatientPortal, Backbone, Marionette, $, _) {
Portal.Router = Backbone.Marionette.AppRouter.extend({
controller: "API",
appRoutes: {
"": "goHome",
"home": "goHome"
}
});
var API = {
goHome: function () {
console.log("go home");
}
};
PatientPortal.on("home:route", function () {
console.log("OKOKOK")
API.goHome();
});
PatientPortal.addInitializer(function () {
new Portal.Router({
controller: API
});
});
});
and here a home page code:
<!DOCTYPE html>
<html>
<head>
<title>INSAH - Login Page</title>
</head>
<body>
<div id="header"></div>
<script src="./js/assets/provider/jquery/jquery-2.1.1.min.js"></script>
<script src="./js/assets/provider/underscore/underscore-min.js"></script>
<script src="./js/assets/provider/backbone/backbone-min.js"></script>
<script src="./js/assets/provider/backbone/backbone.babysitter.min.js"></script>
<script src="./js/assets/provider/backbone/backbone.wreqr.min.js"></script>
<script src="./js/assets/provider/marionette/backbone.marionette.min.js"></script>
<script src="./js/app.js"></script>
<script src="./js/routes/route.js"></script>
</body>
</html>
Thanks.
I figured out the problem, it was because of starting the backbone history, the AddInitializer functuion shoudl be as following:
PatientPortal.addInitializer(function () {
new Portal.Router({
controller: API
});
Backbone.history.start();
});
and we should remove this line from app.js:
Backbone.history.start();
How can I avoid the next logic ? I have the next code in view:
<script type="text/javascript">
var x = $("#myId1").val();
#if(Model.IsOptions)
{
$('#myId2').click(function () { doSomething(); });
}
</script>
So, I want execute $('#myId2').. only if 'Model.IsOption' is true. Currently Visual Studio underline it as wrong code.
The code inside #if should be C#, not JavaScript. Razor tries to execute it on server, not on client. To force it to treat it as JavaScript, you should use <text></text> or #:, like this.
<script type="text/javascript">
var x = $("#myId1").val();
#if(Model.IsOptions)
{
<text>
$('#myId2').click(function () { doSomething(); });
</text>
}
</script>
Can you try:
#{
if(Model.IsOptions)
{
$('#myId2').click(function () { doSomething(); });
}
}
Does it work?
Is there an easy way to auto-resize a jqplot chart when resizing the browser? I have been looking on Google, and haven't found anything.
Resizing jqplots is discussed here.
To make it work when the browser is resized, bind the replot function up with the window.resize event:
$(window).resize(function() {
plot1.replot( { resetAxes: true } );
});
Running code:
$(document).ready(function(){
var plot1 = $.jqplot ('container', [[3,7,9,1,4,6,8,2,5]], {});
$(window).resize(function() {
plot1.replot( { resetAxes: true } );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.8/jquery.jqplot.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.8/jquery.jqplot.min.css">
<div id="container"></div>
I've found that using replot doesn't always give consistent results if you've got a lot of options on your graphs. The only way I've found to have complex graphs cope with window resizes is to get brutal and destroy it and rebuild it.
function () {
var plot;
var renderGraph = function() {
plot = $.jqplot('chartId', yourChartData, yourChartOptions);
}
renderGraph();
var resizeGraph = function() {
if (plot)
plot.destroy();
renderGraph();
}
$(window).resize(function() {
resizeGraph();
});
}