Django Ajax 'GET' - ajax

newbie here. I am trying to get some data from my database using ajax.
In my views.py,
def getEvents(request):
eventList = Events.objects.all()
events=[]
for event in eventList:
events.append({"name": event.name, "start": event.start, "end": event.end})
return HttpResponse(events, content_type="application/json")
Note that Events is the model that I am trying to parse. After I collect the data from this model, I want to return it to my template using the following ajax code:
$.ajax({
url: 'getEvents/',
datatype: 'json',
type: 'GET',
sucess: function(data) {
alert(data.name);
}
});
In my urls.py:
url(r'^getEvents/', views.getEvents, name='getEvents'),
However, I think I am doing something wrong because it doesn't work. I have been stuck on this for hours...Any ideas?
EDIT:
Okay. When I append the getEvents to the url, I do see all the database objects together in a dict but it seems my ajax is not working. How do I parse this data? The data is in the form:
[{"start": "2017-02-06", "end": "2017-02-07", "name": "Capstone Meeting"},
{"start": "2017-02-07T0:00", "end": "2017-02-08", "name": "Capstone"},
{"start": "2017-01-31T0:00", "end": "2017-02-01", "name": "dasdsd"},
{"start": "2017-01-31", "end": "2017-02-01", "name": "hjb"}]
Here is what I have so far...
$.ajax({
url: 'getEvents/',
datatype: 'json',
type: 'GET',
sucess: function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
}
});

One of your errors is being caused by not using a JsonResponse in your view instead of an HttpResponse. Here’s how to fix that issue:
from django.http import JsonResponse
def getEvents(request):
eventList = Events.objects.all()
events=[]
for event in eventList:
events.append({"name": event.name, "start": event.start, "end": event.end})
return JsonResponse(events)
From the docs, the JsonResponse is
An HttpResponse subclass that helps to create a JSON-encoded response.
The reason that your regular HttpResponse didn’t work, is because you have to manually serialize the data to JSON when using an HttpResponse, e.g., something like:
import json
response_data = json.dumps(events)
return HttpResponse(response_data, content_type="application/json")
Otherwise, I think what will happen is that you will get a call to __repr__ on the events list which will get you python ast serialized data and not JSON serialized data.

