joe
joe

Reputation: 35077

How to Access Java Script Variable in CGI

How to access Javascript Gobal Variable into CGI Program

Thanks , Chells

Upvotes: 1

Views: 2801

Answers (3)

GeneQ
GeneQ

Reputation: 7595

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

Upvotes: 2

S.P
S.P

Reputation: 8756

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.

Upvotes: 2

Patrick Cornelissen
Patrick Cornelissen

Reputation: 7958

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?

Upvotes: 2

Related Questions