ajax returns python array response as string
<p>I am trying to list, in a select dropdown, some ontology elements using the following ajax:</p>

<pre><code>$.ajax({
                type: 'get', 
                url:"../py/ConfigOntology.py",
                success: function(data){
                    $("#instance_image_1").append($("&lt;option&gt;&lt;/option&gt;").attr("value", data).text(data));   

                },});
</code></pre>

<p>"ConfigOntology.py" is a simple code that extracts and prints two ontology items. However, the ajax takes these two as a single string. Parts of this .py contents that generate the output are:</p>

<pre><code>import rdflib, rdfextras, cgitb
from rdflib import Graph

cgitb.enable()
print ("Content-Type: text/plain;charset=utf-8")
print("")

def getImages(results):

    for row in results:
        print (row['storedImage'][50:]) 

sparql = "the query goes here"
results = ConfigOnto.query(sparql)
getImages(results)
</code></pre>

<p>I tried a php script with a php exec(), which gets the .py output as an array but the ajax also takes that a string. I tried JSON.parse(data) but got error saying "Uncaught SyntaxError: Unexpected token K in JSON at position 0" - referring to end of line in in .py output. </p>

<p>So, my "big" question is: <strong>how can I access the ConfigOntology.py output as individual items in the ajax() rather than a string, and what could be a possible fixed code for this problem.</strong></p>

<p>P.S: this is my first ajax function so please go easy on me. </p>

<p>I think what you should do is to return a JSON Object in the endpoint of your ajax call. </p>

<p>If I understand it correctly right now you try to read the output of a python script in an ajax request which is not the normal workflow for this. </p>

<p>the normal workflow would be <strong>request</strong> (client, your browser) --> <strong>server</strong>(this is in your case the script, but it should really be a server) <strong>--> response</strong> (this can be a json Object or html, in your case it is just the console output.)</p>

<p>so what you need to do is to change your pyhton script that gives a console output into an endpoint of a server, and that endpoint should return a <strong>JSON</strong> response. </p>

<p>here is a simple example of json processing with Flask (a simple python webserver) 
<a href="http://code.runnable.com/Up77jfzqtL5FAAAu/json-dumps-and-loads-in-flask-for-python" rel="nofollow">http://code.runnable.com/Up77jfzqtL5FAAAu/json-dumps-and-loads-in-flask-for-python</a></p>

<p>I hope this can get you started</p>

javascript php python ajax