In ASP.NET Razor Page Jquery Ajax Function not Working - javascript

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) {
..
}

Related

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

How to update a textbox with the result from a get Request

I have a simple web page designed to show the list of players when a certain team is selected. Currently my API can successfully return all of the players and display it it on the console log, but I am confused on how to you connect that with my div container.
My function returns all the player names as a list
<div class="card">
<div class="card-header"> Player List</div>
<div class="card-body">
<label>Teams</label>
<select id="playerDisplay" onChange="updatePlayerlist();">
<option value=" ">Select a Team</option>
<option value="Fractional">Giants</option>
</select>
<div class="col-sm-7">
<label>Players</label>
<div id="listPlayers"></div>
</div>
</div>
</div>
function updatePlayerslist() {
var playerPick = $("#playerDisplay")[0].value;
$.ajax({
type: 'GET',
url: APICALL,
data: {
'code': playerPick
},
success: function(list) {
if (list.length === 0) {
console.log(list);
playerPick = list;
} else
console.log("EMPTY");
}
})
}
Given that you state:
My function returns all the player names as a list
I'm going to assume that the response is an array of strings. Therefore you can simply loop through that and create the new elements to append to the DOM. Try this:
function updatePlayerslist() {
var playerPick = $("#playerDisplay").val(); // Note use of jQuery here
$.ajax({
type: 'GET',
url: APICALL,
data: {
'code': playerPick
},
success: function(playerNames) {
var html = playerNames.map(function(playerName) {
return `<div>${playerName}</div>`;
});
$('#listPlayers').append(html);
}
})
}
function updatePlayerslist() {
var playerPick = $("#playerDisplay")[0].value;
$.ajax({
type: 'GET',
url: APICALL,
data: {
'code': playerPick
},
success: function(list) {
if (list.length === 0) {
console.log("EMPTY");
}
// Construct the text to be displayed from the `list` data
var textToDisplay = list.join(', ');
// Update the html
$('#listPlayers').html(textToDisplay);
}
})
}
loop through the list and update the element by appending with jQuery
function updatePlayerslist(){
var playerPick = $("#playerDisplay")[0].value;
$.ajax({
type: 'GET',
url: APICALL,
data: {
'code': playerPick
},
success: function(list){
console.log(list);
list.forEach(value => {
$("#listPlayers").append(value)
})
}
})
}

Problems with selecting option with loading data with Ajax request with the object select option

I have performed a rest service performed with C # with ajax request in a combo box, this object shows the data of my rest service, this combo box must fill data from many cities and this shows the cities that I perform in the service, but the inconvenience is in the object combo box or select option in html5, whenever I give in the object, it loads the data and I cannot select my city that I want, reloading it, as an infinite loop when I want to select the data Annex code
https://es.stackoverflow.com/questions/279794/problemas-en-mostrar-datos-en-combo-box-en-pantalla-con-petici%c3%b3n-ajax
<div class="form-group has-feedback">
<label>Ciudad</label>
<select class="form-control" data-rel="chosen" id="Ciudad" name="Ciudad" onclick="ValidarExisteCiudad()">
<option/>
<option/>
</select>
</div>
function ValidarExisteCiudad() {
//$("[data-rel='chosen']").chosen();
//var ddlCiudad = $("[data-rel='chosen']");
var ddlCiudad = $("#Ciudad");
ddlCiudad.empty().append('<option selected="selected" value="0" disabled = "disabled">Loading.....</option>');
$.ajax({
type: 'GET',
url: "CargaCiudad",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
ddlCiudad.empty().append('<option selected="selected" value="0">Seleccione ...</option>');
$.each(data, function () {
ddlCiudad.append($("<option></option>").val(this['Value']).html(this['Text']));
});
// After updated data from database you need to trigger chosen:updated.
//$("[data-rel='chosen']").trigger("chosen:updated");
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
existeUsuario = false;
}
});
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> CargaCiudad()
{
List<Cuidad> Items = await drHelpPrueba.Cuidad.ToListAsync();
List<SelectListItem> ciudad = new List<SelectListItem>();
for (int i = 0; i < Items.Count; i++)
{
ciudad.Add(new SelectListItem
{
Value = Convert.ToString(Items.ToList()[i].IdCiudad),
Text = Items.ToList()[i].Nombre
});
}
return Json(ciudad);
}
ddlCiudad.append($("").val(this['Value']).html(this['Text']));
undefined
my friend. Because you don't get true data from the response.
Try following this. Hope to help, my friend :))
function ValidarExisteCiudad() {
var ddlCiudad = $("#Ciudad");
ddlCiudad.empty().append('<option selected="selected" value="0" disabled = "disabled">Loading.....</option>');
$.ajax({
type: 'GET',
url: "CargaCiudad",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
ddlCiudad.empty().append('<option selected="selected" value="0">Seleccione ...</option>');
$.each(data, function () {
ddlCiudad.append($("<option> </option>").val(this.value).html(this.text)); //Modified this line
});
// After updated data from database you need to trigger chosen:updated.
//$("[data-rel='chosen']").trigger("chosen:updated");
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
existeUsuario = false;
}
});
}

