-1

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)

akg777
  • 35
  • 6
  • Please go read [ask]. You need to give us a proper problem description. What _exactly_ is not working right now? What have you done so far to try and debug this? – 04FS Oct 24 '19 at 10:02
  • It looks like you did nothing here to prevent the _normal_ form submit. So your JS function gets called, briefly tries to make its AJAX request in the background - but this then gets interrupted, because the normal form submission was not prevented, so the browser just submits the form data to the URL in the action attribute (which since that is empty, would just be the URL you are currently on again), and then you get a “page reload” as result. – 04FS Oct 24 '19 at 10:05
  • @04FS My bad, updated the question again. I have removed the action attribute from my form tag, which makes me think should solve the issue, but I see the same result. – akg777 Oct 24 '19 at 10:10
  • No, that does not solve the issue. A missing action attribute is treated the same, as an empty one. A quick fix here would be to change the type of your button, from `submit` to `button`. Then it’s a “click button” only, but does not submit the form. – 04FS Oct 24 '19 at 10:13
  • But you should probably go research how to properly prevent form submission in a case like this anyway - otherwise, you’ll easily run into trouble if submission happens f.e. because the user simply pressed [enter] while having focus in one of the text fields. – 04FS Oct 24 '19 at 10:15
  • Tried that but that doesn't fix things. I can see in the console now that the python script is running and its status is OK but there is no output on the page. Seems to be an issue somewhere in my JS function. – akg777 Oct 24 '19 at 10:22
  • Check in the network tab, what the actual response of the python script was. _“status is OK”_ actually meaning HTTP status code here, so a 200 OK? If the status code does not indicate success, it would not go into the specified `success` handler. – 04FS Oct 24 '19 at 10:25
  • Yes, what it shows is Status Code: 200 OK – akg777 Oct 24 '19 at 10:26
  • Btw., you are outputting huge portions of mostly _static_ HTML code using print here, which means you have to deal with escaping of string delimiters all the time. Make your life a little easier, by using this syntax: https://www.php.net/manual/en/language.basic-syntax.phpmode.php – 04FS Oct 24 '19 at 10:27
  • Okay, and if you inspect the details of the request in the network panel, what does the response look like? – 04FS Oct 24 '19 at 10:28
  • Response is empty! – akg777 Oct 24 '19 at 10:31
  • Then check if the parameters where send correctly to begin with. You can also do that in the network panel, depending on the browser it might be named a bit differently, Chrome shows it in the “Headers” tab under “Form Data”. – 04FS Oct 24 '19 at 10:38
  • Yeah, I have done that. They are accepting the right values that I have inputted into the fields – akg777 Oct 24 '19 at 10:41
  • Is the request send in the correct “format”? The `content-type` request header should be `application/x-www-form-urlencoded`. – 04FS Oct 24 '19 at 10:44
  • Tried adding that into my ajax request also, but nothing changes – akg777 Oct 24 '19 at 10:51

1 Answers1

0

Turns out it was a very small error in my Python script where I define my CGI field storage as a variable called data and try to access its value using form.

Also, this question helped answer my div value not updating!

Update div with jQuery ajax response html

akg777
  • 35
  • 6