send data in object from html by fetch to spreadsheet - html

I try to send data from html inputs to spreasheet like author in video
https://www.youtube.com/watch?v=yiPnkBEHqf0&list=PLRmEk9smitaVGAAhgU0Pdc2sEs7yxDrEk
In JS and HTML I wrote this:
const url = "https://script.google.com/macros/s/AKfycbzZe824lIxa-hNsO71xoFfq5qXbFaDKhHZeACrQgLMCjU_EjvY/exec";
var loginText = document.getElementById("tLogin");
var tableText = document.getElementById("tTable");
var orderText = document.getElementById("tOrder");
function testGS(){
var userInfo = {
login: loginText.value,
table: tableText.value,
order: orderText.value,
sdate: new Date().toLocaleDateString(),
};
fetch(url, {
method: 'POST',
headers: {"Content-Type": 'application/json'},
body: JSON.stringify(userInfo)
})
.then((res) => res.text())
.then((text) => console.log(text));
}
document.getElementById("del").addEventListener("click", testGS);
<!doctype html>
<html lang="en">
<head>
<title>CLR: PACKING</title>
<meta charset = "UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="CSS/main_page_style.css">
<link rel="icon" href="Image/favicon.png" type="png">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
</head>
<body>
<div class="conteiner">
<form novalidate>
<h6 class="title">PACKING</h6>
<img src="Image/mainImg.jpg" class="img-fluid" alt="...">
<div class="dws-input">
<div class="col-md-3"></div>
<div>
<div>
<button id="del" type="button"><======СБРОС</button>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tLogin" name= "username" placeholder= "Login:" autofocus >
<label for="tLogin">Логин:</label>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tTable" name= "text" placeholder= "Table:" >
<label for="tTable">Номер стола:</label>
</div>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" novalidate class="form-control" id="tOrder" name= "text" placeholder= "Order:" >
<label for="type3">Заказ:</label>
</div>
</div>
</form>
</div>
<script src="JS/fetchNew.js"></script>
</body>
</html>
In GAS I wrote this:
function doGet() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("LOG_history");
const data = ws.getRange("A1").getDataRegion().getValues();
const headers = data.shift();
const jsonArray = data.map(r => {
let obj = {};
headers.forEach((h , i) => {
obj[h] = r[i];
});
return obj;
})
const response = [{status: 200, data: jsonArray}];
return sendJSON_(response);
}
function doPost(e){
let jsonResponse;
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("LOG_history");
const headers = ws.getRange(1,1,1,ws.getLastColumn()).getValues()[0];
const headersOriginalOrder = headers.slice();
headersOriginalOrder.shift();
//remove id columns header
headers.shift();
headers.sort();
const body = e.postData.contents;
const bodyJSON = JSON.parse(body);
const headersPassed = Object.keys(bodyJSON).sort();
if(!compareTwoArray_(headers, headersPassed)){
jsonResponse = [{status:500, message:"Invalid Arguments Passed"}];
return sendJSON_(jsonResponse);
}
const arrayOfData = headersOriginalOrder.map(h => bodyJSON[h]);
const aoaIds = ws.getRange(2,1,ws.getLastRow()-1,1).getValues();
const newIDNumber = getMaxFromArrayOfArray_(aoaIds) + 1;
arrayOfData.unshift(newIDNumber);
ws.appendRow(arrayOfData);
return ContentService.createTextOutput("ok");
}
//return true if all ites are the same
function compareTwoArray_(arr1, arr2){
if (arr1.length !== arr2.length) return false;
for (let i = 0; i < arr1.length; i ++){
if (arr1[i] !== arr2[i]) return false;
}
return true;
}
function sendJSON_(jsonResponse){
return ContentService
.createTextOutput(JSON.stringify(jsonResponse))
.setMimeType(ContentService.MimeType.JSON);
}
//return the highest number / id
function getMaxFromArrayOfArray_(aoa){
let maxID = 0;
aoa.forEach(r => {
if (r[0] > maxID) maxID = r[0];
});
return maxID;
}
I need to send the data from inputs html page into object UserInfo in js-function and appendthem to spreadsheet but nothing happens.
If I put userInfo object in fetch like this "body: JSON.stringify(userInfo)" I get cor-mistake.
How can I organize that? thank you!
I have one notice: if I write in fetch "mode: 'no-cors'," then the data appends to spreadsheet, but return-info from doPost doesn't show. I need return info....((

Do you have to stringify your object to pass between server and client? I have this code in my html for getting data back from the server.
function succeed (res) {
alert('Begin succeed' );
console.log('Begin succeed' );
if (res == null) {
alert('Error: response was null!' );
console.log('Error: response was null!' );
return;
}
try {
alert(JSON.stringify(res) );
console.log(JSON.stringify(res) );
alert(res);
console.log(res);
} catch (err) {
alert('catch error trying to display res' );
console.log('catch error trying to display res' );
}
try {
document.getElementById('listDisplay').innerHTML = JSON.stringify(res);
} catch (err) {
alert('catch error trying to put res into textarea' );
console.log('catch error trying to put res into textarea' );
}
}
function fail (err) {
alert('Begin fail' );
console.log('Begin fail' );
alert('Error occurred', err);
console.log('Error occurred', err);
document.getElementById('listDisplay').innerHTML = 'ERROR: ' + err;
}

Related

React: Error-Message does not show up, while others do?

