Binding server connect variable inside Javascript

Hey @johnny.hajjar,

can you provide a specific example of what would you like to achieve?

Hi Teodor,

thank you for your quick response.

i’m using template monster to render large data sets into a pivot table.
https://jsfiddle.net/flexmonster/pz431qp5/

i need to be able to dynamically pass the json object , or jsonURL etc

var jsonData = {{jsonDS1.data}}

----original script------
var jsonData = [
{
“Color” : “green”,
“Country” : “Canada”,
“State” : “Ontario”,
“City” : “Toronto”,
“Price” : 174,
“Quantity” : 22
},
{
“Color” : “red”,
“Country” : “USA”,
“State” : “California”,
“City” : “Los Angeles”,
“Price” : 166,
“Quantity” : 19
}
];

hi Teodor,

was my use case explanation sufficient? :grinning:,

I really hope this is possible :slight_smile:

It is not possible to use the expressions like that in script and style tags. The expressions are evaluated after the DOM is loaded, the script and style tags are then already parsed by the browser. There are also no plans on making this possible in the future.

You can use data from the App Connect like var jsonData = dmx.parse('sonDS1.data'). You should call it after the data is loaded, it does not update like on the rest of the page. Best way is to create a javascript function with your code and do the parsing in there. Call the function on the load event of the server connect component.

Still trying to get somewhere with Tawk

Adding basic tawk is simple enough, just paste the JS in the body
However @updates question still remains problematic
I tried using Tawk_API.visitor = {} and spotted in the documentation that a secure hash is required based on the email address via the PHP function hash_hmac().
This led me to looking into sessions to see if i could access the email address that way
I have a security restrict names basr_security
within the server action i have a query (named query1) which returns fields FirstNames, LastNames, email and Applicant ID.
Everything OK so far
I then added the PHP line in the page var_dump($_SESSION);
This returned:
array(2) {
[“basr_securityId”]=>
int(16)
[“userdata”]=>
array(1) {
[0]=>
array(4) {
[“FirstNames”]=>
string(5) “Brian”
[“LastNames”]=>
string(7) “English”
[“email”]=>
string(22) "admin@hyperbytes.co.uk"
[“Applicant_ID”]=>
int(16)
}
}
}

