How to send JSON data created by Python to JavaScript?
<p>I am using Python <code>cherrypy</code> and <code>Jinja</code> to serve my web pages. I have two Python files: <em>Main.py</em> (handle web pages) and <em>search.py</em> (server-side functions).<br>
I create a dynamic dropdown list (using <code>JavaScript</code>) based on a local <code>JSON</code> file called <em>component.json</em>(created by function <em>componentSelectBar</em> inside <em>search.py</em>).  </p>

<p>I want to ask how can my JavaScript retrieve JSON data <strong>without physically storing the JSON data into my local website root's folder</strong> and still fulfil the function of dynamic dropdown list.</p>

<p>The <em>componentSelectBar</em> function inside <em>search.py</em>:</p>

<pre><code>def componentSelectBar(self, brand, category):
    args = [brand, category]
    self.myCursor.callproc('findComponent', args)
    for result in self.myCursor.stored_results():
        component = result.fetchall()
    if (len(component) == 0):
        print "component not found"
        return "no"

    components = []
    for com in component:
        t = unicodedata.normalize('NFKD', com[0]).encode('ascii', 'ignore')
        components.append(t)

    j = json.dumps(components)
    rowarraysFile = 'public/json/component.json'
    f = open(rowarraysFile, 'w')
    print &gt;&gt; f, j

    print "finish component bar"
    return "ok"
</code></pre>

<p>The <em>selectBar.js</em>:</p>

<pre><code>    $.getJSON("static/json/component.json", function (result) {
        console.log("retrieve component list");
        console.log("where am i");
        $.each(result, function (i, word) {
            $("#component").append("&lt;option&gt;"+word+"&lt;/option&gt;");
        });
    });
</code></pre>

<p>You are rendering a HTML and sending it as response. If you wish to do with JSON, this has to change. You should return JSON in your main.py, whereas you will send a HTML(GET or POST) from Javascript and render it back.</p>

<pre><code>def componentSelectBar(self, brand, category):
    /* Your code goes here */
    j = json.dumps(components)
    // Code to add a persistent store here
    rowarraysFile = 'public/json/component.json'
    f = open(rowarraysFile, 'w')
    print &gt;&gt; f, j
    // Better to use append mode and append the contents to the file in python
    return j //Instead of string ok


@cherrypy.expose
def codeSearch(self):
    json_request = cherrypy.request.body.read()
    import json # This should go to the top of the file
    input_dict = json.loads(json_request)
    modelNumber = input_dict.get("modelNumber", "")
    category = input_dict.get("category", "")
    brand = input_dict.get("brand", "")
    /* Your code goes here */
    json_response = self.search.componentSelectBar(cherrypy.session['brand'], cherrypy.session['category'])
    return json_response
</code></pre>

<p>Here, I added only for the successful scenario. However, you should manage the failure scenarios(a JSON error response that could give as much detail as possible) in the <code>componentSelectBar</code> function. That will help you keep the <code>codeSearch</code> function as plain as possible and help in a long run(read maintaining the code). </p>

<p>And I would suggest you to read <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> and apply it to the code as it is kind of norm for all python programmers and help any one else who touches your code.</p>

<p>EDIT: This is a sample javascript function that will make a post request and get the JSON response:</p>

<pre><code>searchResponse: function(){
  $.ajax({
    url: 'http://localhost:8080/codeSearch', // Add your URL here
    data: {"brand" : "Levis", "category" : "pants"}
    async: False, 
    success: function(search_response) {
      response_json = JSON.parse(search_response)
      alert(response_json)
      // Do what you have to do here;
      // In this specific case, you have to generate table or any structure based on the response received
    }
  })
}
</code></pre>

javascript python html json cherrypy