I have this simple Login-Form, in which I want to display an Error-Message, which contains Login tries (3 tries possible). Somehow, my one errormessage (loginTries) is not being displayed. Why?
My form is running the method handleSubmitAndStartTimer() when I submit it. You can find more comments and details below:
export const Login = () => {
const [errorMessages, setErrorMessages] = useState({});
const [loginFailCounter, setLoginFailCounter] = useState(2);
const [firstTimeSubmitted, setFirstTimeSubmitted] = useState(false);
const mockUserData = [
{
username: "user1",
password: "pass1",
istGesperrt: false,
},
];
const handleSubmitAndStartTimer = (event) => {
setFirstTimeSubmitted(true);
event.preventDefault();
var { benutzername, passwort } = document.forms[0];
const userData = mockUserDaten.find(
(user) => user.username === benutzername.value
);
// Compare user info
if (userData) {
if (!userData.istGesperrt) {
if (userData.password !== passwort.value) {
setLoginFailCounter(loginFailCounter - 1);
// THIS DOESNT WORK!
setErrorMessages({ name: "loginTries", message: errors.loginTries, });
// ALL THESE ERROR MESSAGES WORK!
// Invalid password
setErrorMessages({ name: "passwort", message: errors.passwort });
} else {
// Username not found
setErrorMessages({
name: "benutzername",
message: errors.benutzername,
});
}
} else {
setErrorMessages({
name: "userGesperrt",
message: errors.userGesperrt,
});
}
}
};
// This method is called to display to correct message
const renderErrorMessage = (name) =>
name === errorMessages.name && (
<div className="error">{errorMessages.message}</div>
);
const errors = {
benutzername: "invalid username",
passwort: "invalid password",
loginTries: loginFailCounter + " Tries possible!",
userGesperrt: "",
};
const renderForm = (
<div className="form">
<form onSubmit={handleSubmitAndStartTimer}>
<div className="input-container">
<label for="benutzername">Benutzername</label>
<input type="text" id="benutzername" name="benutzername" required />
{renderErrorMessage("benutzername")}
</div>
<div className="input-container">
<label for="passwort">Passwort</label>
<input type="passwort" id="passwort" name="passwort" required />
{renderErrorMessage("passwort")}
</div>
<div className="button-container">
<input type="submit" value="Log in" />
</div>
{renderErrorMessage("userGesperrt")}
// THIS MESSAGE ISNT BEING SHOWN!
{renderErrorMessage("loginTries")}
</form>
</div>
);
return (
<div className="app">
<div className="login-form">
<div className="title">Sign In</div>
{isSubmitted ? <div>User is successfully logged in</div> : renderForm}
</div>
</div>
);
};
export default Login;

Trying to create login with react, golang and mysql

this time I am creating a login for a dashboard, the problem is that I cannot identify what is failing, I have the following configuration
HANDLER CONTROLLER
func Login(username string, pass string) map[string]interface{} {
db := GetConnection()
user := &models.User{}
// sql := "SELECT * FROM users WHERE username'" + user.Username + "'and password ='" + user.Password + "'"
if db.Where("username = ?", username).First(&user).RecordNotFound() {
return map[string]interface{}{"message": "Usuario no encontrado"}
}
passErr := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(pass))
if passErr == bcrypt.ErrMismatchedHashAndPassword && passErr != nil {
return map[string]interface{}{"mesagge": "Usuario o contraseña incorrectos"}
}
// buscar cuenta usuario
accounts := []models.ResponseAccount{}
db.Table("accounts").Select("id, name").Where("user_id = ?", user.ID).Scan(&accounts)
// Configuración del response
responseUser := &models.ResponseUser{
ID: user.ID,
Username: user.Username,
Accounts: accounts,
}
defer db.Close()
fmt.Println(responseUser)
//Entrada token
tokenContent := jwt.MapClaims{
"user_id": user.ID,
"expiry": time.Now().Add(time.Minute ^ 60).Unix(),
}
jwtToken := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tokenContent)
token, err := jwtToken.SignedString([]byte("TokenPassword"))
HandleErr(err)
var response = map[string]interface{}{"Message": "Bienvenido"}
response["jwt"] = token
response["data"] = responseUser
return response
}
AXIOS CONFIG
import axios from "axios";
export class AdminService {
baseUrl = "http://localhost:3001/persona/api/";
async login() {
const res = await axios.post(this.baseUrl + "login");
return res.data;
}
}
export default new AdminService();
INDEX LOGIN CONFIG
class Login extends React.Component {
state = {
form: {
"username": "",
"password": ""
},
error: false,
errormsg: ""
}
manageChange = async (e) => {
this.setState({
form: {
...this.state.form,
[e.target.name]: e.target.value,
}
})
console.log(this.state.form)
}
handleClick = (e) => {
e.preventDefault();
AdminService.login(this.state.form).then((response) => {
console.log(response)
if (response.data.status === 200) {
this.props.history.push('/dashboard');
}
else {
this.setState({
error: true,
errormsg: response.data.message
})
}
})
}
render() {
return (
<React.Fragment>
<section >
<div class="container" >
<div class="top"></div>
<div class="bottom"></div>
<div class="center">
<img src={LogoIndex} id='logo-df' />
<form >
<input placeholder="Usuario" name="username" type="text" onChange={this.manageChange} />
<input placeholder="Contraseña" name="password" type="password" onChange={this.manageChange} />
<button onClick={this.handleClick} type='submit' className='corner-button' >Entrar</button>
</form>
</div>
</div>
</section>
</React.Fragment>
)
}
}
I've tried to do other configurations, but I can't go any further, I followed some guides from platforms documentation and I don't understand what it can be

Can I put HTML code in string value which I send Google Firebase Cloud Database in React?

