CGI Programming / Scripts Question:

Download Job Interview Questions and Answers PDF

Can I pass JavaScript variables to a CGI Perl program?

CGI Programming Interview Question
CGI Programming Interview Question

Answer:

This question has been asked a few times so I felt it was time to include it in the FAQ. The only way to pass information from the client-side (in the JavaScript variable) to the server-side (the Perl program) is through the CGI. Since a CGI application is stateless, it does not remember anything about how it was last called between invocations. Once it stops running, all its variables are forgotten. In order to submit information to a CGI script from a JavaScript variable, you must dynamically create a URL pointing to the CGI program which submits your JavaScript variable. Your CGI script must be set up to respond to submissions using the GET method, since this is the only one you can use when submitting a variable as part of a URL. Take a look at the following bit of code:

var firstname = 'Smith'; // JavaScript variable containing firstname

var URL = eval('http://www.server.com/cgi-bin/script.pl?firstname=' + firstname);

document.location.href = URL;

and when your script is run (because of the document.location.href statement), your script will have access to the firstname variable.

Download CGI Programming Interview Questions And Answers PDF

Previous QuestionNext Question
Can I do HTTP authentication using CGI?Can I run a CGI script without returning a new page to the browser?