tarunkhanna has asked for the wisdom of the Perl Monks concerning the following question:

Hi
use CGI; my $co = new CGI; use CGI qw(:standard); use CGI::Carp qw(fatalsToBrowser); use strict; use diagnostics; print $co->header; print $co->start_html(); print $co->start_form(-method => "POST", -action => 'first.cgi'); print $co->h4("Name").$co->p; print $co->textfield({name => 'name', id => 'name'}).$co->p; print $co->submit(-onclick=>"return CheckForEmptyTextbox()"); print $co->reset; print $co->end_form; print $co->end_html;
Above CGI code is calling CheckForEmptyTextbox() function in javascript. But this javascript is in the different file.

Javascript

print <<CheckNameBox; <script language="JavaScript"> function CheckForEmptyTextbox() { if(document.getElementById("name").value=="") { alert ("Emtpy"); return false; } return true; } // end function </script> CheckNameBox
How to call above javascript function from CGI program which is in different files??

If I paste the above javascript code in the same CGI file, it works.

But what if I want javascript code to be in different file??

Replies are listed 'Best First'.
Re: (OT) Javascript with CGI using different files
by marto (Cardinal) on Oct 08, 2011 at 13:24 UTC

    Like your last problem, this isn't a Perl problem, it's a HTML problem. Learn how to use scripts within HTML, or take the advice given in your previous question regarding use of template files.

Re: (OT) Javascript with CGI using different files
by aaron_baugher (Curate) on Oct 08, 2011 at 18:27 UTC

    Your question (like the other one) shows a misunderstanding of what's going on. Your CGI program isn't "calling" any javascript. It can't -- the CGI runs on the server, and javascript runs in the browser after the page is loaded. Your CGI is outputting an HTML page, which happens to include a button on which is attached a click handler which calls a javascript function. By the time someone clicks the button, the CGI program has already done its job and exited.

    For your browser to find that function when a user clicks the button, the function will have to be defined in the HTML file itself (as you discovered) or in a separate javascript file that the HTML file includes with a <script type='text/javascript' src='myfile.js'> sort of tag.

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: (OT) Javascript with CGI using different files
by Anonymous Monk on Oct 08, 2011 at 12:43 UTC

    CGI CTRL-F ".js"

    html is html

Re: (OT) Javascript with CGI using different files
by ww (Archbishop) on Oct 08, 2011 at 13:50 UTC
    - -, not for being OT (the very first reply, from AM nails the documentation with your answer), but for your failure to read the doc for CGI.pm.