I have a PHP script that has a form with two input fields. My page needs to pass these two input values back into my Python CGI script
(calculate.py) when a user clicks the submit button, retrieve the result and prints it back onto the same PHP page below my input fields (without the page refreshing).
I tried simple form action calls to the script but they led me to a new page, i.e. my own script opening. I then read answers saying that for dynamic page updating, JS & AJAX need to be used, and thus created a JS function called python_process()
in my PHP file based on those guidelines.
However, when I currently click submit, nothing appears below my input fields.
I have also tried to debug this by viewing the developer console, but nothing appears there.
Here is my PHP code:
<?php
print "<html>";
print "<script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-1.4.4.min.js\"></script>";
print "<script>
function python_process() {
var cancellationrate = $('input[name=cancellationrate]').val();
var waitingtime = $('input[name=waitingtime]').val();
$.ajax({
url: \"/cgi-bin/calculate.py\",
type: \"POST\",
contentType: \"application/x-www-form-urlencoded\",
data: {\"cancellationrate\" : cancellationrate, \"waitingtime\": waitingtime },
success: function(response){
$(\"#result\").html(response);
}
});
};
</script>";
print "<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">
";
print "<br/>";
print "<div class=\"container\">";
print "<form name=\"calculate\" id=\"calculate\" method=\"post\">";
print "<div class=\"form-group row\">";
print "<label for=\"cancellationrate\" class=\"col-sm-2 col-form-label\">Cancellation Rate</label>";
print "<div class=\"col-lg-10\">";
print "<input type=\"text\" style=\"width: 400px\" class=\"form-control\" name=\"cancellationrate\" id=\"cancellationrate\" placeholder=\"Expected % Change in Cancellation Rate\">";
print "</div>";
print "</div>";
print "<div class=\"form-group row\">";
print "<label for=\"waitingtime\" class=\"col-sm-2 col-form-label\">Waiting Time</label>";
print "<div class=\"col-lg-10\">";
print "<input type=\"text\" style=\"width: 400px\" class=\"form-control\" name=\"waitingtime\" id=\"waitingtime\" placeholder=\"Expected % Change in Waiting Time\">";
print "</div>";
print "</div>";
print "<center><button type=\"button\" onclick=\"python_process()\" class=\"btn btn-primary\">Submit</button></center>";
print "</form>";
print "</div>";
print "<div id=\"result\"></div>";
?>
And here is my calculate.py CGI script:
#!/anaconda3/bin/python3
import cgi
print ("Content-type: text/html\n\n")
data = cgi.FieldStorage()
cancellation_rate = int(form.getvalue('cancellationrate'))
waitingtime = int(form.getvalue('waitingtime'))
result = cancellation_rate * waitingtime
print(result)