I'm trying to send an array to my python function inside views.py but I can't. It always crash with a keyError because is not recognising the data from js.
Code:
Python function in views.py:
def cargar_datos_csv(request):
if request.method == 'POST':
filtros = request.POST['node']
print(filtros)
ctx = {'A':filtros}
return JsonResponse(ctx)
JS
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
var frutas = ['Manzana', 'Banana'];
$.ajax({
url: '/../../data_bbdd/',
type: 'POST',
headers:{"X-CSRFToken": csrftoken},
data: {
'node': frutas,
},
dataType: "json",
cache: true,
success: function(response) {
coords = JSON.stringify(response.A);
alert(coords);
}
});
How can I send an array to my python function?
Thank you very much.
Because node is a list it will be posted as node[] by JQuery so you can get it using request.POST['node[]'] or request.POST.getlist('node[]')
More informations on why this is the behavior of JQuery on this stackoverflow's answer :django - getlist()
Related
I am new to programming with django and now I am stuck at this stage, where I have to move data from the js variable to Django view or something. But at the moment if I try to pass the data from js to Django using ajax post function it says uncaught range error. I am not sure where I am making the mistake but it would be really helpful if anyone can help me. Really indeed of help PLS!!!
Error message:
Uncaught RangeError: Maximum call stack size exceeded at Dt (jquery.min.js:2)
Script code
<script>
var URL = "{% url 'textFromInputFile' %}";
var textOfFile = document.getElementById('fileinput');
textOfFile.addEventListener('change', function(){
var fr = new FileReader();
fr.onload = function(){
document.getElementById("textarea").value = fr.result;
};
fr.readAsText(this.files[0]);
});
function getText(){
$.ajax({
type: "POST",
url: "/textFromInputFile",
data: {"textOfFile":textOfFile},
dataType: "String",
success: function(data){
alert("ok")
},
failure:function(){
alert("failed")
}
},);}
$('button').click(function(){
getText();
});
</script>
views.py
def textFromInputFile(request):
if request.method == 'POST':
if 'textOfFile' in request.POST:
textOfFile = request.POST['textOfFile']
#need to do something here
return HttpResponse('success') #if everything is o.k
else:
return HttpResponse('failed!!')
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('signin.html', views.signin, name='signin'),
path('index.html', views.index, name='index'),
path('home.html', views.home, name='home'),
path('logoutPage.html', views.logout, name='logout'),
path('home.html', views.textFromInputFile, name='textFromInputFile'),
]
The error can be caused by multiple Ajax attempts to serialize your JSON. So we better serialize it before sending it using JSON.stringify ()
Try changing yor ajax function, the data like this:
data:JSON.stringify({"textOfFile":textOfFile}),
The other way is jus adding this to the ajax function:
$.ajax({
type: "POST", url: "/textFromInputFile",
data: {"textOfFile":textOfFile},
dataType: "String",
success: function(data){
alert("ok")
},
failure:function(){
alert("failed")
},
cache: false,
contentType: false,
processData: false,
},);
View.py
def export(request):
if request.is_ajax():
ourid = request.GET.getlist("terid")
Case_Detail = Case_Info_Resource()
for i in ourid:
print(i)
queryset = Case_Info.objects.filter(id=i)
dataset = Case_Detail.export(queryset)
response = HttpResponse(
dataset.xls, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="persons.xls"'
print("breakpoint")
return response
Ajax Script
<script>
$(document).ready(function () {
$('#Download').click(function () {
var list = [];
$("input:checkbox[name='checkbox']:checked").each(function () {
list.push($(this).val());
});
$.ajax({
url: '/Account_Manager/Download/',
type: 'GET',
data: { 'terid': list },
traditional: true,
dataType: 'html',
success: function () {
alert("The best cricketers are: " + list.join(", "));
}
});
});
});
</script>
Error:
The view Apps.views.export didn't return an HttpResponse object. It returned None instead.
So, Ajax wants us to return the value in HttpResponse but I need to pass the response normally in order to download the excel which I am creating. I think I checked all the possible answers and struggling with it from the last 3 days. Thank you in advance for any help, suggestions, or edit.
I am trying to send data from javascript/ajax (selected regions and city information) to flask and then return processed data back to javascript. The 'var data' look like {"region1":"Asia","city1":"Taipei","region2":"S America"} on console.log.
I get error within ajax.
javascript:
$(function() {
$('#button').on('click', function() {
var data = {'region1': $('select[name=slct1]').val(),
'city1': $('select[name=slct2]').val(),
'region2': $('select[name=slct3]').val()};
console.log(data);
$.ajax({
url: '/receive',
type: 'post',
dataType: 'json',
contentType: 'application/json',
crossDomain: true,
data: data,
success: function(data2){
alert('success');},
error: function(){alert('failure');}
});
});
});
Flask: Temp1 and other variables (np array) for City1 are extracted from pandas db.
#app.route('/receive', methods=['POST', 'GET'])
def receive():
if request.method == 'POST':
data = request.form['data']
City1 = data['city1']
Temp1 = some_function(City1) # np array
return jsonify({'Temp1': list(Temp1)})
I think the data received in Flask should be parsed like this:
if request.method == 'POST':
data = request.get_data()
data = json.loads(data)
City1 = data['city1']
I'm trying to compile project https://github.com/kannan4k/django-carpool
please refer this project repo for this issue.
and end up with following error during ajax call.
Failed to load resource: the server responded with a status of 400 (BAD REQUEST).
I know this is because of ajax post request & CSRF tokens.
following is my setting.
1. disable "django.middleware.csrf.CsrfViewMiddleware"
2. in new_trip page I have a button (Postdata)so this button sends an ajax request.
My View:-
#login_required
def save_journey(request):
if request.is_ajax() and request.method == "POST":
try:
res = json.loads(request.body)
cords = res['cords']
cords = [[x['d'], x['e']] for x in cords]
distance = res['distance']
start_place = res['start']
end_place = res['end']
clusters = clusterize_latlngs(cords, distance)
time = datetime.datetime.strptime(res['time'], "%m/%d/%Y %H:%M")
Trip.objects.create(user=request.user, time=time, cluster=json.dumps(clusters), travel_distance=distance,
start_place=start_place, end_place=end_place)
return HttpResponse()
except:
return HttpResponseBadRequest()
else:
return HttpResponseNotAllowed(['POST'])
Ajax call (home.js)
function postData() {
radius = 0;
var url = "/save_journey/";
var dataType = 'json';
if (type == 'r') {
radius = $('#radius').val();
url = "/get_results/";
dataType = 'html';
}
var data = JSON.stringify({
cords: myroute,
time: document.getElementById('dateStart').value,
start: document.getElementById('startPlace').innerHTML,
end: document.getElementById('endPlace').innerHTML,
radius: radius,
distance: distance
});
$.ajax({
type: "POST",
url: url,
dataType: dataType,
data: data,
success: function (data) {
if (type == 'r') {
window.location.href = "/search_results/";
}
else {
window.location.href = '/trip_success/';
}
},
error: function () {
console.log('Error getting options list...')
}
});
console.log(data);
}
this code is not able to call /save_journey/ URL.
I tried many answers from stack overflow & didn't figure out what is the problem .
You should never disable csrftoken unless you're absolutely sure about what you're doing. It's an important part of the security features implemented in Django.
Here is an example of how you can use Ajax with Django with csrftoken:
You can use Ajax Post to send JSON to Django and then handle the arguments as a dict(). Here is an example:
In browser (JQuery/JavaScript):
function newModule() {
var my_data = $("#my_element").val(); // Whatever value you want to be sent.
$.ajax({
url: "{% url 'modules' %}", // Handler as defined in Django URLs.
type: "POST", // Method.
dataType: "json", // Format as JSON (Default).
data: {
path: my_data, // Dictionary key (JSON).
csrfmiddlewaretoken:
'{{ csrf_token }}' // Unique key.
},
success: function (json) {
// On success do this.
},
error: function (xhr, errmsg, err) {
// On failure do this.
}
});
In server engine (Python):
def handle(request):
# Post request containing the key.
if request.method == 'POST' and 'my_data' in request.POST.keys():
# Retrieving the value.
my_data = request.POST['my_data']
# ...
Hope this helps.
I´m building a social network with Grails and got stucked
on giving users inner their editprofile
page the chance to paste an youtube-Url into a textfield and by clicking a button a JS regexxes the id out of the URL pasted, an ajax post is fired updating a div with a preview image of the youtube video
the html looks like :
<g:textField name="videoinput" class="videoinput reLef" value="" />
<span class="daten_videouploadbtn reLef" ></span>
<g:render template="/forms/storedVideos" />
the JS looks like :
$('.daten_videouploadbtn').click(function() {
var string = document.editProfileForm.videoinput.value;
var neu = string.replace(/http[s]?:\/\/(?:[^\.]+\.)*(?:youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)|youtu.be\/)([\w\-\_]+)/i, '$1');
var id = RegExp.$1;
jQuery.ajax({
type:'POST',
data:RegExp.$1,
url:'${createLink(action: 'addVideo')}',
success:function(data,textStatus){jQuery('#storedvideos').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
});
the controller looks like :
def addVideo() {
def videoitems = !!%%-- HOW TO PARSE YOUTUBE-ID HERE -%%!!
render(template:"/forms/storedVideos", model: [newVideo:videoitems])
}
and stored videos looks :
<div id="storedvideos"><span><img src="http://img.youtube.com/vi/${newVideo}/default.jpg" width="225px" height="130px"/></span></div>
i just dont get it how to catch the data of the Ajax Post and update the div with the preview image with the id inside,
can someone give a hint ? it is killing me
You should post the data like this:
jQuery.ajax({
type: 'POST',
data: { value: RegExp.$1 },
...
After that you can access the posted data inside your grails controller with params.value.
I got this working on Grails 2.0.4:
Javascript/Ajax
var data =
{requestId: 12456,
node: "node1",
host: "mynode.com"};
$.ajax({
url: '/myurl',
data: JSON.stringify(data),
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() ...
},
error: function() ...
}
});
In Grails....
def service(){
def jsonObj = request.JSON
}
I like this approach because request.JSON parses the data and returns a ready to use object.