how do i remember the radio button selection in django - javascript

i'm trying to make sure that even if the user refresh the page or goes back and comes back to that page, the radio button is still the same as what the user selects.
N.B: the value of the radio button is saved in sessions
<div class="col-md-1 ps-md-1">
<input class="align-middle h-100" type="radio" name="deliveryOption" id="{{option.id}}"
value="{{option.id}}">
</div>
my ajax
$('input[type=radio][name=deliveryOption]').on('change', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '{% url "checkout:cart_update_delivery" %}',
data: {
deliveryoption: $(this).val(),
csrfmiddlewaretoken: "{{csrf_token}}",
action: "post",
},
success: function (json) {
document.getElementById("total").innerHTML = json.total;
document.getElementById("delivery_price").innerHTML = json.delivery_price;
},
error: function (xhr, errmsg, err) {},
});
});
</script>
my view
def cart_update_delivery(request):
cart = Cart(request)
if request.POST.get("action") == "post":
delivery_option = int(request.POST.get("deliveryoption"))
delivery_type = DeliveryOptions.objects.get(id=delivery_option)
updated_total_price = cart.cart_update_delivery(delivery_type.delivery_price)
session = request.session
if "purchase" not in request.session:
session["purchase"] = {
"delivery_id": delivery_type.id,
}
else:
session["purchase"]["delivery_id"] = delivery_type.id
session.modified = True
response = JsonResponse({"total": updated_total_price, "delivery_price": delivery_type.delivery_price})
return response

Related

How to pass double variable through laravel jquery? No response is shown on button click

