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)
Related
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.
So I am using axios in order to send a JSON request to Django API.
axios({
method: 'post',
url: 'http://127.0.0.1:8000/' + this.state.dataRequestEndPoint,
data: (reqData)
});
Just before the axios call I can see the request:
Object {nvm: "", a: Array(1), b: Array(1), c: Array(1), d: Array(1)}
However, when it gets to Django:
class TargetClass(APIView):
def get(self, request):
Here request is empty:
(Pdb) request.data
<QueryDict: {}>
(Pdb) request.body
b''
def post(self):
pass
What am I doing wrong?
P.S. Tried to send the request with fetch as well:
fetch('http://127.0.0.1:8000/' + this.state.dataRequestEndPoint, {
method: 'POST',
body: reqData,
})
None of it works.
Here is the solution for the problem above. Apparently, axios needs to send parameters:
var reqData = this.state.requestParams
axios({
method: 'post',
url: 'http://127.0.0.1:8000/' + this.state.dataRequestEndPoint,
params: {
'a': reqData['a'],
'b': reqData['b']
}
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
});
However, I don't know how good this solution is security-wise.
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 built a webserver in Flask and I'm passing in the request using jsonp. One of the things I pass in is an nested array and when I retrieve the data in Flask, the array is completely messed up.
Here's my code
index.html
var array = [[2,1],[2,2],[2,3]]
function getNext() {
var data = {
'M': 5,
'N': 5,
'array' : array
};
$.ajax({
url: '/getNewGeneration',
jsonp: 'callback',
dataType: 'jsonp',
data: data,
success: function(response) {
...
}
});
}
server.py
#app.route('/getNewGeneration')
def getNext():
M = request.args.get('M')
N = request.args.get('N')
liveCells = request.args.get('liveCells')
...
When I print out request.args I get ImmutableMultiDict([('callback', u'jQuery17101683842277548142_1412736365518'), ('array[2][]', u'2'), ('array[2][]', u'3'), ('array[1][]', u'2'), ('array[1][]', u'2'), ('N', u'5'), ('M', u'5'), ('_', u'1412736417145'), ('array[0][]', u'2'), ('array[0][]', u'1')])
Does anyone know how to fix this?
I see two problems with your code. First, you don't pass a key named 'liveCells'. You pass one named 'array'. You need to update this either in your JavaScript or on the Flask side. Assuming you want the former, your JavaScript should look like
var array = [[2,1],[2,2],[2,3]]
function getNext() {
var data = {
'M': 5,
'N': 5,
'liveCells' : array
};
$.ajax({
url: '/getNewGeneration',
jsonp: 'callback',
dataType: 'jsonp',
data: data,
success: function(response) {
...
}
});
}
Second, you can't use the get method to retrieve multivalve keys. ImmutableMultiDicts, such as request.args, provide a method called getlist that will return a list of items for the given key rather than a single value. Update your code to
liveCells = request.args.getlist('liveCells')
More information can be found in the werkzeug documentation.
Do it like this and i think it will work for you.
$.ajax({
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
dataType: 'json',
url: 'getNewGeneration',
success: function (e) {
console.log(e);
}
});
And try to print request.json then.