0

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!

2 Answers2

0

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.

emazzotta
  • 1,499
  • 2
  • 19
  • 23
  • I've tried that exactly. Same result. The first innerHTML "UserName" displays instantly and accurately. But all of other elements disappear. I also get a console error that reads: "Uncaught TypeError: Cannot set property 'innerHTML' of null" – Velocity Martial Arts Oct 24 '17 at 21:05
  • Ah, I see! Try setting response and calling accountDetailsReponse inside `window.onload = function() { /* my code here */ }` the problem is that you're likely calling `accountDetailsReponse` before setting `response`. See: https://stackoverflow.com/questions/11163060/cannot-set-property-innerhtml-of-null – emazzotta Oct 24 '17 at 21:09
  • I tried two things: I moved the html elements from header to body. No effect. I also tried your suggestion, emazzotta. What happens is it returns "undefined" for username, and still deletes my html elements! It was a step backwards! – Velocity Martial Arts Oct 24 '17 at 21:20
  • I should also add this: The "accountDetailsResponse" function triggers after an "onclick" in the html above. – Velocity Martial Arts Oct 24 '17 at 21:22
  • Please add the full code to your question, so it's easier to spot the issue. – emazzotta Oct 24 '17 at 21:26
  • Full code posted. I was in the middle of modifications, but functionally, it isn't any different than it was. – Velocity Martial Arts Oct 24 '17 at 21:37
  • I edited my post and made it working, not sure if it's what you're expecting though, since you were doing something with gamesparks before. – emazzotta Oct 24 '17 at 22:12
  • The code works, at least, none of the elements disappear. It does populate each field with "A Coin," "A whatever". I'm working through some code right now to figure out how to fix that. I have no clue. It looks like in your version, the elements' values should already equal what I parse from the string. – Velocity Martial Arts Oct 25 '17 at 21:07
  • I think the code I supplied fixes your problem, so I'd be glad if you could mark my answer as accepted. If you need more help, you can specify what you'd like to be done and I can try to help – emazzotta Oct 26 '17 at 07:26
  • Alas, it does not fix the problem. I was able to populate at least one element with data from the string. Your code (while preserving all the elements) populates NO data from the string. The initial question was how to fill multiple elements with data from a string, and technically, I've taken a step backward. However, I'm going to tinker with the code, and if I can make it function, I'll post the changes I made to it and answer my own question. However, if you beat me to it, I'll yield the victory to you. – Velocity Martial Arts Oct 26 '17 at 19:32
  • When you say "data from the string", then which string are you referring to? – emazzotta Oct 26 '17 at 19:40
  • Account Details Request. found at console.log JSON(stringify(response)) under account details request. – Velocity Martial Arts Oct 26 '17 at 20:20
0

<?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