In Django ,ajax to send the variable by Restful Api - ajax

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

Related

Object property name changes when parsing it to node js

I have an object:
{"description":"Κλείσε τις βάνες","closeValves":["13/21","12/31","13/12","12/32"]}
and when i am sending it to node js with ajax the moment it gets into the router.post it transforms into this
{"description":"Κλείσε τις βάνες","closeValves[]":["13/21","12/31","13/12","12/32"]} ..
Any ideas why this is happening? in the node script where i have the router.post i am requiring this
let express = require('express');
let router = express.Router();
Update at comment:
the call the function:
formEvent(json,'events/entry',valvescallback);
and the function AJAX:
function formEvent(data,module,next,e){//the request function
e=e||false;
console.log("form:",data)
if( e ){e.preventDefault();}
var url = './'+module; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: data,
dataType:'json',
success: function (data) {
next(data);
},
error:function (data) {
next(data)
}
});
}
Update at comment 2:
No the data come from postgress SQL in a text type column like this
{"description":"Κλείσε τις βάνες","closeValves":["13/21","12/31","13/12","12/32"]}
and i am using this to transform it into json and parse it:
var json = jQuery.parseJSON(data.task);
json.action = 'getValves';
json.test = json.closeValves;//test to see if it also changes name
I can see that it transformes any property that is an array like this
name:[1,2,3] --> name[]:[1,2,3]
the odd is that when I am console.log the data inside the AJAX function the are in the right form but inside the post they change..
I found it!! the answer is at the definition of the body-parser npm usage:
app.use(bodyParser.urlencoded({ extended: false}));
you just need to make the extended property true and the array name will not change.. so the answer is
app.use(bodyParser.urlencoded({ extended: true}));

Unable to display queryset using ajax and Django

I'm not able to display queryset while using ajax
here is my views.py:
if request.user.is_authenticated():
productid = request.GET.get('productId')
print productid
if request.is_ajax():
try:
queryset= StoreProduct.objects.get_size(productid)
except:
queryset= None
data = {
"queryset" : queryset
}
return JsonResponse(data)
Here is my ajax script:
<script type="text/javascript">
function getStoreView(event, productId) {
event.preventDefault();
var data = {
productId : productId
}
$.ajax({
type: "GET",
url: "{% url 'storeView' user=store.user %}",
data: data,
success: function(data) {
console.log(data.queryset)
},
error: function(response, error) {
alert(error);
}
});
};
</script>
What should I do to solve the problem above?
Thanks in advance
If you look at the error message from Django, you will see it complaining that the queryset is not JSON serializable. For ajax requests, you can see the response using your web browser's development tools when DEBUG=True.
The first thing to do is to use values(), which returns a queryset containing dictionaries for each instance in the queryset. Secondly, you need to coerce the queryset into a list.
queryset = StoreProduct.objects.get_size(productid)
values_list = list(queryset.values())
You cannot send queryset directory as json, because json is just a string. You could use django serializer to apply to your queryset:
from django.core import serializers
serialized_qs = serializers.serialize('json', queryset)
data = {"queryset" : serialized_qs}
return JsonResponse(data)
Also in your javascript you have to do data['queryset'] to access your queryset as json.

Ajax post request from Backbone to Laravel

I'm trying to send a Backbone collection to Laravel with an Ajax Request.
I don't need to save it or update the database I just need to process the data with the Omnypay php Api. Unfortunately the Laravel Controller variable $input=Input::all() contain an empty string.
var url = 'index.php/pay';
var items = this.collection.toJSON;
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: items,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
This is the Laravel Route:
Route::post('pay','PaypalController#doPay');
And finally the Laravel Controller:
class PaypalController extends BaseController {
public function doPay() {
$input=Input::all();
}
}
Your route doesn't match, it's
Route::post('pay','PaypalController#doPay');
So the url should be
var url = 'pay';
instead of
var url = 'index.php/pay';
BTW, not sure if anything else (backnone) is wrong.
Update : toJSON is a method, so it should be (you missed ())
var items = this.collection.toJSON();
The hack solution I found to transfer a backbone collection to Laravel was to convert the collection to JSON and then wrapping it in a plain object, suitable for the jQuery Ajax POST. Here is the Code:
var url = 'index.php/pay';
var items = this.collection.toJSON();
var plainObject= {'obj': items};
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: plainObject,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
Now the $input variable of my "doPay" controller function contain an array of Backbone models.

Post selected rows with jquery to a Django 1.5 view

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']

Ajax call failing in Django

I have the following ajax call to update a particular field of a model
$("#updateLink").click(function(){
var dec_text = $('#desc_text').val();
$.ajax({
type: "POST",
url:"/users/update_desc/",
data: {
'val': dec_text,
},
success: function(){
$(".display, .edit").toggle();
$("#descText").html(dec_text);
},
error: function(){
alert("Error");
},
});
return false;
});
and my view is this
#csrf_exempt
def update_desc(request):
if request.is_ajax():
if request.method == 'POST':
desc_text = request.POST.get('val', False)
if desc_text:
profile = user.profile
profile.desc = desc_text
profile.save()
return_message = "Sent mail"
return HttpResponse(return_message,mimetype='application/javascript')
I am constantly getting an error message and I don't know how to solve this. I even used the csrf_exempt decorator to workaround if the problem was caused by a missing csrf token but still the problem persists.
Except one ajax post which in my base template all the ajax calls are failing. Can anybody please help to understand what is happening here. I can give some more details if required.
Edit:
I have added the a js file containing this https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax in my base template, so it means it is present in all my templates. And I am using django 1.3 version.
Firstly, you are using POST and not sending a csrf token. Try explicitly sending the csrf token rather than using the decorator csrf_exempt.
One way of doing this is with what I have done in data. That is to fetch the csrf token (or from your own method) and pass it in your arguments.
$.ajax({
url : url,
type: "POST",
data : {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value},
dataType : "json",
success: function( data ){
// do something
}
});

Resources