Wednesday, June 29, 2016

Including ColdFusion Content in Perl CGI Script

I have a site that mostly consists of ColdFusion pages. Occasionally I will use a Perl CGI script when the need arises. For example, long running reports or scripts that need to run shell commands are better suited for Perl than ColdFusion. On a side note, if you are running ColdFusion on a UNIX/Solaris platform like I am, you should avoid CFEXECUTE tags at all costs.

Whenever I create a Perl script on my site, I still want it to have the look and feel of the rest of my ColdFusion pages. I have a standard header that is included on every page of my site. Within that header is a menu that changes depending on which role(s) the user is assigned. To include the header on my Perl pages, I just use wget to retrieve the header file from my site, then display the HTML. It is something similar to this:
print &getHTMLHeader();

sub getHTMLHeader() {
    return `wget -O - http://mysite/myheader.cfm`;
}

The problem is that my ColdFusion session is not passed. Therefore, the menu does not display what a logged in user should see. I first thought I could just pass my cookies to the wget command:
sub getHTMLHeader() {
    open OUT, ">cookies.txt":
    print OUT $ENV{'HTTP_COOKIE'};
    close OUT;
    return `wget --load-cookies=cookies.txt -O - http://mysite/myheader.cfm`;
}

However, the ColdFusion session management is smart enough to recognize that something is not right about this session. That's because the IP address of the server and not the client is being passed to the page.

So here is the solution. After the HTML header is received, I append a little jQuery code to get the menu code and replace what is displayed:
sub getHTMLHeader() {
    my $html = `wget -O - http://mysite/myheader.cfm`;
    $html .= <<"    END";
        <script>
        \$.ajax({
            url: '/path/to/menu/menu.cfm',
            async: false,
            dataType: 'html',
            success: function (data, textStatus, jqXHR) {
                \$(".main-menu-content").html(data);
            }
        });
        </script>
    END
    return $html;
}
 
Blogger Templates