I am trying to list, in a select dropdown, some ontology elements using the following ajax:
$.ajax({
type: 'get',
url:"../py/ConfigOntology.py",
success: function(data){
$("#instance_image_1").append($("<option></option>").attr("value", data).text(data));
},});
"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:
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)
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.
So, my "big" question is: 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.
P.S: this is my first ajax function so please go easy on me.
I think what you should do is to return a JSON Object in the endpoint of your ajax call.
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.
the normal workflow would be request (client, your browser) --> server(this is in your case the script, but it should really be a server) --> response (this can be a json Object or html, in your case it is just the console output.)
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 JSON response.
here is a simple example of json processing with Flask (a simple python webserver)
http://code.runnable.com/Up77jfzqtL5FAAAu/json-dumps-and-loads-in-flask-for-python
I hope this can get you started
Related
I am running a server on Django, one function takes a seed through a URL param GET request, generates some data based on that seed, and sends it back.
The URL format:
mysite.com/api/generate/<seed>
expected result:
submitting a GET on mysite.com/api/generate/99 gets picked up in Django as a seed value of 99. data returned is chosen with random.choice() seeding with random.seed(99) from a database which contains a single column of names. data returned is the following:
Walker Lewis
Dalia Aguilar
Meghan Ford
Theresa Hughes
Kenna Coffey
Kendra Ho
problem
Here's where I'm getting confused (code below for each):
1000 requests in postman, all 1000 return perfectly equal
approx 100 requests from the google chrome console, all are equal
from the generate.js that the server sends with index.html, making the same call, results degenerate (examples below)
Postman call
very simple, GET mysite.com/api/generate/99
jquery from chrome console
$.ajax({
url: "/api/generate/99",
success: function( result ) {
console.log(result.data)
}})
jquery from generate.js
$.ajax({
url: "/api/generate/99",
success: function( result ) {
var data = result.data;
// data is now passed about the script, but debugging at the line above shows that data has already started to vary on a request by request basis
Both Postman and Chrome Console will return the expected results:
Walker Lewis
Dalia Aguilar
Meghan Ford
Theresa Hughes
Kenna Coffey
Kendra Ho
generate.js:
The first two names are always correct
The third is correct the majority of the time
fouth, 20% at best (estimate)
Anything past the forth might as well not be seeded, it just seems to be chosen at random from the database
other information
I have confirmed that each request from each source is being sent and received from the server, and not from a cache
Confirmed that all sources are hitting the same server, in the same state, and the same database
If anyone has any advice on this it would be very appreciated.
So it turned out this was due to me sending multiple AJAX requests "at once". When Django was behind Gunicorn/nginx each request gets a worker and is processed correctly. when requesting directly to docker the front end is returned with the strange data.
I got the arraylist from the ajax response. How can I assign the values to textbox after getting the response from ajax through arraylist?
while(rs1.next())
{
pabean.setAge(rs1.getString("patient_age"));
pabean.setDalerg(rs1.getString("patient_drug_allergies"));
pabean.setPmhistory(rs1.getString("patient_past_medical_history"));
pabean.setDiet(rs1.getString("patient_diet"));
pabean.setFhistory(rs1.getString("patient_family_history"));
pabean.setTobbaco(rs1.getString("patient_smoke"));
pabean.setDhistory(rs1.getString("patient_drug_history"));
pabean.setAlco(rs1.getString("patient_alcohol"));
pabean.setSleep(rs1.getString("patient_sleep"));
pabean.setGhistory(rs1.getString("patient_ob_gyn_history")
pabean.setPatient_details_id(rs1.getInt("patient_details_id"));
//uid = rs.getInt("patient_details_id");
}
addressLists1.add(pabean);
session.setAttribute("pagup", addressLists1);
out.println(addressLists1);
You said you are getting this value from ajax call.
Do remember you can not get a java object in ajax response. because call is part of javascript and javascript can not access java object.
like the way you are printing the arraylist like out.println(addressList1); it is printing as [com.bridghc.bean.PatientDetailsBean#15f9093f] it's just a string representation of the addressList1 object which serves no purpose.
Second thing you have written code in jsp like
<input type="text" id="txtage" name="txtage" placeholder="Age" class="form-control" value="<%=padetail.get(0).getAge()%>">
so <%=padetail.get(0).getAge()%> is a java code which run at server when you demand for the page even before the ajax call was being made.
You can try this -
if you want to print the age in the jsp just print it on servlet like
out.println(padetail.get(0).getAge());
so now in the ajax response you will get the age.
now you can place that response value in the desired input with jquery like $('#txtage').val(responseData);
if you want your whole list on jsp in response of ajax it's better to use json use any of the json library like google gson or json.org and create json array instead of arraylist and then set mime type to "application/json" and then print it with out.print()
after that you can parse this json in ajax success call and use in whatever way you want.
I query the db i my model like so
function graphRate($userid, $courseid){
$query = $this->db->get('tblGraph');
return $query->result();
}
My controller gets data back from my model and I json encode it like so
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['graph_json'] = json_encode($query);
}
$this->load->view('graph', $data);
And thats returns me a json object like so
[
{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
]
In my view graph I'm loading an js file
<script type="text/javascript" src="script.js"></script>
Now I want to use $data that is being sent from my controller to my view, to my external script.js to use as labels and data to feed my chart. But How do I get that Json data to my external script.js so I can use it?
1 more thing about the json data, isn't it possible to get the output of the json data as
{
"obj1":{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
"obj2":{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
"obj3":{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
}
The problem isn't a Codeigniter problem, it's a javascript scope/file inclusion/where-do-i-get-my-data-from problem.
I run into this all the time and have used these solutions:
naming my php files with .php extensions and loading them as if they're views.
Just putting the script that needs data from a view IN the view file where it's used
Using an ajax request in my included js file to hit a controller and get json data.
I use #2 most frequently (for things like datatables where I WANT the js code right there next to the table it's referencing.
I use #1 occasionally, but try NOT to do that because it means some .js files are in my webroot/js dir and some are in teh application/views directory, making it confusing for me or anyone else who wants to support this project.
#3 is sometimes necessary...but I like to avoid that approach to minimize the number of requests being made and to try to eliminate totally superfluous requests (which that is).
You need to print the result of the output json string to the html generated file.
But you need to parse the string with some script. I would recommend you: http://api.jquery.com/jQuery.parseJSON/
For the second question. It is possible by doing:
$returnValue = json_encode(
array (
"obj1" => array("id"=>"1","title"=>"myTitle","score"=>"16","date"=>"2013-08-02"),
"obj2" => array("id"=>"2","title"=>"myTitle2","score"=>"17","date"=>"2013-09-02"),
"obj3" => array("id"=>"3","title"=>"myTitle3","score"=>"18","date"=>"2013-10-02"),
)
);
Print the output using PHP like:
echo json_encode($query);
Then from the client-side (where JavaScript resides) load that JSON that you printed using PHP. This can be done easily using JQuery.
Like this:
$.get("test.php", function(data) {
alert("Data Loaded: " + data);
});
You can find more information about this here: http://api.jquery.com/jQuery.get/
Now you'll need to parse this data so that JavaScript can understand what you got as text from the server. For that you can use the JSON.parse method on the "data" object in the aforementioned example. Once parsed, you can use the object like any other object in JavaScript. You can find more information about JSON.parse here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I hope that helps.
I encountered the strangest thing today while I was trying to filter image data from a string of html that I download through an AJAX request (I use https://github.com/padolsey/jQuery-Plugins/blob/master/cross-domain-ajax/jquery.xdomainajax.js to do so).
I noticed that I was getting a 404 on an image that it was trying to download. After looking at the initialiser stack, it appears that the image is inside the html that my AJAX pulls back. Here is the relevant stack:
b.extend.buildFragment # jquery-1.9.1.min.js:4
b.extend.parseHTML # jquery-1.9.1.min.js:3
b.fn.b.init # jquery-1.9.1.min.js:3
b # jquery-1.9.1.min.js:3
$.ajax.success # main.js:86
My code in main.js looks like this:
function generateAlbumHTML(album)
{
$.ajax({
url: album.data.url,
type: 'GET',
success: function(data)
{
var albumHtmlStr = "";
var images = $(data.responseText).find('#image-container .zoom');
$.each(images, function(i, item)
{
album.data.url = $(item).attr('href');
albumHtmlStr += generateHTML(album);
});
return albumHtmlStr;
}
});
}
It appears that the culprit is line 86 where I do:
var images = $(data.responseText).find('#image-container .zoom');
This causes JQuery to parse the HTML and start loading unwanted images and data from the HTML.
Here is a link to the html that gets pulled back by the ajax request as data.responseText: http://pastebin.com/hn4jEgAA
Anyway, am I doing something wrong here? How can I filter and find the data I want from this string without loading things such as unwanted images and other data?
What causes the "parsing" is this:
$(data.responseText)
This is actually you, telling jQuery to create HTML structure using the string you provided in data.responseText.
If you want to find things in this string, which is the HTML in response to your GET request, then you have to use one of the corresponding String methods:
String instances methods
It should be noted, however, that what you are trying to do is quite unorthodox, since parsing HTML on the client to retrieve information is not the best of approaches.
The better way would be to either use the receieved HTML as is (provided it is from a trusted source or you sanitize it properly), or to receive raw data in JSON form and process that data (while creating corresponding HTML by yourself) in your code.
UPDATE
Additional ways are presented in jQuery ajax method
For instance, you can use dataFilter setting or some such to sanitize your response.
I am trying to create some JSON to be used for displaying a chart using Highcharts
http://www.highcharts.com/
I have copied one of their examples:
http://www.highcharts.com/stock/demo/basic-line
Click "View Options" under the graph to see the source. There is also a JSFiddle there to play with
If I copy that locally it all works fine.
The problem is when I try to use my own data source.
I have an ASP.Net MVC controler which is spitting out a list of arrays, just like their data source. However, that doesn't work.
Their datasource looks like this
http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
and they retrieve it like this
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) {
So I thought I'd take a step back and copy thier data exactly and put it in a text file on my server and try that:
So I tried this
$.getJSON('/data.txt', function (data) {
and this
$.get('/data.txt', function (data) {
but neither work
I have also tried using both JSON.parse and jQuery.parseJSON after retrieving the data, but again - that doesn't seem to work
I am also wondering what the ? is at the start of their data
Their data looks like this
?([[<some data>],[some data]]);
I don't get any error message, the graph just doesn't display
any ideas?
SOLVED IT
Just need to retrive the data and turn it into an array and pass it to the chart.
Needs to be an array, not JSON
That datasource is ouputting JSONP, which is for cross-domain AJAX requests. It's not valid 'raw' JSON because of that extra callback(...) wrapper.
Read up about it here: http://api.jquery.com/jQuery.ajax/ under the 'dataType' section.
As you say in your tags, it's not JSON, it's JSONP. Do not parse it, catch it with a callback. Use jQuery.getScript to do it, and define function callback(data). Inside that function, data should contain the (parsed) object. Also, replace the ? in the URL with callback (or whatever you named your function) - ? is not a valid identifier in JavaScript, so ?([....]) is nonsense.