Ajax is not sending multiselect data to Django views - javascript

I am quite new to Django so bare with me.
I have a multiselct list in my webpage and I need to send the selected items to my views in order to make use of them.
To do so, I used ajax but when it doesn't seem to work for some reason.
This is the script:
$("#var_button").click(function(e) {
var deleted = [];
$.each($("#my-select option:selected"), function(){
deleted.push($(this).val());
});
alert("You have deleted - " + deleted);
e.preventDefault();
$.ajax({
type: "post",
url: "/description/upload-csv/" ,
data: {
'deleted' : deleted }
}); // End ajax method
});
I checked with alert if maybe the variable deleted is empty but it return the selected values so the problem is in my ajax query.
This is the part where I retrieve the data in my views.py
if request.method == 'POST':
del_var = request.POST.getlist("deleted[]")
my_class.del_var = del_var
I changed the data type to text but it doesn't do anything

I cant help you on the Django side.
$.each($('#selector'), (i, e) => {
deleted.push($(e).val());
})
but this will add the value to the "deleted" variable.

Related

jQuery error in client post response - POST HTTP/1.1" 400

I can't figure out what is wrong with my code and I'm not really good with jQuery.
I'm trying to build HTML form will hold cars data. It's based on this form:
HTML source code is here.
Form data is sent on button click on the end back to program.
I upgraded that form with cascading manufacturer (proizvodjac in code) and car models droplist based on this code. But it's not working.
I keep receiving HTTP 400 which would mean that my POST call from client is malformed.
Here is my jQuery functions:
$(function () {
var carsdata = {"alfaromeo":["mito","156","147","giulietta","159","166","146"],"audi":["a3","a4","a6","a5","80","a1","q3","a8","q5"],"bmw":["320","116","x3","316","318","118","530","x1","520","x5","525","330","120","323","serija 1"],"chevrolet":["spark","lacetti","captiva","aveo","cruze"],"citroen":["c4","c4 grand picasso","c3","c5","c4 picasso","xsara","berlingo","c2","xsara picasso","saxo","ds5","c1"],"fiat":["brava","bravo","panda","grande punto","stilo","punto","punto evo","doblo","500","tipo","uno","coupe"],"ford":["c-max","fiesta","focus","mondeo","fusion","ka","escort"],"honda":["civic","accord","cr-v"],"hyundai":["getz","i10","i20","atos","i30","coupe","elantra","accent","santa fe","ix35","tucson"],"kia":["rio","pro_cee'd","sportage","cee'd","pride","sorento"],"mazda":["3","2","323 f","626","6","cx-5","323","premacy","5"],"mercedes":["a-klasa","c-klasa","e-klasa","b-klasa","124"],"mercedes-benz":["e-klasa","clk-klasa","c-klasa","s-klasa","190","a-klasa","b-klasa","c t-model","ml-klasa","w 124","124"],"nissan":["qashqai","x-trail","note","primera","micra","juke","almera"],"opel":["corsa","astra","zafira","meriva","vectra","insignia","mokka","tigra","combo","astra gtc","kadett"],"peugeot":["308","207","206","306","106","307","208","406","508","407","partner","3008","405"],"renault":["thalia","clio","scenic","grand scenic","kangoo","captur","megane grandtour","megane","laguna","5","megane break","twingo","modus","kadjar","megane classic","espace","megane scenic","megane coupe","megane sedan"],"seat":["toledo","leon","ibiza","altea","cordoba"],"skoda":["fabia","octavia","120","superb","felicia","rapid"],"smart":["fortwo"],"toyota":["corolla","yaris","auris","avensis","rav 4","land cruiser"],"vw":["polo","golf v","golf iv","golf vii","passat","golf vi","jetta","passat variant","caddy","sharan","tiguan","golf variant","golf ii","vento","golfplus","golf iii","bora","touran","touareg","up!"]};
var proizvodjac = $('<select id="proizvodjac"></select>');
var model = $('<select id="model"> </select>');
$.each(carsdata, function(item, key) {
proizvodjac.append('<option >' + item + '</option>');
});
$("#containerProizModel").html(proizvodjac);
$("#proizvodjac").on("change", function(e) {
var item;
var selected = $(this).val();
if (selected === "alfaromeo") {
item = carsdata[selected];
} else {
item = carsdata[selected];
}
$(model).html('');
$.each(item, function(item, key) {
model.append('<option >' + key + '</option>');
});
});
$("#containerProizModel").append(model);
$("button#predict").click(function(e){
e.preventDefault();
/*Get for variabes*/
var kilometraza = $("#kilometraza").val(), godina_proizvodnje = $("#godina_proizvodnje").val();
var snaga_motora = $("#snaga_motora").val(), vrsta_goriva = $("#vrsta_goriva").val();
/*create the JSON object*/
var data = {"kilometraza":kilometraza, "godina_proizvodnje":godina_proizvodnje, "proizvodjac":proizvodjac, "model":model, "snaga_motora":snaga_motora, "vrsta_goriva":vrsta_goriva}
/*send the ajax request*/
$.ajax({
method : "POST",
url : window.location.href + 'api',
data : $('form').serialize(),
success : function(result){
var json_result = JSON.parse(result);
var price = json_result['price'];
swal('Predviđena cijena auta je '+price+' kn', '','success')
},
error : function(){
console.log("error")
}
})
})
})
Comments and explanations are in the code.
On server side:
Server is expecting user_input dictionary which is built from variables returned by POST request. Here is how API method looks:
#app.route('/api',methods=['POST'])
def get_delay():
result=request.form
proizvodjac = result['proizvodjac']
model = result['model']
godina_proizvodnje = result['godina_proizvodnje']
snaga_motora = result['snaga_motora']
vrsta_goriva = result['vrsta_goriva']
kilometraza = result['kilometraza']
user_input = {'proizvodjac':proizvodjac,
'model':model,
'godina_proizvodnje':godina_proizvodnje,
'snaga_motora':snaga_motora,
'vrsta_goriva':vrsta_goriva,
'kilometraza':kilometraza
}
print(user_input)
a = input_to_one_hot(result)
price_pred = gbr.predict([a])[0]
price_pred = round(price_pred, 2)
return json.dumps({'price':price_pred});
Error from Google Chrome Developer Console:
which is pointing to:
EDIT 1:
I don' know how to pass proizvodjac and model to onClick function. See what happens on breakpoint:
XHR on Network tab:
HTML form is being filled with data OK only manufacturer and model are not passed to onClick:
EDIT 2:
Getting closer to solution. I've added :
var proizvodjac = $("#proizvodjac").val()
var model = $("#model").val()
as suggested and now all variables are successfully passed!
But I still get error 400 as final ajax POST call is getting stuck somwhere..
EDIT 3:
changed from
data : $('form').serialize()
to
data = data
AJAX method receives everything ok:
Still it doesn't work.
There are two main issues here:
1) you aren't getting the values from two of your fields correctly. You need to add
var proizvodjac = $("#proizvodjac").val()
var model = $("#model").val()
inside the $("button#predict").click(function(e){ function.
2) You're collecting all these values and putting them into your data variable...but then you aren't doing anything with it. Your AJAX request is configured as follows in respect of what data to send:
data : $('form').serialize()
The serialize() function automatically scoops up all the raw data from fields within your <form> tags. In your scenario, if you want to send a custom set of data (rather than just the as-is contents of the form) as per your data object, then you simply need to change this to
data: data
so it sends the information from that object in the POST request instead.

Ajax returning empty string in Django view

I am developing a web application through Django and I want to get information from my javascript to a view of Django in order to access to the database.
I am using an ajax call as this post shows.
I am calling the js in html by an onclick event :
sortedTracks.html
...
<form action="{% url 'modelReco:sortVideo' video.id %}">
<input type="submit" value="Validate" onclick="ajaxPost()" />
</form>
...
clickDetection.js
//defined here
var tracksSelected = [];
//function that fill tracksSelected
function tagTrack(track_num){
if(tracksSelected.includes(track_num)){
var index = tracksSelected.indexOf(track_num);
tracksSelected.splice(index, 1);
}else{
tracksSelected.push(track_num);
}};
//ajax function
function ajaxPost(){
$.ajax({
method: 'POST',
url: '/modelReco/sortedTracks',
data: {'tracksSelected': tracksSelected},
success: function (data) {
//this gets called when server returns an OK response
alert("it worked! ");
},
error: function (data) {
alert("it didnt work");
}
});
};
So the information I want to transfer is tracksSelected and is an array of int like [21,150,80]
views.py
def sortedTracks(request):
if request.is_ajax():
#do something
print(request)
request_data = request.POST
print(request_data)
return HttpResponse("OK")
The ajax post works well but the answer I get is only an empty Query Dict like this :
<QueryDict: {}>
And if I print the request I get :
<WSGIRequest: GET '/modelReco/sortedTracks/?tracksSelected%5B%5D=25&tracksSelected%5B%5D=27&tracksSelected%5B%5D=29'>
I have also tried to change to request_data=request.GET but I get a weird result where data is now in tracksSelected[]
I've tried to know why if I was doing request_data=request.GET, I get the data like this tracksSelected[] and get only the last element of it.
And I found a way to avoid to have an array in my data (tracksSelected) on this link
This enables me to have :
in views.py
def sortedTracks(request):
if request.is_ajax():
#do something
print(request)
request_data = request.GET.getlist("tracksSelected")[0].split(",")
print(request_data)
and in clickDetection.js
function ajaxPost(){
tracksSelected = tracksSelected.join();
$.ajax({
method: 'POST',
url: '/modelReco/sortedTracks',
data: {'tracksSelected': tracksSelected},
success: function (data) {
//this gets called when server returns an OK response
alert("it worked! ");
},
error: function (data) {
alert("it didnt work");
}
});
};
This little trick works and I am able to get the array data like this,
print(request_data) returns my array such as [21,25,27]
Thank you for helping me !
According to me to access the data which is sent in the ajax request can be directly accessed .
For Example:
def sortedTracks(request):
if request.method == 'POST':
usersV = request.POST.get('tracksSelected')[0]
for users in usersV:
print users
return HttpResponse("Success")
else:
return HttpResponse("Error")
The correct syntax is data: {tracksSelected: tracksSelected},

AJAX: Having trouble retrieving queryset from server and appending to select options

I am able to send the value of the input field with the id datepicker to the server. And with this in the view I filter the time slot by the ones that occur on the same date.
Where I am having difficulties is sending this queryset to the browser and then appending this to the options.
I'm still relatively new to javascript I apologize if this is a newb question. I definitely appreciate any feedback!
My View:
if request.is_ajax():
selected_date = request.POST['selected_date']
slots_on_day = Calendar.objects.filter(date=selected_date)
return HttpResponse(slots_on_day)
My Javascript:
$(document).ready(function() {
$("#datepicker").change(function(){
document.getElementById("display_slots").style.display ="block";
$.ajax({
type: 'POST',
data: {
'selected_date':$('#datepicker').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: function(resp){
for (var i=0; i < resp['slots_on_day'].length;++i){
addOption(
document.getElementById("display_slots"), resp['slots_on_day'][i], resp['slots_on_day'][i]);
}
}
});
});
});
Notes: the id=datepicker field triggers the ajax event. I then want to receive the response from the server and append the options to the input with the id=display_slots
Error:
TypeError: resp.slots_on_day is undefined
Updated ajax success
success: function(data){
$.each(data, function(key, value){
$('select[name=display_slots]').append('<option value="' + key + '">' + value +'</option>');
});
}
from django.forms.models import model_to_dict
if request.is_ajax():
selected_date = request.POST['selected_date']
slots_on_day = Calendar.objects.filter(date=selected_date)
data = []
for cal in slots_on_day:
data.append(model_to_dict(cal))
return JsonResponse(status=200, data={'slots_on_day':data})
It'll send JSON response in frontend and now you can use this data as you want to use. I think, It'll work with your current ajax success method code

How could i display search result based on filtered value provided by user?

I have developed filter system where it provides 3 options such as property type, number of rooms, and maximum price. Every time they select filter options the user will get their search result instantly. For example, if a user has selected property type of Apartment and number of rooms as 4 and maximum price of 12000 then the user will get those rents whose property type is apartment with 4 rooms of 12000 mark. I developed the front-end part with React.js and could fetch user selected data successfully. I have also passed data to ajax but I have no idea how should I display the search results based on filtered value provided by user with no page loading.
Ajax code
$.ajax({
type: 'GET',
url: '/filter/space/',
data{property:propertySelectedValue, room:roomSelectedValue, price:maxPrice},
success: function(data){
console.log(data['fields']);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.error("Status: " + textStatus); alert("Error: " + errorThrown);
},
});
Views.py
class FilterSpace(View):
def get(self,request,*args,**kwargs):
property = request.GET.get('property',None)
room = request.GET.get('room', None)
price = request.GET.get('price', None)
rental = Rental.objects.all()
if room:
rental = rental.filter(room=room)
print('rental',rental)
if price:
rental = rental.filter(price__lte=price)
if property:
rental = rental.filter(property=property)
rental_json = serializers.serialize('json',rental)
print('rental_json',rental_json)
return HttpResponse(rental_json,content_type="application/json")
One thing you might consider doing is rendering the html to a string (django - render_to_string not working) on the server side and send that back in an ajax response along with the data. then replace the html where the list is contained with that rendered by the server.
Django:
def get_list(request, *args, **kwargs):
items = Items.objects.filter(...)
html = ""
items = [] # actual data
context = {
"item_list": items,
...
}
for item in items:
html = html + render_to_string(list_html_template, context, context_instance=RequestContext(request))
items.append(item.to_json()) # You have to define this if you want it.
return JsonResponse({
"list_html": html,
"items_data": itmes
})
Template (list_html_template):
{% for item in item_list %}
<!-- render item here... -->
{% endfor %}
Javascript:
$.ajax({
url: "url_for_get_list_view",
dataType: "json",
...
success: function(json) {
$(list_container).html(json.list_html); // Will replace any current html in this container (i.e. refresh the list).
/* You can also do stuff with json.items_data if you want. */
}
});
for efficiency in the python you should find the way to filter once with all the parameters instead of filter the filtered of the filtered, but this is not essential to see result.
inside success: function(data){ you should use jQuery to put data into the page, you might start with something like
function data2html(data) {
...// use .map and .join
}
$("#divid").append(data2html(data))
You can clear up your view by doing something like this:
class MyView(View):
def get(self, request):
results = Rental.objects.filter(**request.GET)
return serializers.serialize('json', results)
and when you get the data back in your AJAX request, in the success part just clear your table and iterate over the results and append rows to the now empty table with your data.
In my opinion, its clearer to have the logic and rendering taking place in django using AJAX to retrieve and place the rendered html. Here is a sketch of the code
Here is the view that passes the set of rentals to an html template
def ajax_rental_search(request):
search_text = 'missing'
if request.method == "GET":
search_text = request.GET.get("search_text", "missing")
# DEBUG: THIS CAN CHECK THE CONNECTION
# return HttpResponse('SERVER RESPONSE: search_text: ' + search_text)
if search_text != 'missing':
rentals = Rental.objects # add filters etc.
context = {
"rentals": rentals
}
return render(request, "rentals_search_response.html", context)
Here is the key part, the jquery, ajax request:
function rentalSearch() {
const search_text = content_search_input');
$.ajax({
type: "GET",
url: < rental_search_url >,
data: {
'search_text': search_text,
},
success: function (serverResponse_data) {
// console.log('search success: ' + serverResponse_data);
$('#rentals_content').html(serverResponse_data);
// rentals_content is an existing div on page
},
error: function (serverResponse_data) {
console.log('error:' + serverResponse_data)
}
});
}
Then you can style the displayed rentals as you wish knowing that they are all going to passed to the sub template.
Thats it

javascript or ajax to update database with asp.net mvc?

I have a function here from a change event on a dropdownlist. When the selection gets changed I want to update a row in my database. Should I use javascript or ajax. I don't want the page to be refreshed. I think it should be ajax, but not sure? If ajax, can anyone point me to a tutorial/video/etc?
Here is where I want to update my db row.
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function(event) {
// call db and update row
}, false);
Looks like you using asp.net mvc.
You can write your ajax calls with pure javascript Ajax docs or the easiest way, using JQuery.
You need to add one action on your controller to receive the ajax data, and then insert/update your db.
See this, this and this.
Most common scenario would be making an ajax call using HTTP POST/PUT to a controller method, which would then handle the data and update the database directly or pass through to your service/data layer code.
Probably the easiest way to make the call would be using the jQuery.ajax method. Documentation can be found here: http://api.jquery.com/jquery.ajax/
You can try something like this
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
var name = $('#TextBox1').val();
var email = $('#TextBox2').val();
if (name != '' && email != '') {
$.ajax
({
type: 'POST',
url: 'Home/UpdateDB', //if it is plain asp.net then UpdateDB is declared as WebMethod
async: false,
data: "{'name':'" + name + "','email':'" + email + "'}",
contentType: 'application/json; charset =utf-8',
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$('#TextBox1').val('');
$('#TextBox2').val('');
alert("Data Saved Successfully");
}
},
error: function (result) {
alert("Error Occured, Try Again");
}
});
}
})
});
</script>
fg
iuou
uouienter link description here
uiouidfgsdfgddfgdfgdfgdgdgd##
Heading
##*
uio
uiopomkl
hjlkdsg
dsf
dfgdg
Blockquote

Categories

Resources