Connect a smart contract to HTML code via javascript - javascript

I'm trying to follow this example to build a webpage that can interact with a smart contract.
It uses this code in remix:
pragma solidity ^0.4.18;
contract Coursetro {
string fName;
uint age;
function setInstructor(string _fName, uint _age) public {
fName = _fName;
age = _age;
}
function getInstructor() public constant returns (string, uint) {
return (fName, age);
}
}
And this code which I have set up in visual studio code:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="main.css">
<!-- <script src="./node_modules/web3/dist/web3.min.js"></script> -->
<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js#1.0.0-beta.36/dist/web3.min.js"></script>
</head>
<body>
<div class="container">
<h1>Coursetro Instructor</h1>
<h2 id="instructor"></h2>
<label for="name" class="col-lg-2 control-label">Instructor Name</label>
<input id="name" type="text">
<label for="name" class="col-lg-2 control-label">Instructor Age</label>
<input id="age" type="text">
<button id="button">Update Instructor</button>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script>
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
web3.eth.defaultAccount = web3.eth.accounts[0];
var CoursetroContract = web3.eth.contract([
{
"constant": false,
"inputs": [
{
"name": "_fName",
"type": "string"
},
{
"name": "_age",
"type": "uint256"
}
],
"name": "setInstructor",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "getInstructor",
"outputs": [
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]);
var Coursetro = CoursetroContract.at('0x0CF6A859635A0729d14b524d05619c7162A102bd');
console.log(Coursetro);
Coursetro.getInstructor(function(error, result){
if(!error)
{
$("#instructor").html(result[0]+' ('+result[1]+' years old)');
console.log(result);
}
else
console.error(error);
});
$("#button").click(function() {
Coursetro.setInstructor($("#name").val(), $("#age").val());
});
</script>
</body>
</html>
When I try to pull it up on the local host I've set it up on. localhost:8545, it gives me a 400 Bad Request with this in the console:
So I tried using an http-server command which successfully set up a site I can visit, but I am receiving these errors in the console:
Just wondering if anyone has had this issues before and knows how to fix them? Or if there is something I've missed and that's why I'm getting the errors.

Related

Angular Generate Pure HTML from Module JSON

Сan't generate an pure HTML file from current JSON data.
I tried to generate pure HTML file from angular generated module JSON:
{"surveyTitle":"ddasdas","surveyType":"Training","surveyQuestions":[{"questionTitle":"dasda","questionType":"Single choice","questionGroup":{"options":[{"optionText":"dsadsa"},{"optionText":"dasdsa"}],"showRemarksBox":false}}],"IsAnonymous":false}
To solve it I used this source below
from here surveyjs.io :
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>One choice - Radio Group question, jQuery Survey Library Example</title><meta name="viewport" content="width=device-width"/>
<script src="https://unpkg.com/jquery"></script>
<script src="https://unpkg.com/survey-jquery#1.8.75/survey.jquery.min.js"></script>
<link href="https://unpkg.com/survey-core#1.8.75/modern.min.css" type="text/css" rel="stylesheet"/>
<link rel="stylesheet" href="./index.css"></head>
<body>
<div id="surveyElement" style="display:inline-block;width:100%;"></div>
<div id="surveyResult"></div>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
JS:
Survey
.StylesManager
.applyTheme("modern");
var json = {
questions: [
{
"type": "radiogroup",
"name": "car",
"title": "What car are you driving?",
"isRequired": true,
"hasNone": true,
"colCount": 4,
"choices": [
"Ford",
"Vauxhall",
"Volkswagen",
"Nissan",
"Audi",
"Mercedes-Benz",
"BMW",
"Peugeot",
"Toyota",
"Citroen"
]
}
]
};
window.survey = new Survey.Model(json);
survey
.onComplete
.add(function (sender) {
document
.querySelector('#surveyResult')
.textContent = "Result JSON:\n" + JSON.stringify(sender.data, null, 3);
});
$("#surveyElement").Survey({model: survey});
But I getting errors for my current JSON.
My Code Here: Stackblitz - by clicking Add New Survey JSON has generates.

Making a gogocartojs map work in js project

I created a project and I'm trying to add gogocartoJs in it.
The project works but the map is not showing.
I tried with the guides I found in the site, it looks plain and easy, but there is an step that I'm not understanding (please dont just copy/paste a piece of the site like it was obvious what it is the mistake, because it is not for me)
<html lang="en">
<head>
<link
rel="stylesheet"
href="https://gogocarto.fr/assets/css/gogocarto.min.css"
/>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script type="text/javascript" src="./jquery.js"></script>
<script src="https://gogocarto.fr/js/gogocarto.min.js"></script>
<title>Hello Webpack</title>
</head>
<body>
<div>
<h1>Hello Webpack</h1>
<div id="gogocarto"></div>
</div>
<script>
$(document).ready(function() {
carto = goGoCarto("#gogocarto", {
data: {
taxonomy: taxonomy,
elements: elements
}
});
});
</script>
<script src="./bundle.js"></script>
</body>
</html>
I expect the map to show, and it doesnt
I added the project to github to show better
https://github.com/Aredros/testGogo/tree/master/dist
elements & taxonomy are js variables containing data you must provide according to the format described in the documentation.
// taxonomy
let taxonomy = {
"options":[
{
"id": "eu1",
"name":"Belgium",
"color":"#9acd32",
"icon":"fa-solid fa-building"
},
{
"id": "eu2",
"name": "Netherland",
"color": "#ffa500",
"icon": "fa-solid fa-fan"
},
{
"id": "eu3",
"name": "Luxembourg",
"color": "#a52a2a",
"icon": "fa-solid fa-money-bill-1"
}
]
}
The only missing info in the documentation is the id key in the taxonomy which must be referenced in your elements source dataset.
// elements
let elements = [
{
"title": "Brussels",
"geo": {
"latitude":50.84,
"longitude":4.34
},
"taxonomy": [ "eu1" ],
},
{
"title": "Namur",
"geo": {
"latitude":50.45,
"longitude":4.88
},
"taxonomy": [ "eu1" ],
},
{
"title": "Liege",
"geo": {
"latitude":50.62,
"longitude":5.60
},
"taxonomy": [ "eu1" ],
},
{
"title": "Rotterdam",
"geo": {
"latitude":51.88,
"longitude":4.51
},
"taxonomy": [ "eu2" ],
},
{
"title": "Amsterdam",
"geo": {
"latitude":52.07,
"longitude":5.12
},
"taxonomy": [ "eu2" ],
},
]
Idealy you should build an API returning taxonomy classification & elements data. Then perform ajax call in your html page.
$.ajax({
type: 'GET',
url: '/ajax/url_to_get_elements',
dataType: 'json',
success: function(elements, status) {
build_map(elements);
}
});
// build map = function with 1 arguments (elements) where you put the call to goGoCarto and options...
You can define more than 1 taxonomy group (Example above is about English countries) with the name you want => Cfr. Advanced Taxonomy with Categories. Your elements can then have multiple taxonomy reference listed [ "eu1", "week22", 14 ]. Items in the list can be Integer or String. The only important thing is the ID key and the taxonomy order! Keep the same order in your taxonomy than in your key "taxonomy": in your elements data sources!
Point of attention
Because the library is highly configurable with options, colors and icons it is important to put all your <scripts> tags inside <head> tags of your html page!

successfully parsed my .json file but there is an error

I've been continuing my work on a drag and drop page that will parse and display the json data.
I was able to parse the .json file and showed it in console but at the end there is an error showing up (Please refer on the screenshot below). Did I miss anything from my code? Thank you in advance!
JSFiddle : https://jsfiddle.net/vy19a7sf/2/
(function() {
var dropzone = document.getElementById("dropzone");
dropzone.ondrop = function(event) {
event.preventDefault();
this.className = "dropzone";
console.log(event.dataTransfer.files[0]);
var fileInput = document.getElementById("dropzone");
var fileDisplayArea = document.getElementById("displayarea");
var file = event.dataTransfer.files[0]
var textType = "";
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(read) {
// fileDisplayArea.innerText = reader.result;
var json = reader.result;
for(var num = 0; num < json.length; num++) {
obj = JSON.parse(json);
// console.log(obj["value"][num]);
console.log(obj["value"][num]["changesetId"]);
console.log(obj["value"][num]["author"]["displayName"]);
console.log(obj["value"][num]["createdDate"]);
console.log(obj["value"][num]["comment"]);
}
}
reader.readAsText(file);
}
else {
// fileDisplayArea.innerText = "File not supported!";
console.log("File not supported!")
}
}
dropzone.ondragover = function() {
this.className = "dropzone dragover";
return false;
};
dropzone.ondragleave = function() {
this.className = "dropzone";
return false;
};
}())
.dropzone {
display: flex;
line-height: 300px;
justify-content: center;
border: 2px dashed #ccc;
color: #ccc;
}
.dropzone.dragover {
border-color: #000;
color: #000;
}
.displayarea {
height: 200px;
width: 100%;
color: #000;
padding: 20px;
background-color: #e7e7e7;
overflow-x: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css" />
<link rel="stylesheet" href="/css/styles.css" />
<link rel="stylesheet" href="/changesets/css/styles.css" />
<title>Code Metrics Tool</title>
</head>
<body>
<header>
<div>
Code Metrics Tool
</div>
</header>
<main>
<h2>Changesets</h2>
<div class="dropzone" id="dropzone">Drop .json files here to convert</div>
</main>
<footer>
</footer>
<script src="/changesets/js/dragdrop.js"></script>
</body>
</html>
SCREENSHOT Console log was successfully printed, but at the end there is an error showing up
JSON File
{
"count": 2,
"value": [
{
"changesetId": 1456,
"url": "https://.../changesets/1456",
"author": {
"displayName": "--",
"url": "https://.../0e79980d-2df8-47b2-9aa3-4a7a118f1c90",
"id": "0e79980d-2df8-47b2-9aa3-4a7a118f1c90",
"uniqueName": "--",
"imageUrl": "https://.../identityImage?id=0e79980d-2df8-47b2-9aa3-4a7a118f1c90"
},
"checkedInBy": {
"displayName": "--",
"url": "https://.../0e79980d-2df8-47b2-9aa3-4a7a118f1c90",
"id": "0e79980d-2df8-47b2-9aa3-4a7a118f1c90",
"uniqueName": "--",
"imageUrl": "https://.../identityImage?id=0e79980d-2df8-47b2-9aa3-4a7a118f1c90"
},
"createdDate": "2018-02-28T11:20:36.52Z",
"comment": "fixed problems",
"commentTruncated": true
},
{
"changesetId": 1451,
"url": "https://.../changesets/1451",
"author": {
"displayName": "--",
"url": "https://.../f62e6531-cb28-6ebb-bb5c-1663549c6165",
"id": "f62e6531-cb28-6ebb-bb5c-1663549c6165",
"uniqueName": "--",
"imageUrl": "https://.../identityImage?id=f62e6531-cb28-6ebb-bb5c-1663549c6165"
},
"checkedInBy": {
"displayName": "--",
"url": "https://.../f62e6531-cb28-6ebb-bb5c-1663549c6165",
"id": "f62e6531-cb28-6ebb-bb5c-1663549c6165",
"uniqueName": "--",
"imageUrl": "https:///identityImage?id=f62e6531-cb28-6ebb-bb5c-1663549c6165"
},
"createdDate": "2018-02-26T11:47:42.233Z",
"comment": "Added an item",
"commentTruncated": true
}
]
}
As Patrick Evans commented, json.length is not the length of the array in "value".
You also don't want to use obj = JSON.parse(json) inside that loop, you only need to parse it once.
To solve this issue you described, you need to get the actual ids inside the "value" array.
let valueArray = obj.value;
valueArray.forEach(function(vel){
console.log(vel.changesetId);
console.log(vel.author);
//etc..
});

swagger-ui response example as reference in definitions

Is there a way to define a response example object in the 'definitions' and reference it using "$ref" : "#/definitions/ResponseExample"?
This is what my response looks like at the moment:
"200": {
"description" :"Successful operation",
"schema" : {
"$ref" : "#/definitions/AttributesBasicResponse"
},
"examples": {
"application/json": {
"data": [
{
"name" :"My data",
"code": "DATA",
"units": "UK, US, EU"
}
],
"attribute": "test"
}
}
}
What I'm trying to achieve is this:
"200": {
"description" :"Successful operation",
"schema" : {
"$ref" : "#/definitions/AttributesBasicResponse"
},
"examples": {
"$ref": "#/definitions/AttributeBasicExample"
}
}
I've decided to use whitlockjc/json-refs to resolve JSON references before passing json object into swaggerUI.
Load swagger.json using jQuery.get, run JsonRefs.resolveRefs to resolve 'relative' references in this case and then pass resolved json into
swaggerUi.setOption('spec', json) and update swaggerUi.load()
This is done on browser side, I could do this on server side using nodejs to reduce the number of http requests.
Updated swagger-ui index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="icon" type="image/png" href="images/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="images/favicon-16x16.png" sizes="16x16" />
<link href='css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='css/reset.css' media='print' rel='stylesheet' type='text/css'/>
<link href='css/print.css' media='print' rel='stylesheet' type='text/css'/>
<script src='lib/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='lib/jquery.slideto.min.js' type='text/javascript'></script>
<script src='lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='lib/handlebars-2.0.0.js' type='text/javascript'></script>
<script src='lib/underscore-min.js' type='text/javascript'></script>
<script src='lib/backbone-min.js' type='text/javascript'></script>
<script src='swagger-ui.js' type='text/javascript'></script>
<script src='lib/highlight.7.3.pack.js' type='text/javascript'></script>
<script src='lib/jsoneditor.min.js' type='text/javascript'></script>
<script src='lib/marked.js' type='text/javascript'></script>
<script src='lib/swagger-oauth.js' type='text/javascript'></script>
<script src='lib/json-refs-standalone.js' type='text/javascript'></script>
<script type="text/javascript">
$(function () {
var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
url = "http://petstore.swagger.io/v2/swagger.json";
}
// Pre load translate...
if(window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
window.swaggerUi = new SwaggerUi({
url: url,
dom_id: "swagger-ui-container",
supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
onComplete: function(swaggerApi, swaggerUi){
if(typeof initOAuth == "function") {
initOAuth({
clientId: "your-client-id",
clientSecret: "your-client-secret-if-required",
realm: "your-realms",
appName: "your-app-name",
scopeSeparator: ",",
additionalQueryStringParams: {}
});
}
if(window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
$('pre code').each(function(i, e) {
hljs.highlightBlock(e)
});
addApiKeyAuthorization();
},
onFailure: function(data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "none",
jsonEditor: false,
apisSorter: "alpha",
defaultModelRendering: 'schema',
showRequestHeaders: false
});
function changedBaseUrl( event ) {
event.preventDefault();
var url = $(this ).val();
$.get( url ,function(response){
// do the json-refs first
JsonRefs.resolveRefs( response, { relativeBase: '/swagger',filter: [ 'relative' ] } )
.then(function( response ){
var json = response.resolved;
window.swaggerUi.setOption('spec', json);
window.swaggerUi.load();
// resolve failed
}, function( error ){
console.log("failure", error);
});
});
}
function addApiKeyAuthorization(){
var key = encodeURIComponent($('#input_apiKey')[0].value);
if(key && key.trim() != "") {
var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("api_key", key, "query");
window.swaggerUi.api.clientAuthorizations.add("api_key", apiKeyAuth);
log("added key " + key);
}
}
$('#input_baseUrl').change(changedBaseUrl);
$('#input_apiKey').change(addApiKeyAuthorization);
// if you have an apiKey you would like to pre-populate on the page for demonstration purposes...
/*
var apiKey = "myApiKeyXXXX123456789";
$('#input_apiKey').val(apiKey);
*/
window.swaggerUi.load();
function log() {
if ('console' in window) {
console.log.apply(console, arguments);
}
}
});
</script>
</head>
<body class="swagger-section">
<div id='header'>
<div class="swagger-ui-wrap">
<a id="logo" href="http://swagger.io">swagger</a>
<form id='api_selector'>
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
<div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/></div>
<div class='input'><a id="explore" href="#" data-sw-translate>Explore</a></div>
</form>
</div>
</div>
<div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>
Sample swagger.json:
{
"swagger": "2.0",
"info": {
"title": "Basic Login",
"version": " 1.0.0"
},
"paths": {
"login": {
"post": {
"summary": "User login",
"tags" : [ "Login" ],
"responses" : {
"200": {
"description" :"Returns authorization hash",
"schema" : {
"$ref" : "./schemas/login.json"
},
"examples": {
"$ref": "./responses/login/login.json"
}
}
}
}
}
}
}
schema login.json
{
"type" : "object",
"properties": {
"data": {
"type": "object",
"properties": {
"auth_hash": {
"type": "string"
}
}
}
}
}
example login.json:
{
"data": {
"auth_hash": "e2ad8410efa2d68cedad76b83eb97ecd"
}
}
end result after JsonRefs has run:
{
"swagger": "2.0",
"info": {
"title": "Basic Login",
"version": " 1.0.0"
},
"paths": {
"login": {
"post": {
"summary": "User login",
"tags": [
"Login"
],
"responses": {
"200": {
"description": "Returns authorization hash",
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"auth_hash": {
"type": "string"
}
}
}
}
},
"examples": {
"data": {
"auth_hash": "e2ad8410efa2d68cedad76b83eb97ecd"
}
}
}
}
}
}
}
}
Other references used:
swagger-ui issue #1110
json-refs API docs
json-refs browser source code

