Home > Software design >  I am trying to run a python script from a click of a button in my HTML code using Ajax
I am trying to run a python script from a click of a button in my HTML code using Ajax

Time:10-31

My JS code -

function callPythonScript() {
                alert("called");
                $.ajax({
                    url: "http://localhost:5000/app.py",
                    type: "POST",
                    // data: {
                    //     "var1": 'value1',
                    //     "var2": "value2"
                    // },
                    success: function(response) {
                        console.log(response);
                    },
                    error: function(xhr) {
                        console.log(xhr);
                    }
                });
            }

button code -

<button  onclick="callPythonScript()" value = "Display">Click Here to open a request</button>

Python Code -

import cgi
import requests
import json
form = cgi.FieldStorage()
var1 = form.getvalue('var1')
var2 = form.getvalue('var2')

def api_call():
    url = "https://instance.service-now.com/api/now/table/incident"

    payload = json.dumps({
    "short_description": "onclickbutton test api"
    })
    headers = {
    'Authorization': 'Basic auth',
    'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    return (response.text)

api_call()

Error which i get in console - enter image description here

I don't understand why i get cors policy error when both my server and page is on same host.

I tried to add the file path locally instead on hosting i get the same cors policy error. Please suggest a different approach to run a python script from HTML and pass values as well. TIA

CodePudding user response:

I was initiating the server using "python -m httpserver"

This server is a simple server and wont be able to run your code when called, we need to use Flask or Django , i used Flask because i needed a very simple server with very less configurations, Using Flask i was able to bypass CORS policy error by adding app = Flask(__name__) CORS(app)

  • Related