jQuery 'change' doesn't show most up-to-date data - javascript

I have a jQuery change function that populates a dropdown list of Titles from the user selection of a Site dropdown list
$("#SiteID").on("change", function() {
var titleUrl = '#Url.Content("~/")' + "Form/GetTitles";
var ddlsource = "#SiteID";
$.getJSON(titleUrl, { SiteID: $(ddlsource).val() }, function(data) {
var items = "";
$("#TitleID").empty();
$.each(data, function(i, title) {
items +=
"<option value='" + title.value + "'>" + title.text + "</option>";
});
$("#TitleID").html(items);
});
});
The controller returns JSON object that populates another dropdown list.
public JsonResult GetTitles(int siteId)
{
IEnumerable<Title> titleList;
titleList = repository.Titles
.Where(o => o.SiteID == siteId)
.OrderBy(o => o.Name);
return Json(new SelectList(titleList, "TitleID", "Name"));
}
The markup is:
<select id="SiteID" asp-for="SiteID" asp-items="#Model.SiteList" value="#Model.Site.SiteID" class="form-control"></select>
<select id="TitleID"></select>
The problem is that the controller method is only touched on the FIRST time a selection is made. For example,
The first time SITE 1 is selected, the controller method will return the updated list of Titles corresponding to SITE 1
If SITE 2 is selected from the dropdown, the controller will return the updated list of Titles corresponding to SITE 2
The user adds/deletes Titles in the database corresponding to SITE 1
User returns to the form and selects SITE 1 from the dropdown. The list still shows the results from step 1 above, not the updates from step 3
If I stop debugging and restart, the selection will now show the updates from step 3.
Similar behavior described in jQuery .change() only fires on the first change but I'm hoping for a better solution than to stop using jQuery id's
The JSON response is:
[{"disabled":false,"group":null,"selected":false,"text":"Title2","value":"2"},{"disabled":false,"group":null,"selected":false,"text":"Title3","value":"1002"},{"disabled":false,"group":null,"selected":false,"text":"Title4","value":"2004"},{"disabled":false,"group":null,"selected":false,"text":"Title5","value":"3"},{"disabled":false,"group":null,"selected":false,"text":"Title6","value":"9004"}]

The issue was that the JSON result was being read from cache as #KevinB pointed out. This was fixed by adding the following line within the change function
$.ajaxSetup({ cache: false });

Related

Use multiselect with dynamically generated select