uncaught typeerror object object object has no method 'kendoUi' Error in Parsing

This is My JSonSctipt file code:
var data = [
{
"SearchResult": {
"assets": [
{
"agent": "6.1.0",
"id": 1,
"model": "Gateway1",
"modelId": 2,
"name": "Name",
"serialNumber": "Serial01"
},
{
"agent": "M2M",
"id": 2,
"model": "Gateway1",
"modelId": 3,
"name": "Name",
"serialNumber": "Serial02"
}
],
"searchCriteria": {
"paginationEnabled": false,
"rowsPerPage": -1,
"startRow": -1,
"totalAvailableRows": -1,
"alternateId": {
"#xsi.nil": "true"
},
"modelNumber": {
"#xsi.nil": "true"
},
"name": "*",
"serialNumber": {
"#xsi.nil": "true"
}
}
}
}
];
$("#grid").kendoGrid({
dataSource: {
data: data,
schema: {
data: function(rawData) {
return rawData[0].SearchResult.assets;
}
}
}
});
Thsi is My Index.html file
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="cordova.js"></script>
<script src="kendo/js/jquery.min.js"></script>
<script src="kendo/js/kendo.mobile.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="scripts/hello-world.js"></script>
<script src="kendo/js/kendo.dataviz.min.js"></script>
<link href="kendo/styles/kendo.mobile.all.min.css" rel="stylesheet" />
<link href="styles/main.css" rel="stylesheet" />
</head>
<body>
<div id="grid"></div>
</body>
</html>
when i run this code uncaught typeerror object object object has no method 'kendoUi' Error I m getting so am Unable to Display data In Grid please tell me how i will fix it or can any one Please tell me how i will Json parsing In Kendo UI
It looks like you are trying to use Kendo Grid, which is a part of Kendo Web, but only have a reference to Kendo Mobile (i.e. kendo.mobile.min.js). You need to add a script reference to either kendo.web.min.js or kendo.all.min.js. Take a look at this jsfiddle, paying particular attention to the External Resource (i.e. kendo.all.min.js)
P.S. SO won't let me post a link to jsfiddle without some code, so here is part of the code again, to satisfy their requirements:
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
</head>
<bo
<div id="grid"></div>
</body>

Categories