grab IDs from list items to update div with ajax - javascript

I'm a little stuck here. I have a page that displays three different views by loading with jQuery: a view of all categories associated with the user, the image and name of all the items within the category that is selected and a full detail view of all the properties of the item selected. HOw to get the id of the category selected than display the items and same with the item to display the full details. Ajax isn't the problem, so I think.
When the user clicks on an <li> within the test <div> this fires to retrieve items for that category
$(document).ready(function() {
$('#test li').click(function() {
//get id of cat selected
$.ajax({
url: "",
type: "POST",
data: {//return all the item info},
success: function(data) {
//when returns display updated results
}
});
});
I figure it would be the same as when you click an item. But how to write the query for the controller. Right now I'm just displaying all:
//Item Controller
//two queries; one for displaying items when certain cat is selected and
// another to display full details when an item is selected
public ActionResult Partial(Item item)
{
//var query = from i in db.Items
// orderby i.dateAdded
// where i.user_id==4
// select i;
//var results = query;
var model = db.Items;
return PartialView("_Partial1", model);
}
public ActionResult PartialTwo() //pass in the catId??
{
var query = from d in db.Items
// how to get catID which is in the item table?
select d;
var results = query;
return PartialView("_FullInfoPartial", results);
}
//Category controller
//get the categories from
public ActionResult GetCats( Category cat)
{
var query = from c in db.Cats where c.user_id == 4 orderby c.catId select c;
var results = query;
return PartialView("_PartialGetCats", results);
}
Am I on the right track?

A trick can be that for each <li> element, create a <input type="hidden" value="catID" ...> element for holding ids of categories.
So, as you render the category names in your view, add another line to create a hidden field for storing that category id like the following:
<li id="liCat1">
</li>
<input type="hidden" name="liCat1" value="catID1" />
Note that I set the name of the hidden field asa same as the id of the related li element.
Then, change your jquery like the following:
$(document).ready(function() {
$('#test li').click(function() {
var selector = "input[name='" + $(this).id + "value']";
var catID = $(selector).val();
// Now, you have the categoryID in the catID variable. Enjoy using it...!
$.ajax({
url: "...",
type: "POST",
data: {//return all the item info},
success: function(data) {
//when returns display updated results
}
});
});
});

Related

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.

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

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

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>

how to toggle particular div element in ng-repeat?

I have list of product , If I click on one product it needs to be added in database and again if I click on same product it should be removed from database, I am toggling wishlistFlag on ng-click. It should be fine on one div element, for second div element it is working reverse of first div element, I mean in case first product is added then if I click second product it has to be added but it is removing first product.
<div class="hmpal-prprt-post-wdgt hmpal-prprt-wishlist">
<a href="">
<span class="prprt-icon"><i class="fa fa-heart" aria-hidden="true"
ng-click="WishlistAdd($index,project.propertyId)"></i></span>
<span>Wishlist</span>
</a>
</div>
And inside Controller code is here,
a.WishlistAdd = function (index,propertyId) {
a.wishlistFlag = !a.wishlistFlag;
var data = {
wishlistFlag:a.wishlistFlag,
propertyId:propertyId
};
e.createWishLists(data).then(function (result) {
alert("sucesss");
alert(JSON.stringify(result));
}, function (error) {
alert("error");
alert(JSON.stringify(error));
});
}
How I can implement toggle wishlistFlag for different product .
Since you want at most one product selected in your wish list, instead of having a boolean flag, you can use the selected product id (called propertyId in your code if I'm right). The selectedProductId variable, defined in the controller, is either null if there is no product selected, or the product id if there is one.
The toggling is done by checking if the current selected id is equal to the clicked one.
I assume that
when wishListFlag === true in the sent data, you want to add the
product identified by propertyId, and otherwise, remove the
product from the database.
when you add a product, the server side
actually replace the selected product if there is an existing one.
// Is there a selected product ?
var selectedProductId = null;
a.WishlistAdd = function (index, propertyId) {
selectedProductId = (selectedProductId === propertyId ? null : propertyId);
var data = {
wishlistFlag: (selectedProductId !== null),
propertyId: propertyId
};
e.createWishLists(data).then(function (result) {
alert("sucesss");
alert(JSON.stringify(result));
}, function (error) {
alert("error");
alert(JSON.stringify(error));
});
}
You can make use of $index to have seperate flag to each of the wishList. Here, you can write your code as..
a.wishListFlag[index]
maintain a array of added propertyIds before save to the database check that id is in array if so remove from database and array else remove from database and array.
var wishList = [];
a.WishlistAdd = function (index,propertyId) {
var data = {
wishlistFlag: wishList.indexOf(propertyId) === -1,
propertyId:propertyId
};
e.createWishLists(data).then(function (result) {
//add or remove propertyid from whishList
if(data.wishlistFlag)
wishList.push(propertyId);
else
wishList.splice(wishList.indexOf(propertyId), 1);
alert("sucesss");
alert(JSON.stringify(result));
}, function (error) {
alert("error");
alert(JSON.stringify(error));
});
}

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