DOM updated , however changes not visible in browser - javascript

I'm trying to populate html select with an ajax call using jquery. I can see that the dom is getting updated with data from database , however the updated options are not visible on brower.
Here is the static html:
<td>
<div>
<select data-placeholder="-Role-" multiple class="chosen-select"
style="width:170px;">
<option value="TEST_ROLE1">TEST_ROLE1</option>
<option value="TEST_ROLE2">TEST_ROLE2</option>
</select>
<span userId="grouproleError" class="alert alert-danger col-sm-4"
style="display:none"></span>
</div>
</td>
Following is the script code :
$(document).ready(function () {
$('.chosen-select').chosen({}).change(function (obj, result) {
console.debug("changed: %o", arguments);
console.log("selected: " + result.selected);
});
/**
* Get All roles
**/
console.log('Getting all roles..' + new Date().toLocaleString());
$.ajax({
url: "http://localhost:8081/admin/roles/getallroles",
context: document.body,
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
var list = $(".chosen-select");
$.each(data, function (index, item) {
list.append(new Option(item.rolesShortName, item.rolesShortName));
});
console.log('Roles fetched:' + JSON.stringify(data));
},
error: function () {
window.location.replace("http://localhost:8081");
}
});
$('form').submit(function (event) {
register(event);
});
});
$(document).ajaxStop(function () {
$(".log").text("Triggered ajaxStop handler.");
});
}
You can see that the static options are the only options getting displayed.
Options retrieved from the database are updated in the DOM however they are not getting displayed. What do you think I'm doing wrong?

As per the documentation $('.chosen-select').trigger('chosen:updated') was required after the DOM was modified.

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

pre-selection of fields with ajax for select2