I am using React. I am sending and pulling string data from Google Firebase Cloud Database. I want to put HTML code in my string value and I want the browser to implement it.
For example; I sent a string data like this:
lorem ipsum dolor <br> sit amet <ul><li>item1</li><li><item2></li><ul>
And I pulled like this
<div>{data.description}</div>
The result is a string in p tag:
lorem ipsum dolor <br> sit amet <ul><li>item1</li><item2><ul>
But I want to browser implement html codes in string data. Like this
lorem ipsum dolor sit amet item1item2
Can I do that?
If it is neccesary this is my sending code in React
function Lessons({ language }) {
const [lesson, setLesson] = useState({
id: "",
topic: "",
head: "",
description: "",
image: "",
});
const [disabled, setDisabled] = useState(true);
const [progres, setProgres] = useState(0);
const [imageUrl, setImageUrl] = useState("");
function handleChange(e) {
lesson[e.target.id] = e.target.value;
setLesson({ ...lesson, lesson });
if (
lesson.id !== "" &&
imageUrl !== "" &&
lesson.description !== "" &&
lesson.head !== ""
) {
setDisabled(false);
} else {
setDisabled(true);
}
}
const imageHandler = (e) => {
e.preventDefault();
const image = e.target[0].files[0];
uploadImages(image);
};
const uploadImages = (image) => {
const storageRefLes = ref(storage, `/lesAndEx/${image.name}`);
const uploadTask = uploadBytesResumable(storageRefLes, image);
uploadTask.on(
"state_changed",
(snapshot) => {
const prog = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgres(prog);
},
(err) => console.log(err),
() => {
getDownloadURL(uploadTask.snapshot.ref).then((url) =>
setImageUrl(url, imageUrl)
);
}
);
};
const add = async (event) => {
event.preventDefault();
const newTopic = lesson.topic;
switch (language) {
case "English":
await setDoc(doc(db, "lessons-data-" + newTopic, lesson.id), {
head: lesson.head,
image: imageUrl,
description: lesson.description,
});
break;
case "Dutch":
await setDoc(doc(db, "lessons-data-Dutch-" + newTopic, lesson.id), {
head: lesson.head,
image: imageUrl,
description: lesson.description,
});
break;
case "Turkish":
await setDoc(doc(db, "lessons-data-Turkish-" + newTopic, lesson.id), {
head: lesson.head,
image: imageUrl,
description: lesson.description,
});
break;
}
setLesson({
id: "",
topic: "",
head: "",
image: "",
description: "",
});
setImageUrl("");
setDisabled(true);
setProgres(0);
};
return (
<div className="bigContainer">
<h1>Lessons</h1>
<h2>Language: {language}</h2>
<div>
<div className="topicImageLoader">
<form onSubmit={imageHandler}>
<input type="file"></input>
<button type="submit">Upload</button>
</form>
<h2>Uploaded {progres} %</h2>
</div>
<div className="topAndExLabels">
<div>
<label for="id">
Lesson Id
<input
required
type="text"
id="id"
value={lesson.id}
onChange={handleChange}
placeholder="Id"
></input>
</label>
</div>
<div>
<label for="topic">
Lesson Topic
<input
required
type="text"
id="topic"
value={lesson.topic}
onChange={handleChange}
placeholder="Write exactly"
></input>
</label>
<label for="image">
Lesson Image
<input
required
disabled
type="url"
id="image"
value={imageUrl}
onChange={handleChange}
placeholder="imageUrl"
></input>
</label>
</div>
<div>
<label for="head">
Lesson Head
<input
required
type="text"
id="head"
value={lesson.head}
onChange={handleChange}
placeholder="head"
></input>
</label>
<div>
<div className="textAreaArea">Description</div>
<textarea
className="textAreaArea"
required
rows="8"
id="description"
value={lesson.description}
onChange={handleChange}
placeholder="lesson"
></textarea>
</div>
</div>
</div>
<div className="topAddButtonCont">
<button disabled={disabled} onClick={add}>
ekle
</button>
</div>
</div>
</div>
);
}
export default Lessons;
And this is my pulling code
function LessonPage() {
const [lessons, setLessons] = useState([]);
const [current, setCurrent] = useState(0);
const length = lessons.length;
let topicName = useLocation();
const nextSlide = () => {
setCurrent(current === length - 1 ? 0 : current + 1);
};
const prevSlide = () => {
setCurrent(current === 0 ? length - 1 : current - 1);
};
useEffect(() => {
onSnapshot(
collection(db, "lessons-data-" + topicName.state.state),
(snapshot) =>
setLessons(
snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
)
);
console.log(topicName.state.state);
}, []);
return (
<div className="slideBody">
<div className="mainSlide">
<FaArrowAltCircleLeft className="left-arrow" onClick={prevSlide} />
<FaArrowAltCircleRight className="right-arrow" onClick={nextSlide} />
{lessons.map(({ id, data }, index) => (
<div className={index === current ? "data active" : "data"} key={id}>
{index === current && (
<div className="slide">
<div className="dataHeadLesson">{data.head}</div>
<div className="dataImageLesson">
<img src={data.image}></img>
</div>
<div className="dataDesc">{data.description}</div>
</div>
)}
</div>
))}
</div>
</div>
);
}
export default LessonPage;
If I understand your querstion correctly you are receiving an html that you want to display using react JSX
take a look at this https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
Thx to Ilias Aboubeker. I fix the code like this and it works!
<div className="dataDesc" dangerouslySetInnerHTML={{ __html: data.description }}></div>