This indicated the data returned by the query is also available as session variables?
However I have tried every variation to try and access those session variables and failed miserably
Anyone any ideas how to access the email session variable in PHP?
I have tried various variations on (many more tried,. not all listed
$_SESSION[“userdata.email”]
$_SESSION[“userdata[0].email”]
$_SESSION[“userdata.[0].email”]
$_SESSION[“basr_securityId.userdata.email”]
$_SESSION[“basr_security.userdata.email”]

Typical error message:
myaccount.php",“line”:47,“message”:“Undefined index: basr_securityId.userdata.[0].email”,“trace”:"#0 C:\bookastudentroom.com\public_html\users\myaccount.php(47): exception_error_handler(8, ‘Undefined index…’, ‘C:\\bookastudent…’, 47, Array)\n#1 {main}"}

Hi I solved for the moment setting up Tawkt.to chat starting with a form where people insert Name and email to start to chat (it is one of the default configurations).

Patrick gave me some suggestions but my knowledge of Javascript it is not so deep.

An extension would be nice :wink:

Seeing the php dump I think the session variable you want is $_SESSION["userdata"][0]["email"].

So in your script it would then become

<script type=“text/javascript”>
  var Tawk_API=Tawk_API||{};
  Tawk_API.visitor = {
    name : '<?php echo $_SESSION["userdata"][0]["FirstNames"] ?>',
    email : '<?php echo $_SESSION["userdata"][0]["email"] ?>'
  };
  var Tawk_LoadStart=new Date();
  // rest of the tawk.to widget code 
</script>

App Connect expressions in script blocks will not work, but PHP can be used inside the script blocks.

Thanks @patrick, another touch of your genius opens up so may new possibilities Never thought of doing it like that, so obvious now but hindsight is always perfect.:grinning:

Success, passing name and email to tawk!!

OK, here are the stages i used.

Firstly server connect,
Using the usual server restrict and then query for current user
The query finds details,of the current logged in user:


A session, userdata is created in globals and after the query a set session = queryname (in my case query1) is added

The fields i bind are ‘email’ and ‘FirstNames’ from query1 now also in the session ‘userdata’

tawk.to wants parameters containing the email to be encrypted so i opted to use sessions and PHP to add the parameters as I needed to use the PHP hash_hmac function to generate the hash

Now the following code was added to the body of the page.

    var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
    Tawk_API.onLoad = function(){
    Tawk_API.setAttributes({
        'name'  : '<?php echo $_SESSION["userdata"][0]["FirstNames"];?>',
        'email' : '<?php echo $_SESSION["userdata"][0]["email"];?>',
        'hash'  : '<?php echo hash_hmac("sha256",  $_SESSION["userdata"][0]["email"], "put-your-api-key-here"); ?>'
    }, function(error){});
}
    </script>


   
    
 And of course your own **tawk.io** connection script after

   <!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/5bcd7f2fb9993f2ada1518a5/default';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->

The parameters are passed to tawk.io on chat start
2 Likes

Ok this is perfect … thanks
How can I pass javascript result to app connect variable or input field.
Forexample :
Input field name is testinput and id is testinput

My script like this (just example )

var a = 2;
var b = 5;
c = a+b;

I can bind this result like

document.getElementById("testinput").value = xyz;
Or
 document.getElementById("testinput").setAttribute('value','My value');``

What is right way for bind value javascript to input value .

I want to use results in app connect

you can use jQuery like

$('#testinput').val('My value').change();

if not using jQuery it is a bit more difficicult, you need to trigger the change event on the input after changing it value.

var element = document.getElementById('testinput');
var event = new Event('change');
element.value = 'My value';
element.dispatchEvent(event);
2 Likes

Thank you very much @patrick and @Hyperbytes!!
This post is very important for all of us !!

2 Likes

Hi @Hyperbytes,
I followed your procedure and it work, passing the Identity to Tawk.to.

I got a strange thing: When user at first time load the page, the widget do not appear. I have to reload the page to make him appear and works properly.

Through the developers tools in Google Chrome I saw that when I load for first time the page it is like the Browser cut the end of the page, while after reloading it works perfectly.

Here the screenshot:

Any idea about this ?

thank you

Roberto

I will have a look tomorrow when I get in office. I don’t actually use Tawk so I am not that familiar with it, I just liked the challenge of making it work so I will have to look at their documentation 're time zones and restrictions. I suppose there is some sense in needing to know them in a world wide application

Thank you very much !

Sorry about delay, i don’t get that error however i think if you add the line into the head section of your page it may resolve the problem

<?php date_default_timezone_set('Europe/Stockholm'); ?>

Obviously changing it to your required timezone.

Thank you very much @Hyperbytes… I will try and let you know!!

Rather than start a new topic (unless you would prefer me to)
I too am struggling with setting a variable inside javascript.

I have a signature drawing in my database (JSON) e.g [{lx:20,ly:34,mx:20,my:34},{lx:21,ly:33,mx:20,my:34},…];

I return that value in serverconnnect and bind it to a variable
<dmx-value id="sig" dmx-bind:value="sig.value"></dmx-value>
If i place the variable on my page it shows the value correctly.

I then have this at the bottom within the body

    <script type="text/javascript">
    $(document).ready(function () {
      $('.sigPad').signaturePad({displayOnly:true}).regenerate(sig);
    });
      </script>

I need to set a variable ‘sig’ to the value of my JSON signature
var sig = [{lx:20,ly:34,mx:20,my:34},{lx:21,ly:33,mx:20,my:34},…];

I’ve tried the suggestions about, but can’t seem to get it to work.
Many thanks in advance.

Mim

I’ve even tried binding the value to a hidden input field and using
var sig = document.getElementById("mysig").value;
But that doesn’t seem to work either.