When I try to pre-select the value with ajax everything except the shown value is working.
Does anyone know where I've made the mistake?
I call the pre_select() function for each <select>.
When I look in to the code, everything is OK, but the label on the page is showing me the ID instead of myTitle. After submitting the form, the data is also ok! I need only the right label...
function pre_select(pre_id, query_id) { //my ID of selection, the query
var mySelect = $('#form_my_id'+pre_id);
$.ajax({
type: 'GET',
dataType:'json',
url: '?search&id='+query_id
}).then(function (data) {
var option = new Option(data.myTitle, data.id, true, true);
mySelect.append(option).trigger('change');
mySelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
}
Here is the HTML output
<select name="form_select[]" class="form-control select2bs4 select2-hidden-accessible" id="form_my_id1" width="100%" required="" data-select2-id="form_stok_id1" tabindex="-1" aria-hidden="true">
<option value="1" selected="" data-select2-id="5">The Title Of Product</option>
</select>
This function has done my job :-)
function pre_select(pre_id, query_id) { //my ID of selection, the query
var mySelect = $('#form_my_id'+pre_id);
$.ajax({
type: 'GET',
dataType:'json',
url: '?search&id='+query_id
}).then(function (data) {
mySelect.select2("trigger", "select", {
data: data
});
});
}

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 retrieve the elements of a dropdownlist in jquery and send it with ajax to an MVC Controller in ASP.Net?

I have a select item as follows:
<select id="id_category">
<option> </option>
</select>
In run time there is a tree view used to fill up the select menu as follows:
<script>
$(document).ready(function () {
$('#data').jstree({
"plugins": ["checkbox"]
});
$("#data").on("changed.jstree", function (e, data) {
if (data.selected.length) {
$("#id_category").empty();
$(data.selected).each(function (idx) {
var node = data.instance.get_node(data.selected[idx]);
var s = document.getElementById('id_category');
s.options[s.options.length] = new Option(node.text, '1');
});
}
else
$("#id_category").empty();
});
});
</script>
and the html for the tree is not important now as it works well.
Now, I want when a user click on a button with HTML as follows:
<input id="btn3" type="button" value="Test 3" />
an ajax will be run to send all the items in the select to a controller in MVC as follows:
$("#btn3").click(function () {
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: $.map($('#id_category')[0].options, function( elem ) { return (elem.value || elem.text); }),
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
and the controller:
[HttpPost]
public string Test03(Object str1)
{
// call with two parameters and return them back
this.myRetrievedData = str1;
return str1.ToString();
}
The above did not work with me, when I click on Test3 button nothing happened.
I am not sure how to pass the retrieved items to the function in the controller. Could anyone tell me how to do that?
The below logic must work for you. Many thanks to Mr.Stephen Muecke for assistance.
$("#btn3").click(function () {
var optionsData= $.map($('#id_category')[0].options, function(elem) {
return (elem.value || elem.text);
}); // create a variable to hold all the options array.
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: JSON.stringify(optionsData), //pass this variable to post request as 'options'
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
Then you can have your controller as below.
[HttpPost]
public string Test03(IEnumerable<string> options ) // change here to this
{
//your logic goes here
}
I think it's because you have not added [HttpPost] attribute in your controller function

ajax requesting sending in second click in knockout js

i have the below knockout js code..
Design Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<div class="acmenu">
<ul id="accordion" data-bind="foreach: CategoryList">
<li data-bind="click$parent.categorySelected),attr: {iddata.CategoryId},htmldata.CategoryName">
</li>
</ul>
</div>
self.categorySelected = function (selectedCategory, event) {
$('#newproducttitle').hide();
event.preventDefault();
selectCategoryId = selectedCategory.CategoryId();
var refurbishedUrl = "/services/ShopService.asmx/XGetRefurbishedproducts";
$.ajax({
url: refurbishedUrl,
data: JSON.stringify({ ItemID: itemid, categoryid: selectCategoryId, language: lang }),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
/******Lines of code**********/
}});
}
This function is calling for every click but ajax requesting is sending for second click only. i need to send ajax request for first click, is there any solution for that....
here i am proving one drive link for js file https://onedrive.live.com/redir?resid=143242b617ba6be2!6684&authkey=!AAJQbpV8ZQ7fnGI&ithint=file%2ctxt
Though we don't have enough to work on still I think it is calling on first request as well (unless you have verified in developer tools etc.). The reason it seems to work on second click is that ajax call has not returned and on second click it appears to work.
Try this to disable button until ajax returns:
$.ajax({
url: refurbishedUrl,
data: ...,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend:function(){ $(event.target).prop('disabled', true);},
}).done(function(data){
/*USE THIS INSTEAD OF success*/
}).fail(function(data){
/*USE THIS INSTEAD OF error*/
}).always(function(){
$(event.target).prop('disabled', false);
});
You are using knockout against its design.
The viewmodel manages data and state - and nothing else. It is not supposed to contain any code that does HTML or DOM manipulation, at all.
In this case your data is a list of category objects. You want to inform the server when one of them becomes the selected category. Additionally you want to keep track of whether the viewmodel is busy talking with the server.
Therefore we need categoryList, selectedCategory and busy observables, as well as a subscription to changes in the selected category:
function ViewModel() {
var self = this;
self.categoryList = ko.observableArray([/* category objects ... */]);
self.selectedCategory = ko.observable();
self.busy = ko.observable(false);
self.selectedCategory.subscribe(function (newCategory) {
self.busy(true);
API.post("XGetRefurbishedproducts", {
ItemID: itemid, // wherever that comes from
categoryid: newCategory.CategoryId(),
language: lang // wherever that comes from
}).done(function (data) {
/******** Lines of code ********/
}).always(function () {
self.busy(false);
});
});
}
The view displays the category list, provides a way of changing the selected category, and reacts to whether the viewmodel is busy.
Therefore we need foreach, text, click and disable bindings:
<div class="acmenu">
<ul id="accordion" data-bind="foreach: categoryList">
<li>
<span data-bind="text: CategoryName"></span>
<button data-bind="
click: $parent.selectedCategory,
disable: $parent.busy
">Select</button>
</li>
</ul>
</div>
Note that you can use an observable as a click handler.
Finally, to keep the viewmodel tidy, here's a helper that concentrates all Ajax handling in a central spot.
var API = {
ajax: function (httpMethod, apiMethod, data) {
return $.ajax({
type: httpMethod,
url: "/services/ShopService.asmx/" + apiMethod,
data: data,
dataType: "json"
}).fail(function (jqXhr, status, error) {
console.error("Could not call " + method + ", error: " + error, data);
});
},
get: function (apiMethod, data) {
return this.ajax("get", apiMethod, data);
},
post: function (apiMethod, data) {
return this.ajax("post", apiMethod, data);
}
};

Categories

Resources