Dawid Adach
Dawid Adach

Reputation: 769

Client server javascript communication

I want to create 2 scripts, 1 for client 1 for server side.

I found snippet which allows call asyncrhonously js

<html>
<head>
</head>
<body>
<script>

(function() { 
    var projectId = "script";
    var protocol = ('https:' == document.location.protocol ? 
    'https://' : 'http://');
    var scriptTag = document.createElement('script');
    scriptTag.type = 'text/javascript';
    scriptTag.async = true;
    scriptTag.src = protocol + 'localhost/wp/' + 
    projectId + '.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(scriptTag, s);
})();
function optimizelyTimeout() {
    window.optimizely = window.optimizely|| [];
    if (!window.optimizely.data) {
    window.optimizely.push("timeout");
    }
}
setTimeout(optimizelyTimeout, 1000);

</script>
</body>
</html>

This produces below code:

<script type="text/javascript" async="" src="http://localhost/wp/script.js"></script>

Now I would like script.js to return some custom js code which will be injected into original webpage. I tried with: -return("code"); -response.write("code");

but non of that worked for me.

  1. How script.js should look like in order to return some custom js code to be executed on client side?
  2. How can I pass arguments from client to server side call?

Upvotes: 1

Views: 304

Answers (1)

gurvinder372
gurvinder372

Reputation: 68433

How script.js should look like in order to return some custom js code to be executed on client side?

if the javascript code returned by script tag has to be invoked immediately then you need to return a self invoking function

(function(){ 
    /* code that you want to invoke immediately after the script has been loaded*/
})(this);

How can I pass arguments from client to server side call?

just push the parameters in the script src itself

scriptTag.src = protocol + 'localhost/wp/' + projectId + '.js?param1=value';

and intercept the same on your server side

Upvotes: 2

Related Questions