how to get value selected in ajax select2 plugin

html
<label>Customer PO</label>
<select name="Customer_PO" class="form-control" id="Customer_PO" >
<option value="" >Customer PO</option>
</select>
-------------
jquery
$('body').on('click','#Customer_PO',function(e){
id_tosend=$(this).attr("id").toString();
var cust_id=$('#Customer_list').val();
var a=$('#'+id_tosend).select2({
ajax: {
url: 'ajax/report/inspection_report.php?cust_id='+cust_id,
dataType: 'json',
delay: 500,
data: function (params) {
var queryParameters = {
q: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: data
};
},
cache:true
}
});
a.data('select2').dropdown.$dropdown.addClass("test");
$(this).select2('open');
});
i attach plugin of Select2 .When i submitted data in my form ,it shown me empty value . How i get this value to set selected initial value in ajax method.
you can try this
HTML
<label>Customer PO</label>
<select name="Customer_PO" class="form-control" id="Customer_PO" >
<option value="" >Customer PO</option>
</select>
JQUERY
$.ajax({
url: 'url',
type: 'POST',
data: { id: id},
dataType: 'JSON',
success: function (resp) {
if(resp.msg == 'Done'){
$("#Customer_PO option:selected").removeAttr("selected");
$.each(resp.yourListData, function (key, value) {
$("#Customer_PO ").append('<option value="'+value.ID+'">'+value.name+'</option>');
});
$("#Customer_PO ").trigger("change", [true]);
}
},
error: function (e) {
console.log("Line 1204");
console.log(e.responseText);
}
});

change label with ajax from controller?

Hi everybody I need to change text label from JsonResult on my Controller... I have two problems...
1) I can't print on my view the text that I send from my
controller...
2) I want to send 3 labels from my controller when I selected a
option from my dropdownlist.
Please help if someone know how to do this... :)
On my View
<div class="col-md-6 col-sm-6 col-xs-12">
<label id="lblCargo"></label>
</div>
#section scripts{
<script>
$(document).ready(function () {
$("#ddlEmpleado").change(function () {
var selectedItemValue = $(this).find(":selected").val()
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("getLabels", "AsignarBien")',
data: {
"id": selectedItemValue,
},
contentType: 'application/json; charset=utf-8',
Success: function() {
$("#lblCargo").text(data);
},
error: function() {
alert("error");
}
}
);
});
});
</script>
}
On my Controller I got this
public JsonResult getLabels(Guid id)
{
var result = (from item in vempleados.GetAll().ToList()
where item.IdEmpleado == id
select item.Cargo).SingleOrDefault();
return Json(result, JsonRequestBehavior.AllowGet);
}
Three small changes and it will work:
success must be lower case.
Add the data parameter to the success function.
There should be no comma (,) after selectedItemValue
Basically make your $.ajax call like this:
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("getLabels", "AsignarBien")',
data: { "id": selectedItemValue},
success: function (data) {
$("#lblCargo").text(data);
},
error: function () {
alert("error");
}
});
NOTE:You don't need to specify the contentType for the GET request, so you can take that out completely.

Categories

Resources