I am trying to send a jquery request to update the table, that route requires two variables id, Receive_id. I tried this code below but the button on-click does not show any response. Plz review my code or suggest me if there are any other ways to send route.
here is my blade code
<button data-url="{{ route('repairs.updateCylinder',['id'=> $cylinder->id, 'receive_id' => $data->id]) }}" class="btn btn-primary submit" id='update-cylinder'>Update</button>
Here is Jquery code,
<script>
$(document).ready(function(){
$(document).on("click", "#update-cylinder", function() {
// e.preventDefault();
var url = current.data('url')
var id=
$.ajax({
url: url,
type: "PATCH",
cache: false,
data:{
_token:'{{ csrf_token() }}',
body_leak: $('#body-leak').val(),
nozzle_change: $('#nozzle-change').val(),
nozzle_repair: $('#nozzle-repair').val(),
cap_change: $('#cap-change').val(),
washer_change:$('#washer-change').val(),
wash:$('#wash').val(),
refill:$('#refill').val(),
remarks:$('#remarks').val()
},
success: function(dataResult){
dataResult = JSON.parse(dataResult);
if(dataResult.statusCode)
{
window.location = "/repairs/updateCylinder";
}
else{
alert("Internal Server Error");
}
}
});
});
});
</script>
You can add a data-id on your button :
<button data-id="{{$cilinder->id}}" data-receive-id="{{ $data->id }}" class="btn btn-primary submit" id='update-cylinder'>Update</button>
and on your script section :
$("#update-cylinder").on("click", function(e) {
e.preventDefault();
let id = $(this).data("id");
let receive_id = $(this).data("receive-id");
let url = "repairs/updateCylinder/"+ id;
let data = new FormData($('#id_form')[0]);
$.ajax({
url: url,
type: "PATCH",
cache: false,
data : data,
datatype:'json',
success: function(response){
if(response.success == true){
window.location "/repairs/cylinderlist";
}else{
alert("Error to update...");
}
});
}

How to use refresh div correctly?

Hi,
Can you explain why my refresh div does not work? When clicked submit it seems the div is trying to refresh by removing all rows data but it is then not returning anything which leaves the div blank instead. The data stored to DB fine but I need the div to refresh and show all new submitted data
$('#submitBtm').on('click', onSubmit = () => {
const first_nameV = document.getElementById("first_name").value;
const last_nameV = document.getElementById("last_name").value;
const emailV = document.getElementById("email").value;
const departmentV = document.getElementById("department").value;
$.ajax({
type: "POST",
url: `companydirectory/libs/php/insertAll.php?first_name=${first_nameV}&last_name=${last_nameV}&email=${emailV}&departmentID=${departmentV}`,
success: function(data) {
},
error: function(request,error) {
console.log(request)
}
})
$("#id_data").load(location.href + " #id_data");
event.preventDefault();
})
on HTML page
<div class="listTable">
<tbody id="id_data">
</tbody>
</div>
It doesn't update because you're not appending the new data that you receive on the success callback
$.ajax({
type: "POST",
url: `companydirectory/libs/php/insertAll.php?first_name=${first_nameV}&last_name=${last_nameV}&email=${emailV}&departmentID=${departmentV}`,
success: function(data) {
// here you have the data and you can refresh the table
},
error: function(request,error) {
console.log(request)
}
})

problem with prevent and continue submit form after ajax execution

I have form with select. If select value is equal to 2 then part of form is sendign asynch via ajax and later the rest of the form should be sending via POST function. My problem is when I click submit ajax execution is performs correctly but POST method stuck, nothing happens. It looks like be page refresh.
My code
$('form').submit(function(e) {
if($('#car_type').val() == 2)
{
e.preventDefault();
e.returnValue = false;
var type = $('#new_type').val();
var number = $('#numer').val();
var form = $(this);
$.ajax({
url: "{{ url('cars/type') }}",
method: "POST",
context: form,
data: {type: type, number: number, _token: "{{ csrf_token() }}"},
success: function (result) {
if (result.result > 0) {
} else {
$("#msg").html("Errors, try again later!");
$("#msg").fadeOut(2000);
}
},
error: function (xhr) {
console.log(xhr.responseText);
},
complete: function() {
this.off('submit');
this.submit();
}
})
}
});

Django getlist getting null

Hello guys im currently learning on how to send data from HTML to Django backend using Ajax.
I have this HTML
<div class="form-row">
<input type="checkbox" name="car-checkbox[]" value="Audi" id="chck1">
<input type="checkbox" name="car-checkbox[]" value="BMW" id="chck2">
<input type="checkbox" name="car-checkbox[]" value="Lambo" id="chck2">
<input id="submit-car" type="button" value="Submit">
</div>
and then to send the data i use this code (Ajax)
$('#submit-car').click(function () {
const data = {user_id: user_id}
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});
and then on the Django side i try to get the checked checkbox
def insert_car_to_db(self, request):
cars = request.POST.getlist('car-checkbox[]')
print(cars)
Weirdly enough when i try to get the checked data, i keep getting [] value,
where did i miss ? am i misunderstand something?
P.S
i followed this post
How to get array of values from checkbox form Django
$('#submit-car').click(function () {
const car_checkbox = [];
const user_id = "Some test UserId";
const csrftoken = "Provided CSRF TOKEN";
$("input[type=checkbox]:checked").each(function(){
car_checkbox.push($(this).val());
}); //STore the checkbox result in an array
const data = {"user_id": user_id, "car-checkbox": car_checkbox}
console.log(data);
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<input type="checkbox" name="car-checkbox" value="Audi" id="chck1">
<input type="checkbox" name="car-checkbox" value="BMW" id="chck2">
<input type="checkbox" name="car-checkbox" value="Lambo" id="chck2">
<input id="submit-car" type="button" value="Submit">
</div>
So where you are sending the checkbox array value to backend /submit-car/ ?
what is user_id in your click evennt?
As you are using jquery so
$('#submit-car').click(function () {
const car_checkbox = [];
$("input[type=checkbox]:checked").each(function(){
car_checkbox.push($(this).val());
}); //STore the checkbox result in an array
const data = {"user_id": user_id, "car-checkbox": car_checkbox}
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});

JQuery tokenfield with django not working

I am trying to incorporate a search field in a django registration form. I would like to use a bootstrap tokenfield that searches a django model for possible matches to the search string. I've been struggling with this for a couple of days now. Here is my code below.
<div class="form-inline" id="keywords_div">
{% csrf_token %}
<input type="text" name="search_text" class="form-control" id="tokenfield" placeholder="Enter keyword" style="width: 50%" />
<button type="button" id="addKeyword-btn" class="btn btn-primary">Add</button>
My JQuery code.
$(function(){
//auto complete ajax code.
$('#tokenfield').tokenfield({
autocomplete: {
//source:['red','blue','green','yellow','violet','brown','purple','black','white'],
delay: 100
},
showAutocompleteOnFocus: true,
}).keyup(function(){
alert('key pressed');
$.ajax({
url: "/user_account/auto_complete_search/",
type: 'POST',
data: {
'search_text': $('#tokenfield').val(),
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},
success: function(data){
console.log(data)
},
dataType: 'text'
});
});
});
});
Django View
#This is the function that handle the auto complete search functionality.
def autocomplete_search_view(request):
if request.method == 'POST':
search_text = request.POST['search_text']
else:
search_text = ''
keywords = Keywords.objects.filter(keyword__icontains=search_text)
#data = serializers.serialize('json', keywords, fields=('keyword'))
return HttpResponse('Query completed', content_type='application/text')
user_account/urls.py
url(r'^auto_complete_search/$', autocomplete_search_view, name='autocomplete_search'),
The error from the browser.
What am I doing wrong here?
After a very long time of searching for the answer, I eventually got it right. see the code below. I'm trying to figure out how to make the dropdown menu scrollable but code below does exactly what I wanted.
$('#tokenfield').tokenfield({
autocomplete: {
source: function(request, response){
if(request.term.length >= 5){
$.ajax({
url: "/user_account/auto_complete_search/",
type: 'POST',
data: {
'search_text': request.term,
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},
success: function(data){
if(data != ""){
var dataArr = [];
$.each(data, function(i, jsonObj){
dataArr[i] = jsonObj.fields.keyword;
});
response(dataArr);
}
else{
response([]);
}
},
dataType: 'json'
});
}
else{
response([]);
}
},
delay: 300,
},
showAutocompleteOnFocus: true
});
Django view.
#This is the function that handle the auto complete search functionality.
def autocomplete_search_view(request):
if request.method == 'POST':
search_text = request.POST['search_text']
else:
search_text = ''
return HttpResponse([{}], content_type='application/json')
keywords = Keywords.objects.filter(keyword__icontains=search_text)
data = serializers.serialize('json', keywords, fields=('keyword'))
return HttpResponse(data, content_type='application/json')
The HTML is still the same. Hope this helps somebody in the future.

Categories

Resources