Post selected rows with jquery to a Django 1.5 view - ajax

I have a table with multiple <tr> which each has a PK as ID. I am going to POST these <tr> to a Django 1.5 view, but I don't know how to send the data properly.
I've made this javascript function, and it posts successfully, but I don't know how to send the id's of selected_rows, and how to retrieve them in a class based Django view.
function update() {
var selected_rows = $(".ui-selected");
$.ajax({
type: "POST",
url: "/confirm/",
data: { name: "selected_rows" },
success: function(data) {
selected_rows.addClass('success');
}
});
}
I guess the Django view is something like
class ConfirmView(TemplateView):
def post(self, queryset=None):
return HttpResponse("POST")
I've also tried
function update() {
var selected_rows = $(".ui-selected");
selected_rows.each(function() {
$.ajax({
type: "POST",
url: "/confirm/",
data: { id: $(this).attr("id") },
success: function(data) {
$(this).addClass('success');
}
});
});
}
and
class ConfirmView(TemplateView):
def post(self, queryset=None):
if self.request.POST['id']:
ModelName.objects.filter(pk=self.request.POST['id']).update(is_confirmed=True)
return HttpResponse("POST")
But I guess it's better to handle all the rows in the same database query instead of splitting them as above. But if I split them as above, I could check whether or not they were updated successfully, so maybe it's better that way?

You need to do:
data: { name: selected_rows } //Do not put selected_rows in quotes
Also why are you using TemplateView here, it doesn't give you any advantage. You just need to create something and send a response which ajax will handle. You can just use a function view here.
If you use class based view, your signature of post has a bug:
It should be:
def post(self, request, *args, **kwargs):
name = request.POST['name']

Related

django ajax return more than one piece of html and mount

Because of a limitation in bootstrap modals that they need to be outside a postion: fixed, I need to return 2 separate pieces of html in django after an ajax response (a list of items and their modals)
Is there a way in django to return 2 pieces of redendered html?
Currently I have in the ajax view I return a single piece of html with:
return render(request, 'pages/results.html', context)
which I mount with:
$.ajax({
url: '/users/some_ajax_view/',
data: {
'filters': filters
},
success: function (data) {
$('.ajax-block').html(data)
}
})
Best solved with using the render_to_string() method and then sending multiple pieces of html via a JsonResponse to then be mounted on the front end.
eg
in your view:
modals_html = render_to_string('components/modals.html', context)
quotes_html = render_to_string('components/list.html', context )
return JsonResponse({'list': list_html,
'modals': modals_html})
then in the front end mount with:
$.ajax({
url: '/users/some_ajax_view/',
data: {
'filters': filters
},
success: function (data) {
$('#list').html(data.list)
$('#modals').html(data.modals)
}
})

In Django ,ajax to send the variable by Restful Api

