Django getlist getting null - javascript

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!");
}
});
});

Related

In ASP.NET Razor Page Jquery Ajax Function not Working

I have a two onchange function for a page called create delivery request. One is when the dropdownlist of receiver changes, then it should show the phone number & address of receiver selected. Another one is when the dropdownlist of delivery item changes, then it should set the max attribute for the quantity.
The url of both these are linked to the customized OnGet method in razor page.
However, usually the above Onget method is hit but the below one is not. And the above OnGet method can't get the dryfood with the passed ID as well, it is null inside. And the two jQuery ajax function doesn't work at all. I'm totally a beginner. Hope that there is someone who can help me. Thanks in advance.
In create.cshtml:
<div class="mb-3">
Receiver Name
<select id="receiver" asp-for="Delivery.ReceiverID" asp-items="Model.ReceiverList" class="form-control">
<option>--Select the Receiever--</option>
</select>
</div>
<div class="mb-3">
Receiver Phone
<span id="receiverphone" class="form-control">----</span>
</div>
<div class="mb-3">
Receiver Address
<div id="receiveradrs1" class="form-control">----</div>
<div id="receiveradrs2" class="form-control">----</div>
</div>
<div class="mb-3">
Delivery Item
<select id="deliveryitem" asp-for="DeliveryItem.DryFoodID" asp-items="Model.DeliveryItemList" class="form-control">
<option>--Select Delivery Item--</option>
</select>
</div>
<div class="mb-3">
Quantity
<input id="quantity" asp-for="DeliveryItem.Quantity" min="1" class="form-control" />
</div>
In create.csthml.cs, two customized OnGet method here:
public async Task<IActionResult> OnGetSetMaxQuantity(int id)
{
List<DryFoodDonation> dfdlist = await _db.DryFoodDonation.ToListAsync();
var dryfood = dfdlist.Where(d => d.Id == id).FirstOrDefault();
Debug.WriteLine(dryfood.DryFoodName + " " + dryfood.DryFoodRemainQuantity);
return new JsonResult(dryfood.DryFoodRemainQuantity);
}
public async Task<IActionResult> OnGetGetPhoneAdrs(int id)
{
List<User> receiverlist = await _db.User.Where(u => u.UserType.TypeID == 3).ToListAsync();
var selectreceiver = receiverlist.Where(d => d.UserID == id).FirstOrDefault();
Debug.WriteLine(selectreceiver.UserName + " " + selectreceiver.UserPhone);
return new JsonResult(selectreceiver);
}
The jQuery AJAX function in a JavaScript file:
$(document).ready(function () {
$("#receiver").change(function () {
alert('Yes receiver here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=GetPhoneAdrs',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
'id': item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$('#receiverphone').html(data.UserPhone);
$('#receiveradrs1').html(data.UserAdrs1);
$('#receiveradrs2').html(data.UserAdrs2);
}
});
});
$("#deliveryitem").change(function () {
alert('Yes item here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=SetMaxQuantity',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
"id": item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$("#quantity").attr({
"min": 1,
"max": data
});
}
});
});
});
Please help me with this. I can't solve this problem for a few weeks. Thank you!
// cshtml.cs
const sendMe = async function (someData) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/ControllerName/MethodNameInController',
data: { someData: someData },
success: function (response) {
if (response != null && response.statusCode == 200) {
..
} else {
..
}
}
});
}
//Controller
[HttpPost("MethodNameInController")]
public IActionResult MethodNameInController([FromForm] string someData) {
..
}

How to pass an array of "FormData" via ajax and access in Laravel controller

