tags:

views:

551

answers:

3

Hi,

How to access Javascript Gobal Variable into CGI Program

Thanks , Chells

+2  A: 

the cgi prog runs on the server and your javascript is in the browser, right? Maybe you should pass the variable to the server via URL (GET) or HTTP Post?

Patrick Cornelissen
+2  A: 

Three ways: POST, GET, or cookies. which you use depends on your situation.

POST: Include a form on your page with two hidden fields. When an event occurs, fill the hidden fields with your JS variables and submit the form to your cgi program.

GET: Have JS tack the variables onto the URL. when the user clicks a link, it activates a JS function. the JS function sends the browser to "cgi-prog.cgi?JSvar1=foo&JSvar2=bar"

cookies: JS sets a cookie on the user's machine once it has determined the variables. Perl reads that cookie to get the variables.

Suvesh Pratapa
Good To Trigger my mind to think different way of sloving .Thanks suveshpratapa
joe
+2  A: 

The methods suggested by other people such as HTTP GET, POST, query string, hidden form fields and cookies are perfectly fine. But for more finesse and interactivity, consider using AJAX.

We have a web app than uses Javascript on the browser side that sends some data to the server side script via AJAX when something is clicked. Is that similar to what you're doing? If so, then AJAX is the way to go.

The example below uses GET to sent stuff back to a Perl CGI script (located at 'url'):

var request =  new XMLHttpRequest();
request.open("GET", url, false);
request.send(null);

if(!request.getResponseHeader("Date")) {
var cached = request;
request =  new XMLHttpRequest();
var ifModifiedSince = cached.getResponseHeader("Last-Modified");
ifModifiedSince = (ifModifiedSince) ?
      ifModifiedSince : new Date(0); // January 1, 1970
  request.open("GET", url, false);
  request.setRequestHeader("If-Modified-Since", ifModifiedSince);
  request.send("");
  if(request.status == 304) {
    request = cached;
  }
}

Of course, don't ever write this stuff yourself. It's just to illustrate what's going on. Always use a good Javascript library to do the AJAX stuff. There are many good ones out there: List of modern AJAX Libraries and Frameworks

GeneQ
joe
I am going to use this method.
joe
You're welcome. We ported a fairly complex and old web app which uses only hidden fields and query strings. We use jquery and some other stuff on the client side to intercept the form submit and submit it via XMLHTTPRequest. The upside is that the existing server side script was never changed during the port, only the browser side HTML and Javascript. (UI Layer)
GeneQ