How to populate form html with json data from ws, using Typescript

I don't understand how to populate form when I get all data form ws.
I want to populate form from my function productGetAll()
my product.service
public productGetAll(): Observable<Product[]> {
let headers = new Headers();
headers.append('x-access-token', this.auth.getCurrentUser().token);
return this.http.get(Api.getUrl(Api.URLS.productGetAll), {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 1) {
this.auth.logout();
} else {
return res.StatusDescription.map(prod => {
return new Product(prod);
});
}
});
}
This function productGetAll(){} I call in component product.ts like this code:
public prod: Product[];
this.ws.productGetAll().subscribe(
prod=> {
this.prod= prod;
}
);
This code is form that I want to populate
this.productForm = this.fb.group({
'active': new FormControl('', Validators.required),
'name': new FormControl('', Validators.required)
});
My html code:
<form [formGroup]="productForm ">
<mat-slide-toggle formControlName="active" id="active" (change)="onChange($event)" [(ngModel)]="devicee[i]" (click)="onActiveHomeboxP(item.homeboxpackage_id)">
</mat-slide-toggle>{{device}}
<div class="row">
<div class="input-field col s12">
<input formControlName="name" id="name" type="text">
</div>
</div>
</form>

How do I fill in multiple html elements with data from a JSON string?