I am a rookie in the Restful,I want to send some variables to the viewset to response some filtering data by "GET"Now I have finished some parts ,I can get the all data,but I don't understand how to send variables to a specific function in the viewset to response some filtering data , for example I crate a new function called "get_ajax_variable() " ,How could I to send variables to the
specific function ?
appreciate in Advance!
This is my Serializer
class CompanySerializer(serializers.HyperlinkedModelSerializer):
Brand = serializers.ReadOnlyField(source='brand_set.all', read_only=True)
class Meta:
model = Company
fields = data_export_setting.Company_form_stand
def create(self, validated_data):
validated_data['owner'] = self.context['request'].user
return Company.objects.create(**validated_data)
This is my viewset
class CompanyViewSet(viewsets.ModelViewSet):
queryset = Company.objects.all()
serializer_class = CompanySerializer
this is my ajax,the function of "showTable(json)" is a function to reload my company.html
<script type="text/javascript">
$(document).ready(function () {
$('#ab').click(function () {
var filter_2 = $("#insert_value").val();//for City
var filter_1 = $("#insert_value_1").val();// for Company type
var filter = $('#filter').val();//for search
$.ajax({
type: "GET",
data: {filter:filter, filter_1_value:filter_1,insert_value:insert_value},
url: "https://horizon-retail-sam-leon-ghibli.c9users.io/restful_api/companyviewset/?format=json",
cache: false,
dataType: "json",
contentType : 'application/json',
success: function (json) {
$('#ajax_search').empty();
showTable(json);
},
error: function () {
alert("false");
}
});
});
});
since it's a GET, why dont you send them as url params ?
I should've replied as a comment but I don't have enough privilege to do it. So please bear with me.
I assume you are using Django Rest Framework(DRF) given the code and tags you put in the question.
Basically, this url: "https://horizon-retail-sam-leon-ghibli.c9users.io/restful_api/companyviewset/?format=json", allows you to send a request along with data to your REST API server, which is DRF in your setup. And urls.py in django get to know the value you sent and direct you to a certain view/viewset, for example, CompanyViewSet in your example.
And in terms of how the view/viewset works with a serializer, you can take a look at http://www.django-rest-framework.org/api-guide/serializers/
and http://www.django-rest-framework.org/tutorial/1-serialization/. And this should suffice. I am not sure about how data got transferred from view/viewset to the serializer. It would be great if someone could explain. But in your serializer, your data should be in validated_data.
In that view/viewset, your data should be in request.data for POST and in GET, it usually in query.params but this really depends on how you construct the ajax call.
It is important to know the difference between POST and GET. You can simply google it.
HTH.
Yes!I have solve this problem ,the following is my step
the most important step is to overwrite function get_queryset(self): in the class of Viewset
in the template ,the ajax is as follows:
<script type="text/javascript">
$(document).ready(function () {
$('#ab').click(function () {
var filter_2 = $("#insert_value").val();//for City
var filter_1 = $("#insert_value_1").val();// for Company type
var filter = $('#filter').val();//for search
$.ajax({
type: "GET",
//data: {filter:filter, filter_1_value:filter_1,insert_value:insert_value},
url:"You_own_url"+format=json&a="+filter+"&b="+filter_1+"&c="+filter_2,
cache: false,
dataType: "json",
contentType : 'application/json',
success: function (json) {
$('#ajax_search').empty();
showTable(json);
},
error: function () {
alert("false");
}
});
});
in the Setting of Django,you should set the REST_FRAMEWORKas
'DEFAULT_FILTER_BACKENDS':('django_filters.rest_framework.DjangoFilterBackend',),
in the Url of Django,you should set the url as follows:
router.register(r'companysearch',CompanyViewSet)
in the viewset,I did not pull all function of get_queryset, you should set as follows:
serializer_class = CompanySerializer
filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
def get_queryset(self):# how to define the null and None
filter_1 = self.request.query_params.get('a')#, None)
filter_company_type = self.request.query_params.get('b', None)# company_type
filter_city_type = self.request.query_params.get('c', None)
....
then you can get the result correctly ,thanks anyone who helps

How to make an ajax request to a view

I am trying to figure out how I can make an ajax request (with jquery) from my template in order to execute a view on a button click. I don't want to redirect to another page. I just need to execute the code in the view.
This is my on button click event:
$(document.body).on("click", "#download_xls",function(e) {
selected_country = ($("#button-countries").val())
selected_subareas = $('#_all_values').val();
id = "?country=" + selected_country + "&" + "regions=" + selected_subareas
whole_url = "{% url 'test_download' %}" + id
$("#download_xls").attr("href", whole_url)
});
As I pass the values in my URL, I don't even need to pass some parameters through the ajax request. I just need to execute the code in the view.
The view is something like this:
def test_download(request):
print(request.GET.get('country'))
print(request.GET.get('regions'))
fileContent = "Your name is %s"
res = HttpResponse(fileContent)
res['Content-Disposition'] = 'attachment; filename=yourname.txt'
return res
EDITED
I have added the ajax GET request in my template as:
whole_url = "{% url 'test_download' %}"+id
$.ajax({
type: "GET",
url: whole_url,
success: function(data) {
alert('sd')
},
error: function(data) {
alert('error')
},
});
I get an error cause there is no corresponding template for this view. I think I need to add something in the urls.py file.
I read here that I need to modify urls.py as:
url(r'^link-to-fun1$', views.fun1),
But its not clear to me what should be the link-to-fun1.
I tried:
url(r'^create$', 'test_download', name='test_downlad'),
But gives an error: No Reverse Match.
You could use TemplateView add to your url and use JQuery to do something, like this:
views.py
class ajax_view(TemplateView):
def get(self, request, *args, **kwargs):
id_value = request.GET['id']
value = Model.objects.filter(id=id)
data = serializers.serialize('json', value, fields=('fieldone'))
return HttpResponse(data, content_type='application/json')
urls.py
url(r'^ajax/$', ajax_view.as_view()),
JQuery
$.ajax({
data: { 'id': id },
url: '/ajax/',
type: 'get',
success: function (data) {
// Do something with the data
}
})
That's in general how you can use Ajax with Django, the important is the use of TemplateView

Retrieve post value in the controller sent by ajax call

I am unable to retrieve value sent as a post through ajax call in cake php controller file
$.ajax({
type: "POST",
url: "share",
data: country,
dataType: "json",
success: function (response) {
if (response.success) {
// Success!
} else {
console.log(response.data, response.code);
}
}
});
I have tried with the below ways of retrieving the data sent in the above code through POST. But none of them worked.
$this->params
$this->data
$_POST[]
$this->request
The url points to the function in the controller page.
Please can any of you let me know how the value can be retrieved.
When submitting data via ajax and you want cake to pick it up in the usual way just use $('whatever').serialize().
if you don't have an actual form to serialize you can fake it by submitting the data as follows:
$.ajax({
...
data: {
data: country
},
...
});
Note how cake generates fields like data[Model][field]. you don't need the Model part but the data part is important.

Multiple Ajax PUTs in Laravel 4 Giving Errors

I am updating my Model through a resource controller via jQuery Ajax Put. No problems at all the first time. This works fine:
$(".addNest").click(function() {
var nid = msg; //once the LI is added, we grab the return value which is the nest ID
var name = $('.nestIn').val();
if(name == '') {
$("textarea").css("border", "1px solid red");
}else {
$.ajax({
type: 'PUT', // we update the default value
url: 'nests/' + nid,
data: {
'name': name
},
success: function(msg) {
alert(msg)
window.location.replace('nests/' + nid ); //redirect to the show view
}
});
}
});
Later in a separate code block, I try to call the PUT again like this:
$(".nestEdit").click(function() {
$(".nestEdit").hide();
var name = $('.nestName').data("name");
var nid = $('.nestName').data("id");
$(".nestName").html("<textarea class='updateNest'>"+ name +"</textarea> <span><a href='#' class='btn btn-mini nestUpdate'><i class='icon-plus'></i> Update</a></span>");
$(".nestUpdate").click(function() {
var updatedName = $('.updateNest').val();
$.ajax({
type: 'PUT', // we update the default value
url: 'nests/' + nid,
data: {
'name': updatedName
},
success: function(msg) {
alert(msg) // showing the error here
location.reload( ); //refresh the show view
}
});
});
The 'updatedName' values and the 'nid' values are passing fine when I 'alert' them. When I view the return for the first PUT it comes back fine. However, when I view the return for the second PUT I get this:
{"error":{"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException","message":"","file":"\/Applications\/MAMP\/htdocs\/n4\/bootstrap\/compiled.php","line":8643}}
Anyone have some insights here? As you can tell, I am trying to do an inline edit. I have tried to wrap everything into a function but still not helping...
Laravel does not use PUT and DELETE natively since it is not supported in all browsers, you need to send a POST request with '_method' set to either put or delete.
$.ajax({
type: 'POST',
url: 'nests/' + nid,
data: {
'name': updatedName,
'_method': update
},
success: function(msg) {
alert(msg) // showing the error here
location.reload( ); //refresh the show view
}
EDIT: Ajax request do support PUT AND DELETE.
In your JavaScript code, for the inline editing, you are not making proper use of $.
If you click on .nestEdit, it's inner function should not be calling it by name, provided you have multiple objects of the same class on that page. This is why you get the error. Instead of sending the nest ID, it's sending an array object, which your Laravel Router will not pick up, because it is more than likely not defined.
Simply put, you should not be doing this:
$(".nestEdit").click(function() {
$(".nestEdit").hide();
...
You should be making a call to this:
$(".nestEdit").click(function() {
$(this).hide();
...
So, for every .nestEdit within the inner function, you need to call for this instead.

Resources