# I just want to know how to send this array the controller by requete ajax
var dataPanier=[];
function addarray(objser)
{
dataPanier.push(objser);
}
$('.target').click(function() {
var btn_name=$(this).attr("name");
switch(btn_name) {
case 'FormPVC':
var dataformPVC = new FormData(),
form_data = $('#'+btn_name).serializeArray();
$.each(form_data, function (key, input) {
dataformPVC.append(input.name, input.value);
});
dataformPVC.append('Fichier', $('#File_PVC')[0].files[0]);
/* function addarray push dataform in array*/
addarray(dataformPVC);
break;
.
.
.
more . . .
I am attempting to send multiple forms data as an array by ajax to a Larave controller.
$.ajax({
type: 'POST',
url: 'lsitedevis',
data: array ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
$("#btnTest").click(function(){
var formData = $('#frm1, #frm2').serialize();
console.log(formData);
$.ajax({
method: 'POST',
url: 'lsitedevis',
data: formData ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="frm1">
<input name="n1" type="text"/>
<input name="n2" type="hidden" value="test2"/>
<input name="n3" type="hidden" value="test3"/>
</form>
<form id="frm2">
<input name="n1" type="text" />
<input name="n2" type="hidden" value="test2"/>
<input name="n3" type="hidden" value="test3"/>
</form>
<input type="button" id="btnTest" value="send"/>
As your already using jQuery for the AJAX request, you could use the serialize() function. This supports multiple form elements, so it is possible to do:
var formData = $('#form1, #form2').serialize();
$.ajax({
type: 'POST',
url: 'lsitedevis',
data: formData ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
You might want to ask yourself why you have multiple forms but submitting them all as a single request. If it's for visual purposes, it might be easier to have a single form and separate the contents using other markup elements such as a <fieldset> or <div>.

Sending form data and action to wordpress admin-ajax.php

I have a form that I want to send its data to admin-ajax:
<form method="POST" id="form">
<input type="text" name="name">
<input type="number" name="phone">
<input type="email" name="email">
<textarea name="overview"></textarea>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
Javascript/jQuery code to send the data using Ajax:
document.getElementById('submit').addEventListener('click', function(e){
e.preventDefault();
var form_data = $('#form').serialize();
$.ajax('http://mywebsite.com/wordpress/wp-admin/admin-ajax.php', {
method: "POST",
data: form_data + {action: 'my_action'},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log('Error:' + err);
}
});
});
Also tried formData:
var form_data = new FormData();
form_data.append('form', $('#custom').serialize());
form_data.append('action', 'my_action');
How to send the form data and the action my_action?
you need to change this line from data: form_data + {action: 'my_action'}, to data: {action: 'my_action', form_data:form_data},
jQuery(document).on("click","#submit", function(){
e.preventDefault();
var form_data =jQuery('#form').serializeArray();
jQuery.ajax('http://mywebsite.com/wordpress/wp-admin/admin-ajax.php', {
method: "POST",
data: {action: 'my_action', form_data:form_data},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log('Error:' + err);
}
});
});
and change input type submit to button.
In general i prefer to use this way, like in your case you are using submit type button:
$(document).on('click', '#submit', function(){ // the id of your submit button
var form_data = $('#your_form_data_id'); // here is the id of your form
form_data.submit(function (e) {
var my_action = "my_action";
e.preventDefault();
$.ajax({
type: form_data.attr('method'), // use this if you have declared the method in the form like: method="POST"
url: form_data.attr('action'), // here you have declared the url in the form and no need to use it again or you can also use the path like in your code
data: form_data.serialize() +'&'+$.param({ 'my_action': my_action}), // here you are sending all data serialized from the form and appending the action value you assing when declare var my_action
success: function (data) {
// after the success result do your other stuff like show in console, print something or else
},
});
});
});
Hope it helps you. if anything is not clear feel free to ask, i try to explain in the comments.
You should just pass form to new FormData() so in your case when submitting the form just pass new FormData(e.target);
Hope it helps

Send multiple checkbox data with ajax

I have a form where I have countries list in checkbox format to be inserted into database. Say for example:
<input type="checkbox" name="country[]" value="Afghanistan" checked>Afghanistan<br>
<input type="checkbox" name="country[]" value="Albania" checked>Albania<br>
<input type="checkbox" name="country[]" value="Algeria" checked>Algeria<br>
<input type="checkbox" name="country[]" value="American Samoa" checked>American Samoa<br>
<input type="checkbox" name="country[]" value="Andorra" checked>Andorra<br>
<input type="checkbox" name="country[]" value="Angola" checked>Angola<br>
<input type="checkbox" name="country[]" value="Anguilla" checked>Anguilla<br>
I want to insert this into database using ajax. I could have easily done this through normal same page PHP post. But when sending data with ajax to other page for processing I am confused on how to send. Once it sends all the selected checkbox values perfectly then all the rest is onto me.
My AJAX script
$("#submit").click(function() {
var dataString = {
clicks: $("#clicks option:selected").data("value"),
country: $("input[name=country").data("value") // tried using this and input[name=country[]] but they did not work.
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to purchase this advertisement?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType : "json",
url: "add-ptc-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#loading-rent").hide();
$("#submit").show();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
}
}
});
return false;
});
});
I have put a check on the processing page where if the country value is empty return error like:
if($country == ''){
echo "No countries selected. Please select at least one country.";
}
No matter if I select one or all countries still I get this error response back. What should I do to send these checkbox data with ajax?
Try
var countries = {};
$('input[name^="country"]').each(function(){
countries[$(this).attr('value')] = $(this).is(":checked");
});
then post it to ajax data: countries or change the code to send only checked elements
Your PHP will receive an array so you can check
if(is_array($_POST['countries'])){
foreach($_POST['countries'] AS $country_name => $is_checked){
//do something...
}
}
You will want to switch your .data() to .val() on your input capture. Also change the name of the inputs to input[name=country\\[\\]]:checked.
# Use "e" as the event
$("#submit").click(function(e) {
# Use this function to stop the form
e.preventDefault();
# You could make a quick function to save all the countries
# You can actually feed other selectors into this as well, so
# it can do all your value retrievals, not just for countries
function getCountries(checkboxes)
{
var getVals = [];
$.each($(checkboxes),function(k,v) {
getVals.push($(v).val());
});
return getVals;
}
var dataString = {
clicks: $("#clicks option:selected").val(),
# Run the function to gather
# Note the name (escaped [] with :checked)
country: getCountries("input[name=country\\[\\]]:checked")
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to purchase this advertisement?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType: "json",
url: "add-ptc-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#loading-rent").hide();
$("#submit").show();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
}
}
});
});

