and python/cherrypy server
#cherrypy.tools.json_out()
#cherrypy.tools.json_in()
def get_data(self):
cherrypy.response.headers['Content-Type'] = 'application/json'
datas = {"ABCDEF"}
return datas
but I get a Internal Server Error (500), where is my mistake?
I get work to post data to server, but with getting data is my problem..
One problem is in your fifth line of your second code block. Change
datas = {"ABCDEF"}
to something like
datas = { "somedata" : "ABCDEF"}
And if this is all of your cherrypy server code, you're not exposing your route. Then you have to add the
#cherrypy.expose
annotation. You can consult the docs for this as well.
Your datas variable is a Python set, and those are not directly serialisable to JSON. Perhaps you meant to create a dictionary or list?
Related
I currently have a javascript variable called myVariableToSend that contains a single string and I need to send to my views where I can make raw SQL queries to gather corresponding data from the database and bring it back to my javascript. Here is what I have:
Javascript:
function scriptFunction(myVariableToSend){
$.getJSON("http://127.0.0.1:8000/getData/", myVariableToSend, function(serverdata){
window.alert(serverdata);
});
Views.py:
def getData(request):
some_data = request.GET(myVariableToSend)
cursor = connection.cursor()
cursor.execute("SELECT Car_ID FROM cars WHERE Carname = %s ", [some_data])
row = cursor.fetchall()
return JsonResponse(row, safe = False)
Urls.py:
url(r'^admin/', include(admin.site.urls)),
url(r'^$', startpage),
url(r'^getData/$', getData ),
I don't think my server side script(views.py) is working because when I run my server, I get a http500 error. Any help would be appreciated. Thank you.
UPDATE:
I have found that when I comment out my entire Views.py and only put
def getData(request):
return JsonResponse({"hello":"World"}, safe = False)
I get no problems and the AJAX request works. But when I have my original getData, it doesn't work. When I add this line in my views.py:
some_data = request.GET(myVariableToSend)
, I get an error and the data isn't displayed
If u want to send ur variables to function in view, u can capture it with url, like this:
$.getJSON('http://127.0.0.1:8000/getData/' + myVariableToSend +'/', function (serverdata) { //do ur work}
Then in urls.py you have:
url(r'getData/(?P<my_var>\w+)/$', views.get_data, name='get_data')
Then views.py:
def get_data(request, my_var):
#do ur work here
Answering the original question:
Your server is failing probably because bad syntax in views.py
some_data = request.GET(myVariableToSend)
myVariableToSend is undefined here. So you should get it like this:
some_data = request.GET['myVariableToSend']
Besides the original question:
You'll get a lot of headaches if you try to set up your django app like this.You can query your database way easier if you use django's ORM. Read about it here.
Also, if you want to send the data in your models to your javascript code, you can save yourself lots of time by using a framework like Django REST Framework.
I send a http GET request which returns JSON data in the following form. I am finding it impossible to access this data despite having no problems with example json that I create. I want to ideally take the array under wifi, and use this data to create a html table, but I think I can work out how to create the table if I could just access the actual elements of the data.
I have tried multiple methods to try and reach the first timestamp. I have tried:
var element = result.undefined.clients.wifi[0].timestamp;
but this returns an error that 'clients' can't be found.
I also tried:
var element = result.clients.wifi[0].timestamp; //and
var element = result.wifi[0].timestamp;
The JSON data returned to a variable is shown below:
result = undefined
{"sourceId":"idid","sourceType":"CLOUD_source","searchMeta":{"maxResults":4,"metricType":["clients"],"family":["wifi"],"Interval":"M1"},
"clients":{"wifi":
[{"timestamp":1424716920,"avg":3,"min":1,"max":4,"Count":8,"sCount":3,"sources":["x1","x2","x3","x4","x5","x6","x7","x8"]},{"timestamp":1424716980,"avg":2,"min":1,"max":3,"Count":4,"sCount":2,"sources":["x3","x4","x8","x4"]},{"timestamp":1424717160,"avg":2,"min":1,"max":3,"Count":9,"sCount":4,"sources":["x3","x4"]}]}}
The JSON data is invalid. If it is returned from a server, you need to go there and correct the data source, (if you have access to that).
Otherwise, perhaps notify the backend guy(s) about it.
If it is from a REST API, and you are "sure" that the server code should be error free, then check that you have supplied all the required parameters in the API request you are making.
I think your JSON is messed up. I ran it through JSONLint, and having the undefined at the beginning causes things to break.
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
I'm using YUI io to post data to my server. I have some problems sending foreign characters like æ ø å.
First case: a form is posted to the server
Y.io(url, {
method: 'POST',
form: {
id: 'myform',
useDisabled: true
}
});
This will post the content of the form to the server. If I have a field named "test1" containing "æøå", then on the server I'll see REQUEST_CONTENT="test1=%C3%A6%C3%B8%C3%A5". This can be easily decode with a urldecode function, NO PROBLEM, but...
Second case: data is posted this way:
Y.io(uri, {
data : '{"test1":"æøå"}'),
method : "POST"
});
Now I see this on the server REQUEST_CONTENT="{"test1":"├ª├©├Ñ"}". How can I decode that? And why is it send like that?
I know I can use encodeURIComponent() to encode the string before sending it. But the io request is actually part of a Model Sync operation, so I'm not calling io directly. I'm doing something like this:
Y.User = Y.Base.create('user', Y.Model, [Y.ModelSync.REST], {....});
var user = new Y.User();
user.set('test1', 'æøå');
user.save();
So it doesn't make sense to encode/decode everytime I set/read the attribute.
Also I have tried to set charset=utf-8 in the request header, but that didn't change anything.
EDIT
I have done some more debugging in chrome and the request is created with this line of code:
transaction.c.send(data);
transaction.c is the xmlhttprequest and (using chrome debugger) I can see the data is "{"test1":"æøå"}"
When the above line of code is executed, a pending network entry is shown (under the network tab in chrome debugger). Request payload displays {"test1":"├ª├©├Ñ"}
Headers are:
Accept:application/json
Content-Type:application/json; charset=UTF-8
ModelSync.REST has a serialize method that decides how the data in the model is turned into a string before passing it to Y.io. By default it uses JSON.stringify() which returns what you're seeing. You can decode it in the server using JSON. By your mention of urldecode I guess you're using PHP in the server. In that case you can use json_decode which will give you an associative array. If I'm not mistaken (I haven't used PHP in a while), it should go something like this:
$data = json_decode($HTTP_RAW_POST_DATA, true);
/*
array(1) {
["test1"] => "æøå"
}
*/
Another option would be for you to override the serialize method in your User model. serialize is a method used by ModelSync.REST to turn the data into a string before sending it through IO. You can replace it with a method that turns the data in the model into a regular query string using the querystring module:
Y.User = Y.Base.create('user', Y.Model, [Y.ModelSync.REST], {
serialize: function () {
return Y.QueryString.stringify(this.toJSON());
}
});
Finally, ModelSync.REST assumes you'll be using JSON so you need to delete the default header so that IO uses plain text. You should add this at some point in your code:
delete Y.ModelSync.REST.HTTP_HEADERS['Content-Type'];
I'm new to JSON/AJAX and
I've some problems with displaying data out of a JSON-object I've got from a server..
The url "http://localhost:8387/rest/resourcestatus.json" represents this object, which I would like to display via HTML/Javascript.. This object stores some monitoring information:
{"groupStatus":[
{"id":"AL Process","time":1332755316976,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance1","time":1332919465317,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance2","time":1332919465317,"level":1,"warningIds":["documentarea.locked"],"errorIds":[]},
{"id":"SL","time":1331208543687,"level":0,"warningIds":[],"errorIds":[]}
]}
Since the requested url is different from my domain I can't create a typical XMLHttpRequest.. So I found out that there's an AJAX cross-domain request which can be realised via jQuerys "getJSON()" method.
I want to display the ids and their level in a table.
Any solution to achieve this?
i think you are referring to JSONP. see jQuery.ajax Ex:
var url = 'http://localhost:8387/rest/resourcestatus.json';
$.getJSON(url+'?callback=?', function(data)
{
//data is
/*{
"groupStatus":
[
{"id":"AL Process","time":1332755316976,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance1","time":1332919465317,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance2","time":1332919465317,"level":1,"warningIds":["documentarea.locked"],"errorIds":[]},
{"id":"SL","time":1331208543687,"level":0,"warningIds":[],"errorIds":[]}
]
}*/
});
on the server side you will need to wrap the response into a JavaScript function: response = Request["callback"] +"("+ response+")";
the result will look like this:
?({"groupStatus":[{"id":"AL ....})
So the browser will actually load a valid java script code.
The callback function of $.getJSON contains the result of the AJAX call in it's argument.
$.getJSON('http://localhost:8387/rest/resourcestatus.json', function(data) {
$(data.groupStatus).each(function() {
// do something with $(this).id
});
});