I want to pass array data in views.py file for that I use AJAX and passing data through AJAX. But there I am not able to get all data in views.py file, some of the data are missing.
display.html
var SelectedID = [];
function getvalues() {
$(':checkbox:checked').each(function (i) {
SelectedID[i] = $(this).val();
console.log("Selected Data", SelectedID[i])
$.ajax({
url: "{% url 'addtoexisting' bid=adduser.id %}",
type: "POST",
dataType: "json",
data:{
SelectedID : SelectedID[i],
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (data) {
console.log("Selected Data AJAX", SelectedID)
alert("Successfully sent the Data to Django");
},
error: function (xhr, errmsg, err) {
// alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
}
});
});
}
views.py
def display(request):
is_ajax = request.headers.get('x-requested-with') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
SelectedID = request.POST.get('SelectedID')
print(SelectedID)
return render(request, 'display.html',{})
SelectedID[i] = $(this).val(); in this selectedID There are 10 records but in print of views.py there is only 6 records, other data are missing.
Related
Currently using the django-carton app, I have a django view that returns JSON data that I use in an ajax call. Broadly speaking, I have got it working but struggling to work out how I can pass my item quantity (using ajax).
Within the template I can call my item quantities using:
{% for item in cart.items %}
{{ item.quantity }}
The ajax call connects to the view to return the Json data:
def cart_detail_api_view(request):
# cart_obj, new_obj = Cart.objects.new_or_get(request)
cart = Cart(request.session)
products = [{"name": x.name, "price": x.price} for x in cart.products]
cart_data = {"products": products, "total": cart.total}
return JsonResponse(cart_data)
This is my Jquery/Ajax call:
$(document).ready(function() {
var productForm = $(".form-product-ajax") // #form-product-ajax
productForm.submit(function(event) {
event.preventDefault();
// console.log("Form is not sending")
var thisForm = $(this)
//var actionEndpoint = thisForm.attr("action");
var actionEndpoint = thisForm.attr("data-endpoint");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax({
url: actionEndpoint,
method: httpMethod,
data: formData,
success: function(data) {
var submitSpan = thisForm.find(".submit-span")
if (data.added) {
submitSpan.html("In cart <button type='submit' class='btn btn-link'>Remove?</button>")}
var currentPath = window.location.href
if (currentPath.indexOf("") != -1) {
refreshCart()
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
})
function refreshCart() {
console.log("in current cart")
var cartTable = $(".cart-table")
var cartBody = cartTable.find(".cart-body")
// $(cartBody).empty()
var productRows = cartBody.find(".cart-product")
var cartTotal = cartTable.find(".cart-total-sec")
var currentUrl = window.location.href
var refreshCartUrl = '/api/cart/'
var refreshCartMethod = "GET";
var data = {};
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
success: function(data) {
console.log("success")
console.log(data)
if (data.products.length > 1) {
$(cartBody).empty()
productRows.html("")
$.each(data.products, function(index, value) {
console.log(value)
console.log(data.count)
cartBody.append("<tr><td>" + value.name + "</td><td>" + value.price + "</td></tr>")
})
cartTotal.find(".cart-total").text(data.total)
console.log(data.total)
} else {
window.location.href = currentUrl
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
}
})
You have to instruct your $.ajax() call that you are expecting data in JSON format, so the data is parsed properly in your success callback:
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
dataType: 'json', // <- here
success: function(data) {
// ...
},
error: function(errorData) {
// ...
}
})
I have a dictionary of arrays that I would like to pass to my Django view.
$.ajax({
url: '/fund_monitor/fund_directory',
type: 'GET',
data:{
filter_dict: filter_dict,
},
success: function (data) {
console.log(filter_dict);
}
});
And in my view I would like to receive this dict:
if request.is_ajax():
filter_dict = request.GET.getlist('filter_dict')
print("Is Ajax", filter_dict)
But "Is Ajax []" gets printed out and just as an example, my filter_dict:
Designated Broker:["BMO"]
Fund Class:["OM"]
Any ideas why a blank array gets passed?
$.ajax({
url: '/fund_monitor/fund_directory',
type: 'GET',
data:JSON.stringify({
filter_dict: filter_dict,
}),
success: function (data) {
console.log(filter_dict);
}
});
if request.is_ajax():
request_data = json.loads(request.GET)
filter_dict = request_data['filter_dict']
print("Is Ajax", filter_dict)
Totally unclear 404 Ajax error.
var int_page_number = 2;
$.ajax({
type:'GET',
url: '/loadmore/',
data: { 'page_number' : int_page_number},
dataType: 'json',
success: function (data) {
alert(data);
}
});
In the place passing data, I tried both using apostrophe and not around page_number. It's 404 so error may be in frontedn, but anyways I attach django urls.py string just in case :
url(r'^loadmore/(?P<page_number>[0-9]+)/$', views.loadmore),
and views.py function, which is all right:
#api_view(['GET', ])
def loadmore(request,page_number):
answers_to_questions_objects = Question.objects.filter(whom=request.user.profile).filter(answered=True).order_by('-answered_date')
paginator = Paginator(answers_to_questions_objects,10)
current_page = (paginator.page_number)
answers = serializers.serialize('json', current_page)
data = {
'answers': answers
}
return Response(data)`
For your url you should make a call to the url like /loadmore/2/, but you make the call like /loadmore/?page_number=2. So your ajax should be like this:
var int_page_number = 2;
$.ajax({
type:'GET',
url: '/loadmore/' + int_page_number + '/',
success: function (data) {
alert(data);
}
});
I have two different AJAX requests that I want to combine.
The first one gets some html:
def ajax_get_html(request):
if request.is_ajax() and request.method == "POST":
context = {
...
}
return render(request,"my_app/my_template.html", context)
else:
raise Http404
And is used like this:
$.ajax({
type: "POST",
url: ajax_url,
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function(data){
$(my_div).html(data);
}
});
My second one gets some data:
def ajax_get_data(request):
if request.is_ajax() and request.method == "POST":
data = {
"answer": 42,
}
json_data = json.dumps(data)
return HttpResponse(json_data, content_type='application/json')
else:
raise Http404
and is used like this:
$.ajax({
type: "POST",
url: another_ajax_url,
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function(data){
var answer = data.answer;
$("#notification_badge").html(answer);
}
});
How can I combine these to into the same request? I tried adding the result of render to the data in the second view, but json.dumps says it's non serializable.
You can't serialize the output of Django's render because it returns an HttpResponse object, not a string (which is what you want to be able to serialize it).
A good solution is to return your html to the frontend using render_to_string:
...
data = {
"answer": 42,
"html": render_to_string("my_app/my_template.html", context)
}
...
I have this connection with ajax, I put a print in the formulario result and in the python in the bash I get the result from the select like this:
[{"pk": 1, "model": "pagoproveedores.test", "fields": {"just_a_test": "google"}}]
the problem is that when I want show it in the template it send me Server Response: undefined. Looks like I'm not getting the response from the view, I know I have the data that I need.
view.py
def ajax(request):
print 'inside ajax'
if request.POST.has_key('client_response'):
print 'inside if'
x = request.POST['client_response']
y = test.objects.filter(just_a_test=x)
formulario = serializers.serialize('json', y)
return HttpResponse(formulario, mimetype="application/json")
else:
return render_to_response('ajaxexample.html', context_instance=RequestContext(request))
Ajax.html
$(document).ready(function () {
$("#button").click(function () {
var input_string = $("#forminput").val();
$.ajax({
url: "/ajaxexample_json",
type: "POST",
dataType: "json",
data: {
client_response: input_string,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (json) {
$('#result').append('Server Response: ' + json.server_response);
},
error: function (xhr, errmsg, err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});
Instead
return HttpResponse(formulario, mimetype="application/json")
do
return HttpResponse(formulario, content_type="application/json")
I Fix it using this code and same view, ;)
$(document).ready(function () {
$("#button").click(function () {
var input_string = $("#forminput").val();
$.ajax({
url: "/ajaxexample_json",
type: "POST",
dataType: "json",
data: {
client_response: input_string,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (json) {
var jsonResponse = eval(json);
$.each(jsonResponse, function(index, element){
alert(JSON.stringify(jsonResponse));
$('#resultTables').append('<tr><td align="center">'+jsonResponse[0]["pk"]+'</td> <td align="center">'+jsonResponse[0]["fields"]["nombre_miembro_1"]+'</td> <td align="center"></td></tr>');
}); ;
},
error: function (xhr, errmsg, err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});