How to return a string in a class based view using ajax - ajax

I want to transmit a string from a class based view to the client via ajax.
Here's my view, which inherits from another view
class TeamCreateView_Ajax(TeamCreateView):
def render_to_response(self, context, **response_kwargs):
return HttpResponse("asdf")
For some reason, this transmits the entire web page that would've been rendered by TeamCreateView instead of the string "asdf".
class TeamCreateView_Ajax(TeamCreateView):
def dispatch(self, request, *args, **kwargs):
return HttpResponse("asdf")
On the other hand, this correctly transmits "asdf".
What gives?

Usually, using ajax, we communicate using either json/xml to send information from server to webpage. For example:
class SomeView(TemplateView): #I used template view because it has get method
def render_to_response(self, context, **response_kwargs):
data = {}
data['some_data'] = 'asdf'
return HttpResponse(json.dumps(data), content_type="application/json")
And in Script:
$.ajax({ url: url,
type: "get",
success: function (data) {
alert(data.some_data);
})

Related

AspNetBoilerplate Ajax repose error despite 200 response code

Im having some unexpected problems with a ajax call within the aspnetboilerplate system.
I want to return an array to populate a select list,
The ajax call fires correctly and hits the controller. The controller returns the results as a model successfully, except it continually hits an error.
here is my controller action:
public async Task<List<DialectDto>> GetAllDialects(int Id)
{
var language = await _languageAppService.GetLanguage(Id);
return language.Dialects;
}
Here is my ajax call
var languageId = $(this).val();
abp.ui.setBusy('#textContainer');
$.ajax({
url: abp.appPath + 'Language/GetAllDialects?Id=' + languageId,
type: 'POST',
contentType: 'application/json',
success: function (content) {
abp.ui.clearBusy('#textContainer');
},
error: function (e) {
abp.ui.clearBusy('#textContainer');
}
});
Inspecting the return object in javascript clearly shows a 200 result with all the data in the responsetext property.
Other posts suggest that the content type isnt specified correctly and this is likely the a json parse error. Ive tried setting the dataType property to both 'json' and 'text' but still get the same response
I just had the same problem in one project. I'm using AspNet Boilerplate on a web .NET5 project.
Just like in your case I had a call to a controller method in my JavaScript code that returned 200 code, while in JS I had a parse error and then the "success" code was not executed. To solve the problem I changed the return value of my controller method. I used to return an IActionResult value (i.e. the Ok() value for ASP.NET). Then I changed the return value to another object (a DTO in my case) and everything went right afterwards. For reference:
Before (not working):
[HttpPost]
public async Task<IActionResult> Method([FromBody] YourClass input)
{
// method logic
return Ok();
}
After (working):
[HttpPost]
public async Task<DtoClass> Method([FromBody] YourClass input)
{
// method logic
return dtoClass;
}
I also tested that returning a JsonResult class works with the framework just like this (e.g. return new JsonResult(result)).
Hope this helps somebody else in the future :)

Overriding generic.ListView methods for AJAX requests DJANGO

