Search code examples
javascriptperlonclickhref

JavaScript href onclick not working with Perl


The below is my code. All my button functions are working perfectly, but if I click the link click the value of server should be remembered and the page should be reloaded again with the parameters view and subsys.

But the value for the server is empty when I getting reloaded.

my $server = $q->param('server') ;
my $unit = $q->param('unit') ;

my $bfile = __FILE__ ;
$bfile = `basename $bfile` ;
chomp $bfile ;

print "<form name=\"form1\" action =\"/cgi-bin/$bfile\" onsubmit=\"javascript:onsubmitform(doc_press)\">";

print "<input type=\"hidden\" name=\"server\" id=\"server\">";
print "<input type=\"hidden\" name=\"unit\" id=\"unit\">";
print "\n\n<input type=submit name=view value=\"View\" onClick=\"doc_press=this.value\">";
print "<input type=submit name=save value=\"Save\" onClick=\"doc_press=this.value\">";

print $var{$a}."<a href=\"/cgi-bin/$bfile?view=5&SUBSYS=$subsys\" onClick=javascript:click_page(\"$_\")>CLICK</a>\n" ;

print <<"END_OF_SCRIPT";
<script type="text/javascript">
function onsubmitform(doc_press) {
        if (doc_press == "View"){
                document.getElementById('unit').value="$unit";
        }
        else if (doc_press == "Save") {
END_OF_SCRIPT
             var x = "$user=$val";
             document.cookie=x;
             document.getElementById('unit').value="$unit";
        }
        if (document.getElementById('HTTP_TYPE').value == "post") {
                document.form1.method='post';
        }
        else if(document.getElementById('HTTP_TYPE').value == "get") {
                document.form1.method='get';
        }
}

function click_page(server){
        document.getElementById('server').value=server;
}
</script>
END

Solution

  • When you click on a link (<a href="..."/>), the browser will make a new GET request for the given link, regardless of any forms you might have. This means that your form is NOT submitted; so any value in the form will be lost. For this reason, your onclick handler as posted here is useless.

    Sometimes, if you’re really linking to the same page, modern browsers are smart enough to recognize that, and fill in the values you already had. This is only a commodity to users who get frustrated if their values are not kept, and so this doesn't work for hidden fields.

    If you want clicking on the link to submit the form, you should either a) use a button, or b) change your onclick handler to submit the form and return false (so that the link isn’t followed):

    function click_page(server){
        document.getElementById('server').value=server;
        document.forms[0].submit();
        return false;
    }
    

    To make this work correctly, also change the onclick declaration:

    <a href="..." onclick="return click_page('$_')">CLICK</a>