jquery ajax post selectbox array by name

I want to do an ajax request to update the status of an item, but for one or many selected item.
So how can I post all the selected checkbox items to process it on the handle page?
Here is some code I use., but it will only post one item to the process page.
<td>
<input type="checkbox" class="select-all" name="item[]" id="item[78]">
</td>
<td>
<input type="checkbox" class="select-all" name="item[]" id="item[182]">
</td>
And the javascript
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}}"
}
});
var formData = {
item: $('input[name=item\\[\\]]').val(),
}
var type = "POST";
var my_url = "/posturl";
$.ajax({
type: type,
url: my_url,
data: formData,
success: function (data) {
console.log(formData);
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
Assign the unique name to each checkbox
Put all checkboxes in a form tag (all input fields in a single form).
Use serialize() or serializeArray() for collecting data from form
store data in var formData
Code:
<form id="form-name">
<tr>
<td>
<input type="checkbox" name="item[1]">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="item[32]">
</td>
</tr>
</form>
Javascript:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}}"
}
});
var formData = $('#form').serializeArray();
var type = "POST";
var my_url = "/posturl";
$.ajax({
type: type,
url: my_url,
data: formData,
success: function (data) {
console.log(formData);
},
error: function (data) {
console.log('Error:', data);
}
});
This will post an array of items to the url.
I did same thing in minor different way.
I got list of checkbox and names contain their id.
<input type="checkbox" class="bulkChecked" name="{{$value->id}}">
And Inside your event handler
var ids = [];
$(".bulkChecked:checked").each(function () {
ids.push($(this).attr("name"));
});
So at this point you have got ids of checked boxes. No you can pass 'ids' array with your ajax call

Categories

Resources