Iterate arraylist value on jsp after got response from ajax - javascript

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.

Related

How to parse a javascript list containing dictionary in python django

I have a webhook.
data0=[{"senderId":"smsdia","requestId":"******383233353233","report":[{"date":"2017-12-02 17:00:41","number":"12345","status":"1","desc":"DELIVERED"}],"userId":"119385","campaignName":"viaSOCKET"}]
I receive the above data in a POST request to my server.
Content-Type: application/x-www-form-urlencoded
How do I parse it?
I know that if it is a list: data1=['sree','kanth'] I can parse it with request.POST.getlist('data1[]')
But I don't know how to parse when it is a list containing dict.
edit1
Moreover, I get len(data1) is 2. But len(data0) is 0.
edit2
using request.lib:
https://requestb.in/13df2891?inspect
This appears to be JSON sent inside a form field. You can use the json library to parse it:
data = json.loads(request.POST['data'])

ajax returns python array response as string

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

Sending array to django via ajax

I am trying to send Javascript Array via AJAX POST to django view.
I store this array in hidden input using JSON.stringify:
$('#id_uuids').val(JSON.stringify(arr));
this is how I try to send it:
$.post("/ajax/generateGallery",{uuids: $('#id_uuids').val()},function(response){
resp = JSON.parse(response);
alert(resp.html);
},"json");
Browser console shows that data which is being send looks like:
uuids:["6ecbe35b-0b77-4810-aa9a-918fecaeef13","e41f52f7-721b-4d44-b7d6-bbb275182d66"]
However, I am not able to use this in my django view. I've tried:
uuids = request.POST.getlist('uuids')
logger.info(uuids)
logger.info(type(uuids))
which returns:
[08/Aug/2014 15:20:00] INFO [app.rest_client:307] [u'["89a26646-6000-4c48-804a-69abcc496fd8"]']
[08/Aug/2014 15:20:00] INFO [app.rest_client:308] <type 'list'>
[08/Aug/2014 15:20:00] INFO [app.rest_client:312] Generate HTML gallery for photo ["89a26646-6000-4c48-804a-69abcc496fd8"]
So, Django treats very list sent as single element. How can I force python code to treat this data as list and be able to iterate on?
try to JSON-decode the posted data
uuids = json.loads(request.POST.get('uuids'))
that is if you loaded some json module before, e.g.
import simplejson as json

Incorrect JSON data format

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.

Key and value reversed in JSON string sent to Django view via POST

This is my first attempt at ajax, and I've written a submit handler that parses a form and sends the data via POST to the server as a JSON string. Here is a simplified example of what my javascript looks like
formData = JSON.stringify({'testA':{'testa':'some data'},'testB':{'test2':'more data'}});
The JSON string looks like this
{"testA":{"test1":"some data"},"testB":{"test2":"more data"}}
and I send it via post here
$.post("/some/form/page/",formData,updateForm,'json');
On the server side is where the problem rears its ugly head, this is what my query dictionary looks like when I print if from the Django view
<QueryDict: {u'{"testA":{"test1":"some data"},"testB":{"test2":"more data"}}': [u'']}>
The JSON string is the key of the query dictionary. I am not very familiar with Javascript or JSON so don't be afraid of hurting my pride by pointing out an obvious newbie mistake, because I am and I know it. ;)
Thanks,
You're sending the string as a parameter to $.post. Instead of calling "JSON.stringify()" yourself, just pass in your raw JavaScript object as the second parameter to $.post().
$.post("/some/form/page/", {'testA':{'testa':'some data'},'testB':{'test2':'more data'}}, updateForm, 'json');

Categories