First of all, there's a typo of your sucess function, it should be success.
Secondly, JSON response should be a dict object rather than a list, if you really want to get a JSON array response anyway, then you have to specify safe=False when you serializing the data by using JsonResponse(events, safe=False), otherwise you'll get a TypeError like TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.
So the code sample should be:
def getEvents(request):
eventList = Events.objects.all().values("name", "start", "end")
return JsonResponse({"events": eventList})
And for frontend:
$.ajax({
url: 'getEvents/',
datatype: 'json',
type: 'GET',
success: function(data) {
$.each(data.events, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
}
});

Related

DataTables Editor In MVC

I want to use DataTables Editor but I want full control over the post back rather than letting Editor-Server handle it. Is there a way to do this? I am able to specifiy the url in Ajax on the client side and it does post back to the Controller, the only problem is I cannot figure how to get the data out of the call.
This is the Ajax portion:
$(document).ready(function () {
editor = new $.fn.dataTable.Editor({
ajax: ({
url: "/../AnyController/Update",
dataType: "json",
contentType: "application/json",
type: 'POST'
}),
formOptions: {
inline: {
onBlur: true,
submit: 'all'
}
},
table: "#timetracker",
fields: [
{
label: "Date1:",
name: "Date1"
},
{
label: "Comment 1:",
name: "Comment1",
type: "textarea"
}
]
});
And this is the Contoller method:
[HttpPost]
public JsonResult Update(EditorReturnData wtd)
{
return Json(wtd);
}
I have tried using a variety of other method signatures but the value of wtd is always null. I have no problem loading the table just by passing Json data, but how to takeover the update process from datatables editor is eluding me.
I have one update. I could not figure out how the Get, Post and Put could all use the same Controller Method and the method takes no parameters, even for the Post and Put. Finally I figured out that Editor is passing the data in the Header and it could be accessed with Request.Body. From there it must be the Datatables dll that is doing the actual updates.
enter code hereI have found the best way to do this is to post back from ajax to a different Controller for Post and Put and you can get access to the return data from the HttpRequest body in the following manner.
public ActionResult Rest(HttpRequest request)
{
var stream = request.Body;
string url = new StreamReader(stream).ReadToEnd();
string newUrl;
while ((newUrl = Uri.UnescapeDataString(url)) != url)
url = newUrl;
I added this code to the RestController from the Datatables Dot Net Core Demo Rest example which can be downloaded from https://editor.datatables.net/
The Ajax looks like this
editor = new $.fn.dataTable.Editor( {
ajax: {
create: {
type: 'POST',
url: '/api/rest/create'
},
edit: {
type: 'PUT',
url: '/api/rest/edit'
},
remove: {
type: 'DELETE',
url: '/api/rest/remove'
}
},

Can Js and Model.findAll() unable to display data in UI

I have this code where i am trying to retrieve data from model.findall() and display in UI as table
model.js
define(['jquery', 'can'], function ($, can) {
var serviceModel = can.Model.extend({
findAll: function (params,servicename) {
return $.ajax({
type: 'POST',
dataType: 'JSON',
contentType: 'application/json',
url: 'data/+ servicename',
success: function (data) {
console.log("Success ");
},
error: function () {
console.log("Error");
}
});
}
}, {});
return serviceModel;
});
controller.js
serviceModel.findAll(params,"SP_table", function(data) {
if (data.status === "success") {
$('#idtable').dataTable().fnClearTable();
$('#idtable').dataTable().fnAddData(data.result);
}else{
alert("inside alert");
}
});
issue is in serviceModel.findAll() i am unable to get data inside serviceModel.findAll() because data is in the form of stored procedure or macro, which i am getting using "servicename" from function above
please let me know how to resolve this issue.
You can access the raw xhr data from the ajax call and convert it to an appropriate format by overriding the parseModels method:
https://canjs.com/docs/can.Model.parseModels.html
Overwriting parseModels If your service returns data like:
{ thingsToDo: [{name: "dishes", id: 5}] } You will want to overwrite
parseModels to pass the models what it expects like:
Task = can.Model.extend({ parseModels: function(data){ return
data.thingsToDo; } },{}); You could also do this like:
Task = can.Model.extend({ parseModels: "thingsToDo" },{});
can.Model.models passes each instance's data to can.Model.model to
create the individual instances.
In their example above, the response is a nested JSON: in yours, it is your procedure or macro. You have the opportunity here in parseModels to rewrite the response in the appropriate format.

Error when returning single json object after an ajax call in django

when i get multiple objects, it works fine but if i only get 1, it returns an error
views.py
def get_incident_personnel(request):
args = {}
store = Store.objects.get(store_id=request.POST['store'])
data = serializers.serialize('json', store)
return HttpResponse(data, mimetype='application/json')
and here is my ajax.js
$('#id_store').change(function() {
var store = $('#id_store').val();
$.ajax({
url: '/incidents/get_incident_personnel/',
type: 'POST',
dataType: 'json',
data: {
'store': store,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
success: function(data) {
console.log(data);
}
});
});
You can't use serializers.serialize on a model instance, only on a QuerySet. Use filter even though you know you're only going to get one object.
store = Store.objects.filter(...)

jquery ajax data shows [object Object]

I have a very basic ajax call to alert the data that was reported from the server
$.ajax({
type: "POST",
url: "/someform/act", //edit utl to url
data: { changed: JSON.stringify(plainData) }, //edit to include
success: function(data) {
alert(data); //data not $data
},
error: function() {
//error condition code
}
});
According to the docs on the jquery website regarding data field on the success callback, it says that data returned is the data from the server. However for some strange reason when I alert $data, I get [object Object]
I was expecting to see something like this, since that is what the server would send back
<status>0</status>
EDIT:
data is also passed along as the POST
You need to use JSON.stringify(data) in the alert to get anything readable.
Also, $data is a completely different variable name than data.
alert() prints the string representation of the arguments - hence if you pass an object, you'll get [object Object].
To inspect data, use console.log(data) better.
If you server send a JSON, you need to put dataType: 'json' to your ajax call. Be aware there's some mistake in your ajax call.
$.ajax({
type: "POST",
url: "/someform/act", // NOT 'UTL',
data: {
key: value,
key2: value2
},
// or data: plaindata, // If 'plaindata' is an object.
dataType: 'json',
success: function(data) {
console.log(data); // As moonwave99 said
},
error: function() {
//error condition code
}
});
EDIT
When sending data, you should send an object. jQuery will handle the array to sned it to the server. So if plain data is an object, it should be like this
data: plainData,
If you're sending data via $.ajax({...}), the Network tab of your browser inspector might be showing [object Object] in the Payload (Chrome) / Request (Firefox) sub-tab, like in the following image (Firefox):
The reason for this might be in the way you're forming your AJAX call. Specifically:
$.ajax({
url: '/ajax/example-endpoint',
data: {'fooKey':fooData,'barKey':barData},
type: 'post',
cache: false,
contentType: false, // this one will turn your data into something like fooKey=fooData&barKey=barData
processData: false, // and this one will make it [object Object]:""
beforeSend: function() {
// whatever it is you need to do
},
success: function(data) {
// do stuff
},
error: function(desc, err) {
// do stuff
}
});
When combined, contentType: false and processData: false turn your data into [object Object], because you're actually telling your AJAX call to ignore the content type of whatever is being sent, and not to process it.
If it's IIS, try creating a site outside of the Default Web Site (for example localhost/ajax1). For example a new site ajax1, place it not in the DefaultAppPool, but in your pool, for example ajax1. Try http://ajax1

MooTools: How do package data for a POST ajax request?

I'm using MooTools 1.4.1. I want to create an ajax post requst, but I can't figure out how to construct the "data" attribute, which I wish to contain the name value pairs of a form whose id is "myForm".
$('save').addEvent('click', function(event) {
var req = new Request({
method: 'post',
url: 'save',
data: { ... },
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
});
});
Anyone know how I should populate the "data" attribute? Thanks, - Dave
You can use
$('myForm').toQueryString();
Alternatively, The MooTools More package has a Form.Request() class to send a Form using Ajax.
As Savageman commented, you can throw your form element into toQueryString() and send it through in the data property, or by running .send() or .post() on the request object.
You also seem to be missing a closing squiggly bracket.
Anyhow, this is how I make AJAX requests:
new Request({
url: 'http://url/to/ajax/script.php',
onSuccess: function(data) {
doStuff();
}
}).post('action=foo&bar=baz');
I'd recommend you use Request.JSON if you're planning on sending stuff back. It's less "shotgun approach"-ey.
You can just pass form element to "data" property, and conversion is automatic.
var req = new Request({
method: 'post',
url: 'example.com/form.php',
data: $('myForm'),
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
}
});
data - (mixed: defaults to '') The default data for Request:send, used when no data is given. Can be an Element, Object or String.
If an Object is passed the Object:toQueryString method will be used to convert the object to a string.
If an Element is passed the Element:toQueryString method will be used to convert the Element to a string.
http://mootools.net/docs/core/Request/Request

Resources