Here is the code I'm working with:
'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>
<script type="text/javascript" src='http://martialparks.com/wp-content/themes/blankslate/js/gamesparks-rt.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/gamesparks.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/gamesparks-functions.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/hmac-sha256.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/parse.js'></script>
</head>
<body>
<br />
<br />
<br />
<input id="apiKey" type="hidden" value="A319082inSk2"/>
<input id="apiSecret" type="hidden" value="BNuYLYZAoDZDZyh1F7tbR8BMTiqeJbWt"/>
apiCredential<input id="apiCredential"/>
User Name<input id="username"/>
Password<input id="password"/>
<body onload="init()">
<button onClick='gamesparks.registrationRequest("testuser", "testuser", "testuser", registerResponse)'>Register</button>
<button onClick='gamesparks.authenticationRequest("testuser", "testuser", loginResponse)'>Login</button>
<button onClick='gamesparks.accountDetailsRequest(accountDetailsResponse)'>Account Details</button>
<button onClick='customEvent()'>Custom Event</button>
<button onClick='testRT()'>Test RT</button>
<i>Special thanks to the awesome team at GameSparks!</i>
<div id="messages"></div>
<br />
<br />
</body>
User Name
<text id="UserName"/>
<br />
Coins
<text id="Coins"/>
<br />
Exp
<text id="Exp"/>
<br />
Leader Points
<text id="LeadP"/>
<br />
Hero Points
<text id="HeroP"/>
<div id="UserName" style="color: blue;"></div>
<div id="Coins" style="color: red;"></div>
<div id="Exp" style="color: green;"></div>
<div id="LeadP" style="color: hotpink;"></div>
<div id="HeroP" style="color: yellow;"></div>
<script type="text/javascript">
//Create a gamesparks object to be used
var gamesparks = new GameSparks();
//Initialse the SDK
function init() {
gamesparks.initPreview({
key: document.getElementById('apiKey').value,
secret: document.getElementById('apiSecret').value,
credential: document.getElementById('apiCredential').value,
onNonce: onNonce,
onInit: onInit,
onMessage: onMessage,
logger: console.log,
});
}
//Callback function to hmac sha256 a nonce with the secret. It's assumed you will have your own method of securing the secret;
function onNonce(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, document.getElementById('apiSecret').value));
}
//Callback to handle when the SDK is initialised and ready to go
function onInit() {
console.log("Initialised");
}
//Callback to handle async messages from the gamesparks platform
function onMessage(message) {
console.log("onMessage");
}
//Response handler examples
function registerResponse(response) {
console.log(JSON.stringify(response));
}
function loginResponse(response) {
console.log(JSON.stringify(response));
}
function accountDetailsResponse(response) {
console.log (JSON.stringify(response));//logs the string to console
document.getElementById("UserName").innerHTML = (response.displayName);
document.getElementById("Coins").innerHTML = (response.currencies.Coins);
document.getElementById("Exp").innerHTML = (response.currencies.Exp);
document.getElementById("LeadP").innerHTML = (response.currencies.LeadP);
document.getElementById("HeroP").innerHTML = (response.currencies.HeroP); //returns value of name from string. I've tried doing each line with semicolons at the end, and all in a group with commas separating them. Both just give me the first variable and delete the rest.
}
function customEvent() {
gamesparks.sendWithData(
"LogEventRequest",
{
eventKey : "FIRST_EVENT",
NUMBER_ATTR : 123,
STRING_ATTR : "this is a string",
JSON_ATTR : {key1 : 12, key2 : "abc"}
},
function(response){console.log(JSON.stringify(response));}
);
}
var apiKey = "2974660weiMa";
var apiSecret = "p5pFVnohi5eWPYETb4aPgeMLtd95bjfJ";
var myTimer = null;
var myRTSession = function() {};
var numCycles = 0;
myRTSession.started = false;
myRTSession.onPlayerConnectCB = null;
myRTSession.onPlayerDisconnectCB = null;
myRTSession.onReadyCB = null;
myRTSession.onPacketCB = null;
myRTSession.session = null;
myRTSession.start = function(connectToken, host, port) {
var index = host.indexOf(":");
var theHost;
if (index > 0) {
theHost = host.slice(0, index);
} else {
theHost = host;
}
console.log(theHost + " : " + port);
myRTSession.session = GameSparksRT.getSession(connectToken, theHost, port, myRTSession);
if (myRTSession.session != null) {
myRTSession.started = true;
myRTSession.session.start();
} else {
myRTSession.started = false;
}
};
myRTSession.stop = function() {
myRTSession.started = false;
if (myRTSession.session != null) {
myRTSession.session.stop();
}
};
myRTSession.log = function(message) {
var peers = "|";
for (var k in myRTSession.session.activePeers) {
peers = peers + myRTSession.session.activePeers[k] + "|";
}
console.log(myRTSession.session.peerId + ": " + message + " peers:" + peers);
};
myRTSession.onPlayerConnect = function(peerId) {
myRTSession.log(" OnPlayerConnect:" + peerId);
if (myRTSession.onPlayerConnectCB != null) {
myRTSession.onPlayerConnectCB(peerId);
}
};
myRTSession.onPlayerDisconnect = function(peerId) {
myRTSession.log(" OnPlayerDisconnect:" + peerId);
if (myRTSession.onPlayerDisconnectCB != null) {
myRTSession.onPlayerDisconnectCB(peerId);
}
};
myRTSession.onReady = function(ready) {
myRTSession.log(" OnReady:" + ready.toString());
if (myRTSession.onReadyCB != null) {
myRTSession.onReadyCB(ready);
}
};
myRTSession.onPacket = function(packet) {
myRTSession.log(" OnPacket:" + packet.toString());
if (myRTSession.onPacketCB != null) {
myRTSession.onPacketCB(packet);
}
};
function testRT() {
myRTSession.stop();
gamesparks.initPreview({
key: apiKey,
secret: apiSecret,
credential: "",
onNonce: onNonceRT,
onInit: onInitRT,
onMessage: onMessageRT,
logger: console.log,
});
}
function onNonceRT(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, apiSecret));
}
function onInitRT() {
console.log("Initialised");
gamesparks.deviceAuthenticationRequest((Math.floor(Math.random() * (999 - 1)) + 1).toString(), null, null, "js", null, null, function(response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
sendMatchmakingRequest();
}
});
}
//Callback to handle async messages from the gamesparks platform
function onMessageRT(message) {
//console.log("message " + JSON.stringify(message));
if (message["#class"] === ".MatchFoundMessage") {
var accessToken = message["accessToken"];
var host = message["host"];
var port = message["port"];
myRTSession.stop();
if (myTimer) {
clearTimeout(myTimer);
}
myTimer = setInterval(mainRTLoop, 10);
myRTSession.start(accessToken, host, port);
} else if (message["#class"] === ".MatchNotFoundMessage") {
console.log("MATCH NOT FOUND");
sendMatchmakingRequest();
}
}
function sendMatchmakingRequest() {
gamesparks.sendWithData("MatchmakingRequest",
{
skill: 1,
matchShortCode: "Match_STD"
},
function(response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
console.log("Match OK...");
}
}
);
}
function mainRTLoop() {
if (myRTSession.started) {
myRTSession.session.update();
var data = RTData.get();
data.setLong(1, numCycles);
myRTSession.session.sendRTData(1, GameSparksRT.deliveryIntent.RELIABLE, data, []);
numCycles ++;
}
}
</script>
</html>'
Obviously, I'm trying to fill in some html elements with data I get from a string. Problem is, when I use this function, it fills in the first element ONLY, and totally wipes the others from view. So it returns "testuser" for "UserName", and all of the other html elements disappear! I want it to display ALL of the data!
Did I understand correctly, that only your first innerHTML is working and the others aren't?
Very quick and dirty but functioning example:
<script>
function accountDetailsResponse(response) {
console.log(JSON.stringify(response));//logs the string to console
document.getElementById("UserName").innerHTML = response.displayName, document.getElementById("Coins").innerHTML = response.currencies.Coins, document.getElementById("Exp").innerHTML = response.currencies.Exp, document.getElementById("LeadP").innerHTML = response.currencies.LeadP, document.getElementById("HeroP").innerHTML = response.currencies.HeroP;
}
window.onload = function() {
response = {
displayName: 'A user',
currencies: {
Coins: 'A coin',
Exp: 'A exp',
LeadP: 'A lead p',
HeroP: 'A hero p',
},
};
accountDetailsResponse(response);
}
</script>
<body>
<div id="UserName" style="color: blue;"></div>
<div id="Coins" style="color: red;"></div>
<div id="Exp" style="color: green;"></div>
<div id="LeadP" style="color: hotpink;"></div>
<div id="HeroP" style="color: yellow;"></div>
</body>
What's not working?
EDIT:
I'm not really sure what you're trying to do with the Account Detail stuff, but I rewrote it in a way, where at least the innerHTML part works:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html"
xmlns="http://www.w3.org/1999/html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript"
src='http://martialparks.com/wp-content/themes/blankslate/js/gamesparks-rt.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/gamesparks.js'></script>
<script type='text/javascript'
src='http://martialparks.com/wp-content/themes/blankslate/js/gamesparks-functions.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/hmac-sha256.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/parse.js'></script>
</head>
<body onload="init()">
<br/>
<br/>
<br/>
<form>
<input id="apiKey" type="hidden" value="A319082inSk2"/>
<input id="apiSecret" type="hidden" value="BNuYLYZAoDZDZyh1F7tbR8BMTiqeJbWt"/>
<label for="apiCredential">Api Credential</label><input id="apiCredential"/>
<label for="username">User Name</label><input id="username"/>
<label for="password">Password</label><input id="password"/>
<input type="button" onClick='gamesparks.registrationRequest("testuser", "testuser", "testuser", registerResponse)' value="Register" />
<input type="button" onClick='gamesparks.authenticationRequest("testuser", "testuser", loginResponse)' value="Login" />
<input type="button" onClick='accountDetailsResponseCreator()' value="Account Details" />
<input type="button" onClick='customEvent()' value="Custom Event" />
<input type="button" onClick='testRT()' value="Test RT" />
<i>Special thanks to the awesome team at GameSparks!</i>
<div id="messages"></div>
<br/>
<br/>
</form>
User Name
<div id="DisplayName" style="color: blue;"></div>
Coins
<div id="Coins" style="color: red;"></div>
Exp
<div id="Exp" style="color: green;"></div>
Leader Points
<div id="LeadP" style="color: hotpink;"></div>
Hero Points
<div id="HeroP" style="color: yellow;"></div>
<script type="text/javascript">
//Create a gamesparks object to be used
var gamesparks = new GameSparks();
//Initialse the SDK
function init() {
gamesparks.initPreview({
key: document.getElementById('apiKey').value,
secret: document.getElementById('apiSecret').value,
credential: document.getElementById('apiCredential').value,
onNonce: onNonce,
onInit: onInit,
onMessage: onMessage,
logger: console.log,
});
}
function accountDetailsResponseCreator() {
var reponse = {
displayName: 'A user',
currencies: {Coins: 'A coin', Exp: 'A exp', LeadP: 'A lead p', HeroP: 'A hero p'}
}
accountDetailsResponse(reponse)
}
//Callback function to hmac sha256 a nonce with the secret. It's assumed you will have your own method of securing the secret;
function onNonce(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, document.getElementById('apiSecret').value));
}
//Callback to handle when the SDK is initialised and ready to go
function onInit() {
console.log("Initialised");
}
//Callback to handle async messages from the gamesparks platform
function onMessage(message) {
console.log("onMessage");
}
//Response handler examples
function registerResponse(response) {
console.log(JSON.stringify(response));
}
function loginResponse(response) {
console.log(JSON.stringify(response));
}
function accountDetailsResponse(response) {
console.log(JSON.stringify(response));//logs the string to console
document.getElementById("DisplayName").innerHTML = (response.displayName);
document.getElementById("Coins").innerHTML = (response.currencies.Coins);
document.getElementById("Exp").innerHTML = (response.currencies.Exp);
document.getElementById("LeadP").innerHTML = (response.currencies.LeadP);
document.getElementById("HeroP").innerHTML = (response.currencies.HeroP); //returns value of name from string. I've tried doing each line with semicolons at the end, and all in a group with commas separating them. Both just give me the first variable and delete the rest.
}
function customEvent() {
gamesparks.sendWithData(
"LogEventRequest",
{
eventKey: "FIRST_EVENT",
NUMBER_ATTR: 123,
STRING_ATTR: "this is a string",
JSON_ATTR: {key1: 12, key2: "abc"}
},
function (response) {
console.log(JSON.stringify(response));
}
);
}
var apiKey = "2974660weiMa";
var apiSecret = "p5pFVnohi5eWPYETb4aPgeMLtd95bjfJ";
var myTimer = null;
var myRTSession = function () {
};
var numCycles = 0;
myRTSession.started = false;
myRTSession.onPlayerConnectCB = null;
myRTSession.onPlayerDisconnectCB = null;
myRTSession.onReadyCB = null;
myRTSession.onPacketCB = null;
myRTSession.session = null;
myRTSession.start = function (connectToken, host, port) {
var index = host.indexOf(":");
var theHost;
if (index > 0) {
theHost = host.slice(0, index);
} else {
theHost = host;
}
console.log(theHost + " : " + port);
myRTSession.session = GameSparksRT.getSession(connectToken, theHost, port, myRTSession);
if (myRTSession.session != null) {
myRTSession.started = true;
myRTSession.session.start();
} else {
myRTSession.started = false;
}
};
myRTSession.stop = function () {
myRTSession.started = false;
if (myRTSession.session != null) {
myRTSession.session.stop();
}
};
myRTSession.log = function (message) {
var peers = "|";
for (var k in myRTSession.session.activePeers) {
peers = peers + myRTSession.session.activePeers[k] + "|";
}
console.log(myRTSession.session.peerId + ": " + message + " peers:" + peers);
};
myRTSession.onPlayerConnect = function (peerId) {
myRTSession.log(" OnPlayerConnect:" + peerId);
if (myRTSession.onPlayerConnectCB != null) {
myRTSession.onPlayerConnectCB(peerId);
}
};
myRTSession.onPlayerDisconnect = function (peerId) {
myRTSession.log(" OnPlayerDisconnect:" + peerId);
if (myRTSession.onPlayerDisconnectCB != null) {
myRTSession.onPlayerDisconnectCB(peerId);
}
};
myRTSession.onReady = function (ready) {
myRTSession.log(" OnReady:" + ready.toString());
if (myRTSession.onReadyCB != null) {
myRTSession.onReadyCB(ready);
}
};
myRTSession.onPacket = function (packet) {
myRTSession.log(" OnPacket:" + packet.toString());
if (myRTSession.onPacketCB != null) {
myRTSession.onPacketCB(packet);
}
};
function testRT() {
myRTSession.stop();
gamesparks.initPreview({
key: apiKey,
secret: apiSecret,
credential: "",
onNonce: onNonceRT,
onInit: onInitRT,
onMessage: onMessageRT,
logger: console.log,
});
}
function onNonceRT(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, apiSecret));
}
function onInitRT() {
console.log("Initialised");
gamesparks.deviceAuthenticationRequest((Math.floor(Math.random() * (999 - 1)) + 1).toString(), null, null, "js", null, null, function (response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
sendMatchmakingRequest();
}
});
}
//Callback to handle async messages from the gamesparks platform
function onMessageRT(message) {
//console.log("message " + JSON.stringify(message));
if (message["#class"] === ".MatchFoundMessage") {
var accessToken = message["accessToken"];
var host = message["host"];
var port = message["port"];
myRTSession.stop();
if (myTimer) {
clearTimeout(myTimer);
}
myTimer = setInterval(mainRTLoop, 10);
myRTSession.start(accessToken, host, port);
} else if (message["#class"] === ".MatchNotFoundMessage") {
console.log("MATCH NOT FOUND");
sendMatchmakingRequest();
}
}
function sendMatchmakingRequest() {
gamesparks.sendWithData("MatchmakingRequest",
{
skill: 1,
matchShortCode: "Match_STD"
},
function (response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
console.log("Match OK...");
}
}
);
}
function mainRTLoop() {
if (myRTSession.started) {
myRTSession.session.update();
var data = RTData.get();
data.setLong(1, numCycles);
myRTSession.session.sendRTData(1, GameSparksRT.deliveryIntent.RELIABLE, data, []);
numCycles++;
}
}
</script>
</body>
</html>
Hope this helps.
<?php /**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div id="main">
*
*/ ?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<script type="text/javascript"
src='http://martialparks.com/wp-content/themes/js/gamesparks-rt.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/gamesparks.js'></script>
<script type='text/javascript'
src='http://martialparks.com/wp-content/themes/js/gamesparks-functions.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/hmac-sha256.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/parse.js'></script>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<?php
wp_head();
?>
</head>
<body <?php body_class() ?>>
<!--Start Header Wrapper-->
<div class="header_wrapper">
<div class="header">
<!--Start Container-->
<div class="container_24">
<div class="grid_24">
<div class="logo"> <a href="<?php echo esc_url(home_url()); ?>"><img src="<?php if (business_directory_get_option('business_directory_logo') != '') { ?><?php echo esc_url(business_directory_get_option('business_directory_logo')); ?><?php
} else {
echo esc_url(get_template_directory_uri() . '/images/logo.png');
}
?>" alt="<?php bloginfo('name'); ?>" /></a></div>
</div>
<div class="clear"></div>
</div>
<!--End Container-->
<div class="clear"></div>
</div>
<div class="clear"></div>
<!--Start Menu Wrapper-->
<div class="menu_wrapper">
<div class="top_arc"></div>
<div class="menu-container">
<div class="container_24">
<div class="grid_24">
<?php business_directory_nav(); ?>
</div>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="bottom_arc"></div>
</div>
<!--End Container-->
<div class="clear"></div>
</div>
<!--End Header Wrapper-->
<div class="clear"></div>
<div class="wrapper">
<!--Start Container-->
<div class="container_24">
<div class="grid_24">
<body onload="init()">
<br/>
<br/>
<br/>
<form>
<input id="apiKey" type="hidden" value="A319082inSk2"/>
<input id="apiSecret" type="hidden" value="BNuYLYZAoDZDZyh1F7tbR8BMTiqeJbWt"/>
<label for="apiCredential">Api Credential</label><input id="apiCredential"/>
<label for="username">User Name</label><input id="username"/>
<label for="password">Password</label><input id="password"/>
<button onClick='gamesparks.registrationRequest("testuser", "testuser", "testuser", registerResponse)'>Register</button>
<button onClick='gamesparks.authenticationRequest("testuser", "testuser", loginResponse)'>Login</button>
<button onClick='gamesparks.accountDetailsRequest(accountDetailsResponse)'>Account Details</button>
<button onClick='customEvent()'>Custom Event</button>
<button onClick='testRT()'>Test RT</button>
<i>Special thanks to the awesome team at GameSparks!</i>
<div id="messages"></div>
<br/>
<br/>
</form>
User Name
<div id="displayName" style="color: blue;"></div>
Coins
<div id="Coins" style="color: red;"></div>
Exp
<div id="Exp" style="color: green;"></div>
Leader Points
<div id="LeadP" style="color: darkgreen;"></div>
Hero Points
<div id="HeroP" style="color: purple;"></div>
<script type="text/javascript">
//Create a gamesparks object to be used
var gamesparks = new GameSparks();
//Initialse the SDK
function init() {
gamesparks.initPreview({
key: document.getElementById('apiKey').value,
secret: document.getElementById('apiSecret').value,
credential: document.getElementById('apiCredential').value,
onNonce: onNonce,
onInit: onInit,
onMessage: onMessage,
logger: console.log,
});
}
function accountDetailsResponseCreator() {
var response = {
displayName: 'A User',
currencies: {Coins: 'A coin', Exp: 'A exp', LeadP: 'A lead p', HeroP: 'A hero p'}
}
accountDetailsResponse(response)
}
//Callback function to hmac sha256 a nonce with the secret. It's assumed you will have your own method of securing the secret;
function onNonce(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, document.getElementById('apiSecret').value));
}
//Callback to handle when the SDK is initialised and ready to go
function onInit() {
console.log("Initialised");
}
//Callback to handle async messages from the gamesparks platform
function onMessage(message) {
console.log("onMessage");
}
//Response handler examples
function registerResponse(response) {
console.log(JSON.stringify(response));
}
function loginResponse(response) {
console.log(JSON.stringify(response));
}
function accountDetailsResponse(response) {
console.log (JSON.stringify(response));//logs the string to console
document.getElementById("displayName").innerHTML = (response.displayName);
document.getElementById("Coins").innerHTML = (response.currencies.Coins);
document.getElementById("Exp").innerHTML = (response.currencies.Exp);
document.getElementById("LeadP").innerHTML = (response.currencies.LeadP);
document.getElementById("HeroP").innerHTML = (response.currencies.HeroP); //returns value of name from string. I've tried doing each line with semicolons at the end, and all in a group with commas separating them. Both just give me the first variable and delete the rest.
}
function customEvent() {
gamesparks.sendWithData(
"LogEventRequest",
{
eventKey: "FIRST_EVENT",
NUMBER_ATTR: 123,
STRING_ATTR: "this is a string",
JSON_ATTR: {key1: 12, key2: "abc"}
},
function (response) {
console.log(JSON.stringify(response));
}
);
}
var apiKey = "2974660weiMa";
var apiSecret = "p5pFVnohi5eWPYETb4aPgeMLtd95bjfJ";
var myTimer = null;
var myRTSession = function () {
};
var numCycles = 0;
myRTSession.started = false;
myRTSession.onPlayerConnectCB = null;
myRTSession.onPlayerDisconnectCB = null;
myRTSession.onReadyCB = null;
myRTSession.onPacketCB = null;
myRTSession.session = null;
myRTSession.start = function (connectToken, host, port) {
var index = host.indexOf(":");
var theHost;
if (index > 0) {
theHost = host.slice(0, index);
} else {
theHost = host;
}
console.log(theHost + " : " + port);
myRTSession.session = GameSparksRT.getSession(connectToken, theHost, port, myRTSession);
if (myRTSession.session != null) {
myRTSession.started = true;
myRTSession.session.start();
} else {
myRTSession.started = false;
}
};
myRTSession.stop = function () {
myRTSession.started = false;
if (myRTSession.session != null) {
myRTSession.session.stop();
}
};
myRTSession.log = function (message) {
var peers = "|";
for (var k in myRTSession.session.activePeers) {
peers = peers + myRTSession.session.activePeers[k] + "|";
}
console.log(myRTSession.session.peerId + ": " + message + " peers:" + peers);
};
myRTSession.onPlayerConnect = function (peerId) {
myRTSession.log(" OnPlayerConnect:" + peerId);
if (myRTSession.onPlayerConnectCB != null) {
myRTSession.onPlayerConnectCB(peerId);
}
};
myRTSession.onPlayerDisconnect = function (peerId) {
myRTSession.log(" OnPlayerDisconnect:" + peerId);
if (myRTSession.onPlayerDisconnectCB != null) {
myRTSession.onPlayerDisconnectCB(peerId);
}
};
myRTSession.onReady = function (ready) {
myRTSession.log(" OnReady:" + ready.toString());
if (myRTSession.onReadyCB != null) {
myRTSession.onReadyCB(ready);
}
};
myRTSession.onPacket = function (packet) {
myRTSession.log(" OnPacket:" + packet.toString());
if (myRTSession.onPacketCB != null) {
myRTSession.onPacketCB(packet);
}
};
function testRT() {
myRTSession.stop();
gamesparks.initPreview({
key: apiKey,
secret: apiSecret,
credential: "",
onNonce: onNonceRT,
onInit: onInitRT,
onMessage: onMessageRT,
logger: console.log,
});
}
function onNonceRT(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, apiSecret));
}
function onInitRT() {
console.log("Initialised");
gamesparks.deviceAuthenticationRequest((Math.floor(Math.random() * (999 - 1)) + 1).toString(), null, null, "js", null, null, function (response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
sendMatchmakingRequest();
}
});
}
//Callback to handle async messages from the gamesparks platform
function onMessageRT(message) {
//console.log("message " + JSON.stringify(message));
if (message["#class"] === ".MatchFoundMessage") {
var accessToken = message["accessToken"];
var host = message["host"];
var port = message["port"];
myRTSession.stop();
if (myTimer) {
clearTimeout(myTimer);
}
myTimer = setInterval(mainRTLoop, 10);
myRTSession.start(accessToken, host, port);
} else if (message["#class"] === ".MatchNotFoundMessage") {
console.log("MATCH NOT FOUND");
sendMatchmakingRequest();
}
}
function sendMatchmakingRequest() {
gamesparks.sendWithData("MatchmakingRequest",
{
skill: 1,
matchShortCode: "Match_STD"
},
function (response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
console.log("Match OK...");
}
}
);
}
function mainRTLoop() {
if (myRTSession.started) {
myRTSession.session.update();
var data = RTData.get();
data.setLong(1, numCycles);
myRTSession.session.sendRTData(1, GameSparksRT.deliveryIntent.RELIABLE, data, []);
numCycles++;
}
}
</script>
</body>
</html>
WOW! What a crunch for a new month-old coder. So special thanks to EMAZZOTTA who created a code that gave me the building blocks I could manipualte. Again, had I provided all the information, EMAZZOTTA would have been able to fix it immediately.
So my code is different from Zot's in several ways. I had to correct a syntax where they left out the reference to the function "gamesparks" before accountdetailsrequest. I also have the code intermixed with a new theme (no relevance.) I also removed the function E added, that populated "A Coin, A Exp", etc. It was redundant. The main kicker that got this one is this: In order to populate multiple html elements, the elements have to be formatted correctly. Emazzotta had the foresight to use