2

I am calling a python script using AJAX call? I wish to perform some computation in Python which cannot be done in JS and return the result back to AJAX caller. Python script will just encode some data in JSON and send to AJAX caller.

But instead, when I have a return type of AJAX request as HTML or text, it just alerts entire python code instead of executing it.

How can I execute the Python code stored in my server instead of just accessing it?

I am sending the request as follows

$("#train").click(function () {             
            $.ajax({
                type: "GET",
                url: "<?php echo base_url('python/train.py'); ?>",
                dataType: "json",
                cache: false,
                beforeSend: function() {
                    $('#train').val("Training Model...");
                },
                success: function(data) {
                    alert(data)
                },
                error: function(request, status, error) {
                    console.log("Error: " + error)
                },
                complete: function() {
                    $('#train').val("Trained Model")
                }
            });
        });

Please help.

pokemon
  • 71
  • 1
  • 12
  • 4
    It looks like you have a PHP-based server. You need to have a PHP script which runs your Python script. [This link might help.](https://stackoverflow.com/questions/19735250/running-a-python-script-from-php) – Mike Cluck Nov 15 '18 at 17:18
  • You're going to need to run it server side, so there has to be something on the backend that fires up the python script. If you're using django or flask this is pretty straight forward, but maybe a little more tricky or other stuff (php). The idea is to have whatever function handles the request call the python – SuperStew Nov 15 '18 at 17:18
  • I am using a PHP framework codeigniter, but had seen some answer related with how can the HTTP request be sent to the server side for execution. One example is https://medium.com/@NadyaCPena/how-to-run-a-python-script-onclick-event-from-javascript-e5ac79a0320 Please help – pokemon Nov 15 '18 at 17:20
  • 1
    Has nothing to do with Ajax, issue is your server does not know how to run python... – epascarello Nov 15 '18 at 17:21
  • If I am using PHP command line. How will I be able to get JSON output @MikeCluck ? – pokemon Nov 15 '18 at 17:24
  • 1
    @pokemon Did you look at the link I provided? You need to run Python from a PHP script then return the result of the Python script from your PHP script. – Mike Cluck Nov 15 '18 at 17:25
  • 1
    Finally did. Thanks a lot @MikeCluck for giving me write direction. – pokemon Nov 15 '18 at 19:11

0 Answers0