0

I have a javascript file where I am trying to set a variable using data sent from a python cgi script.

I am trying to use the ajax get method, and setting the variable within that method. Here is how I am doing it in the javascript.

$.get('cgi-bin/populate_usernames.py', function(data) {
    users = data
});

console.log(users)

In the python code, I have the following:

#!/usr/bin/python
import os

data = ["Bob", "Jim"]

For some reason, the console log fails because users is undefined. I think it is because the content type is incorrect for data. Is there a way for me to send a JSON array from the python code so that users has the correct contents of Jim and Bob?

1
  • $.get is asynchronous. You will have to put the console.log(users) inside the { } of the callback you pass to $.get. Commented Jun 27, 2019 at 19:00

1 Answer 1

2

For simple data structures like lists, you can use an external standard like JSON to pass information between two languages.

import json
data = ["Bob", "Jim"]
json_string = json.dumps(data)

Then pass the json string to the javascript environment in whatever way is possible in your application.

Sign up to request clarification or add additional context in comments.

1 Comment

I figured out that I have to send a JSON object. The main problem is how do I send the json string over to the javascript environment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.