I am trying to use the multiselect plugin I found on here:
How to use Checkbox inside Select Option
The question above is for a <select> with hard coded <options>.
The <select> I am using generates <options> using jQuery and PHP with this function:
function initializeSelect($select, uri, adapt){
$.getJSON( uri, function( data ) {
$select.empty().append($('<option>'));
$.each(data, function(index, item) {
var model = adapt(item);
var $option = $('<option>');
$option.get(0).selected = model.selected;
$option.attr('value', model.value)
.text(model.text)
.appendTo($select);
});
});
};
initializeSelect($('#salesrep'), 'process/getSalesReps.php', function (item) {
return {
value: item.final_sales_rep,
text: item.final_sales_rep
}
});
I have used the above function several times in different projects, as it successfully creates all of the options brought in by the PHP process. Unless requested, I will not show the code for the process. Just know I am indeed retrieving a group of names and displaying them in the dropdown.
Right beneath the function above is where I call the multiselect feature:
$('select[multiple]').multiselect();
$('#salesrep').multiselect({
columns: 1,
placeholder: 'Select Reps'
});
The HTML for the select is as follows:
<select class="form-control" name="salesrep[]" multiple id="salesrep"></select>
Using all of the above, the output looks like this:
Upon inspecting the element, I can see all of the sales reps names. This tells me that the initializeSelect function is working properly.
Therefore I think the issue must have something to do with the multiselect.
Ajax calls are asynchronous. You call multiselect() before the ajax call has had time to complete and therefore the option list is still empty at the point you call the multiselect() function.
Either move the $('#salesrep').multiselect({.. bit to inside the getJSON method or call the multiselect refresh function after the option list has been populated as I am doing here. (Untested.)
function initializeSelect($select, uri, adapt){
$.getJSON( uri, function( data ) {
$select.empty().append($('<option>'));
$.each(data, function(index, item) {
var model = adapt(item);
var $option = $('<option>');
$option.get(0).selected = model.selected;
$option.attr('value', model.value)
.text(model.text)
.appendTo($select);
});
//now that the ajax has completed you can refresh the multiselect:
$select.multiselect('refresh');
});
};
initializeSelect($('#salesrep'), 'process/getSalesReps.php', function (item) {
return {
value: item.final_sales_rep,
text: item.final_sales_rep
}
});
$('select[multiple]').multiselect();
$('#salesrep').multiselect({
columns: 1,
placeholder: 'Select Reps'
});

Multiple Delete/Update using php- Codeigniter Ajax

The console.log(response) returns the code of whole page in console when I inspect it in ajax . I have created a codeigniter project with MySQL as back end database . I have fetched content from table from database into table. Now I want to give option to user of mulitple delete. Please take it into account that I am not actually deleting value from table I am just turning status of of that row to inactive. It goes as :
If status= 0 : the row's data will be visible in table.
If status= 1:the row's data will not be visible in table.
I have given checkbox option in the table to select multiple checkbox.
Here is my javascript:
To check all the check boxes:-
<script language="JavaScript">
function selectAll(source) {
checkboxes = document.getElementsByName('sport');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
javascript to get value's from the checkboxes and send it to controller:
<script type="text/javascript">
function okay(){
var favorite = [];
$.each($("input[name='sport']:checked"), function(){
favorite.push($(this).val());
var txt=$(this).val();
});
for (var i = 0;i<favorite.length;i++) {
$.ajax({
url:('<?=base_url()?>/Repots/supervisor_muldel'),
type:'POST',
data:{'value_id':favorite[i]},
success:function(response)
{
console.log(response);
},
error:function(response)
{
console.log('nahi gaya');
},
});
//console.log(favorite[i]);
}
//alert("My favourite sports are: " + favorite.join(", "));
}
</script>
every check box is associate with particular values.
here the html button to call the fucntion:
<button onclick="okay();">Delete Selected</button>
Controller:Reports/supervisor_muldel:
//multiple delete supervisor
public function supervisor_muldel() {
$value_id = $this->input->post('value_id');
$selected_supervisor = array('supervisor_id' =>$value_id);
$staus=array('status'=>1);
$this->load->model('Entry_model');
$result = $this->Entry_model->supervisor_muldel($staus,$selected_supervisor);
}
Entry_model/supervisor_muldel:
//delete multiple supervisor
public function supervisor_muldel($staus,$condition)
{
$this->db->trans_start();
$this->db->where($condition)
->update('tbl_supervisor',$staus);
$this->db->trans_complete();
}
The console.log returns the code of whole page in console.I am stuck here.
You have put wrong ajax request URL.
Change
url:('<?=base_url()?>/Repots/supervisor_muldel'),
to
url:('<?=base_url()?>/Reports/supervisor_muldel'),
Look at the controller name in URL.

Retrieve a select element options list that has been re-ordered with JavaScript

I have a Dictionary of names/numbers that are passed through to my View from my Controller. This becomes:
Model.arrayPositions[x]
These are then added to a select list:
<form>
<div class="col-xs-12">
<select id="ListIn" class="select-width" name="SelectionIn" multiple="multiple" size="#Model.arrayPositions.Count">
#foreach (var item in Model.arrayPositions)
{
if (item.Value != null)
{
<option class="active" value="#item.Value">#Html.DisplayFor(modelItem => #item.Key)</option>
}
}
</select>
</div>
</form>
Array items with no value are ignored, the rest is added to the list.
Items can then be added/removed or moved up/down the list using JavaScript:
function AddSelected() {
$('#ListOut option:selected').each(function (i, selected) {
$('#ListIn').append('<option class="active" value="1">' + selected.innerText + '</option>');
selected.remove();
});
}
function RemoveSelected() {
$('#ListIn option:selected').each(function (i, selected) {
$('#ListOut').append('<option class="inactive" value="-1">' + selected.innerText + '</option>');
selected.remove();
});
function MoveUp() {
var select1 = document.getElementById("ListIn");
for (var i = 0; i < select1.length; i++) {
if (select1.options[i].selected && i > 0 && !select1.options[i - 1].selected)
{
var text = select1.options[i].innerText;
select1.options[i].innerText = select1.options[i - 1].innerText;
select1.options[i - 1].innerText = text;
select1.options[i - 1].selected = true;
select1.options[i].selected = false;
}
}
}
(Moving down is pretty much just the opposite of Moving up)
(#ListOut is simply a second list that has the array items with a value of null added to it)
(The final value is not too important right now, so I'm not specifically retaining it. The order of the list is more important)
I'm changing the order using Javascript to avoid having the page refresh constantly for such a simple action.
However, once I press an update button I'll have a call to my Controller (ASP.NET Core in C#). What I am wondering is how I could retrieve the final values of the list in the new order.
i.e.
If Model.arrayPositions = {a=1,b=2,c=null,d=3}, it would add them to the list as: [a,b,d]
I then use javascript to remove 'a' and move 'd' up, resulting in [d,b]
When I press the update button I would like the retrieve the current list of [d,b] from the View.
What would be the best way to achieve this? Or, alternatively, what other methods might be used to achieve the same goal (note that I wouldn't want page refreshes or partial refreshes if possible).
You can use ajax method to hit your controller on the click of your update button
syntax of jquery ajax is:-
<script>
$.ajax({
type:'POST',
url : 'controllerNAME/ActionNAME',
datatype: 'json',
data : {'parameterOne': parameterone, 'parameterTwo' : parametertwo,...},
success : function(response)
{
alert(response.d)
//put your logic here for further advancements
}
});
</script>

Trying to get Jquery working with dynamic select forms in Rails and Active Admin

I'm trying to update a select box based on another..
In my active admin resource, I did the following just for some test data:
controller do
def getcols
list = new Hash
list = {"OPTION1" => "OPTION1", "OPTION2" => "OPTION2"}
list.to_json
end
end
In active_admin.js I have the following
$('#worksheet_type').change(function() {
$.post("/admin/getmanifestcols/", { ws_type: $(this).val() }, function(data) {
populateDropdown($("#column_0"), data);
});
});
function populateDropdown(select, data) {
 select.html('');
alert('hi');
$.each(data, function(id, option) {
select.append($('<option></option>').val(option.value).html(option.name));
});      
}
The above is working in the sense that when my primary select box is changed, the jquery is called and I even get the alert box of 'hi' to be called. However, it's not replacing the contents of the select box with my test OPTION1 and OPTION2 data.
I think I'm passing in the JSON wrong or something, or it's not being read.
What am i missing?
It looks to me as if you're not properly iterating over the map.
What about:
$.each(data, function(value, name) {
select.append($('<option></option>').val(value).html(name));
});
?

Selecting a value on a dynamically populated dropdown list after the list has been populated

So I have a problem where my code tries to select a value on the dropdown list before the list is populated. Basically it calls a javascript function that does an AJAX post to get the dropdown values from php. Then its supposed to select a value on the list, however it does this before the list is populated, so it doesn't find the value. Any idea on how to fix this?
Heres my code
This is where I get the values for the dropdown list
function getProjects(id, proj_select_class)
{
custID = id.options[id.selectedIndex].value;
$.ajax({
type: "POST",
url: "index.php/home/projectlist",
data: {custID : custID},
dataType: "json",
success:function (result){
var ddl = $(proj_select_class);
ddl.children('option:not(:first)').remove();
for (var key in result) {
if (result.hasOwnProperty(key)) {
ddl.append('<option value=' + key + '>' + result[key] + '</option>');
}
}
}
});
}
And heres where I set the values.
AddNew() adds a new row to my table. This is also inside an ajax call.
for (var row in result) {
AddNew();
client_field = document.getElementById('clients'+id);
project_field = document.getElementById('projects'+id);
client_value = $.trim(result[row].client_id);
project_value = $.trim(result[row].project_id);
//set client
client_field.value = client_value;
getProjects(client_field, project_field, client_value);
project_field.value = project_value;
}
Maybe try using a custom event binding to know when your code should fetch the value from the list. To bind to a custom event, you would do something like:
$(document).bind("listpopulated", function(){ /*find value, call AddNew() */ });
and in your ajax success function trigger the "listpopulated" event like so:
$(document).trigger("listpopulated");
References:
http://api.jquery.com/bind/
http://api.jquery.com/trigger/
Fixed it by waiting til the ajax finished running by doing this
$(document).ajaxComplete(function(){ set_values(result); });
set_values is another function that I just loops through all my results and sets all the dropdown values

Categories