I recently started using django's inbuilt generic views (Create, Update, etc) So I'm updating most of my old views to use them, one of them is the ListView, with pagination. So now, it works right,when i GET that page, it displays the objects as directed, and the pagination works fine. But i want to use AJAX on the pagination so that i just click a "More" button and it gets the next page's objects via ajax and are appended onto the end of the . So i've modified some generic views before to incorporate AJAX like the:
class Delete(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
login_url = LOGIN_URL
model = Items
success_url = reverse_lazy('web:member-area')
def test_func(self):
return not self.request.user.is_superuser and self.get_object().created_by == self.request.user
def delete(self, request, *args, **kwargs):
response = super().delete(request)
if self.request.is_ajax():
return JsonResponse({'success': 1}, status=200)
else:
return response
In the above snippet you can see i included the part where it returns something different if the request is AJAX
The current View that i'm working on is as follows:
class Items(ListView):
model = Items
paginate_by = 5
context_object_name = 'items'
template_name = 'web/items/index.html'
which works fine on normal GET requests, so the problem is i dont know which super() method(s) to override and return a different response if its AJAX on that ListView
Use dispatch
class Items(ListView):
def dispatch(request, *args, **kwargs):
response = super().dispatch(request, *args, **kwargs)
if request.is_ajax():
return JsonResponse({'success': 1}, status=200)
else:
return response

How to restrict the ajax call from out side of the browser in django

i am working in a project, there is no user authentication and authorization. Bascially i am calling ajax in client side and it executes a view in django and return a json out. How can i validate this request is only coming from browser and how to restrict the if this not coming from the browser or any manual script?
You can use request.is_ajax() method
HttpRequest.is_ajax()
Returns True if the request was made via an XMLHttpRequest, by checking the HTTP_X_REQUESTED_WITH header for the string 'XMLHttpRequest'. Most modern JavaScript libraries send this header. If you write your own XMLHttpRequest call (on the browser side), you’ll have to set this header manually if you want is_ajax() to work.
If a response varies on whether or not it’s requested via AJAX and you are using some form of caching like Django’s cache middleware, you should decorate the view with vary_on_headers('HTTP_X_REQUESTED_WITH') so that the responses are properly cached.
docs
Im updating my answer to fit what we commented above
In your views
from django.core import signing
from django.views.generic import View, TemplateView
from django.http import HttpResponseBadRequest
class BrowserView(TemplateView):
template_name = 'yourtemplate.html'
def get_context_data(self, **kwargs):
ctx = super(BrowserView, self).get_context_data(**kwargs)
ctx['token'] = signing.dumps(self.request.session_id)
return ctx
class AjaxView(View):
def get(self, *args, **kwargs):
if self.request.is_ajax():
try:
sign = signing.loads(self.request.GET.get('token'), max_age=(20))
if sign == self.request.session_id:
## return ajax
return HttpResponseBadRequest('You are not authorized to see this page')
except signing.BadSignature:
return HttpResponseBadRequest('You are not authorized to see this page')
else:
return HttpResponseBadRequest('You are not authorized to see this page')
In your template
In this case I used a meta tag, but you get the idea
<meta name="validation" content="{{token}}" />
In your javascript
var t = document.querySelector("meta[name='validation']").getAttribute('content');
$.ajax({
url:'yoururl',
data: yourData + '&token=' + t,
type: 'get',
success: function(response){
// do whatever
},
error: function(e){
console.log(e);
}
});
I don't believe it's possible to 100% prevent this, but there are some things you can do:
a set-cookie header w/some unique ID on the page, but not on API responses.
if the cookie isn't received by your API, return a 401.
tracking API calls per unique ID could be a good indicator of "proper" usage.
associate IDs w/IPs.
the tracking metrics can be combined w/a threshold that blocks requests if exceeded.
you can check the referrer header (easy to spoof).
finally, lookup the is_ajax method of Django's, but this just checks for an XMLHttpRequest header (again, easy to spoof).

Deserializing into derived class in ASP.NET Web API

In my last SO question, I asked how to modify the serializer settings for Json.NET, which ASP.NET Web API natively uses for (de)serialization. The accepted answer worked perfectly, and I was, for example, able to embed type information into the serialized JSON string.
However, when I try to throw back this JSON string to a Web API action that's expecting the model's parent class, Web API still deserializes to the parent class, removes all data corresponding to the child class, and prevents casting to and detection of the child class.
class Entity { }
class Person : Entity { }
public Person Get() {
return new Person();
}
public bool Post(Entity entity) {
return entity is Person;
}
A simple use case would be doing something like this in jQuery:
// get a serialized JSON Person
$.ajax({
url : 'api/person' // PersonController
}).success(function (m) {
// then throw that Person right back via HTTP POST
$.ajax({
url : 'api/person',
type : 'POST',
data : m
}).success(function (m) {
console.log(m); // false
});
})
I'd expect that by modifying the JsonSerializerSettings of Json.NET to embed type information that it'd be able to read that and at the very least, try to force deserialization to that type, but apparently it does not.
How should I tackle something like this?
Web API really doesn't do any (de)serialization "natively". It happens to have a few MediaTypeFormatters included in the config.Formatters collection by default. Feel free to remove those and create your own MediaTypeFormatter that handles the serialization the way you want it to be done.
MediaTypeFormatters are really not that hard to create.
Actually the 2nd POST call is sending application/x-www-form-urlencoded data and that's why the type information is not picking up by the JsonMediaTypeFormatter. Try setting the contentType to be "application/json".
Also, the data in the 2nd POST request body seems to be encoded and it needs to be decoded before sending back to the service.
I was able to get this to work:
// get a serialized JSON Person
$.ajax({
url: 'api/person' // PersonController
}).success(function (m) {
// then throw that Person right back via HTTP POST
$.ajax({
url: 'api/person',
type: 'POST',
contentType: "application/json",
data: JSON.stringify(m),
}).success(function (m) {
alert(m); // true!
});
})

What Goes in the Controller for an AJAX get request in GRAILS

I have an AJAX call in my view,
var ajaxData= $.ajax({
type: "GET",
url: "${createLink(controller:'profile',action:'ajaxList')}",
success: function(data) {
}
});
I created a method in the ProfileController.groovy class in order to return "data" from this call, but I don' know how to format the controller correctly. Here is what I want to return. The model, profile, has a name and a description. I want to return a hash object where the key is the name and the value is the description. Is there a way to do this in the controller so that this ajax call returns that hash. Any help would be aprpeciated. Thanks!
In your controller's ajaxList action build your model as you want it, as usual, and then instead of return model at the end you want to render model as JSON.
For example,
class ProfileController {
def ajaxList() {
def profiles = Profile.list()
def model = profiles.collect { [(it.name): it.description] }
render model as JSON
}
}
And if you want to use the same list action for returning different formats, look at using withFormat.

Resources