ajax based multiple dropdown showing result with pagination - javascript

have 3 drop-down
select#opt-category,select#opt-sector,select#opt-company
category onchange
$("select#opt-category").change(function () {
category = $(this).val();
if(sector!='')sector='';
if(company!='')company='';
$("#opt-sector").load('menus.php?category='+category);
$("#opt-company").load('menucmp.php?category='+category);
});
will load sector and company based on category and result shown as
$(".showgrid").load('portal.php?category='+category+'&sector='+sector+'&company='+company);
the results are based on paging which also called ajax
function loading_show(){
$('#loading').html("<img src='assets/img/ajax-loader.gif'/>").fadeIn('slow');
}
function loading_hide(){
$('#loading').fadeOut('slow');
}
function loadData(page,category){
loading_show();
$.ajax
({
type: "POST",
url: "pagination_data.php",
data: {'page':page,'category':category},
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1,<?php echo $catgory?> ) // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
var category= $(this).attr('q');
loadData(page,category);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var category = parseInt($('.total').attr('b'));
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page,category);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
//$('.goto').val("").focus();
return false;
}
});
when category dropdown changed, it loads the new value on other dropdown but can't load the result into .showgrid.
is there another way to accomplished this task

Related

Append footer only once within a callback

My code is a bit complex as I'm appending dynamic content to a cart following a successful AJAX call. I need to add the footer ($(.mini-cart__footer)) to the cart only once at the end of the li items. How do I achieve that? The problem I'm currently facing that every time a li is added, a footer section is attached to it - so if 3 products are added to the cart, I'll end up with 3 footer sections.
Here is my code:
var __isp_options = {
isp_add_to_cart_callback: function(product_id) {
var image = ISP_PRODUCTS[product_id].image.replace('?c=2', '');
var title = ISP_PRODUCTS[product_id].l;
var description = ISP_PRODUCTS[product_id].d;
var price = ISP_PRODUCTS[product_id].p;
isp_add_to_cart(event, product_id);
var miniCart_html = '<div class="mini-cart__full is-mini-cart"><ul class="mini-cart__items is-cart__items"><li class="mini-cart__item"><div class="mini-cart__image-container"><svg class="icon icon-close"><use xlink:href="#icon-close"></use></svg><img class="mini-cart__image" src="'+image+'"></div><div class="product-meta"><span class="cart-item__brand">'+title+'</span><h2 class="product-meta__title">'+'1 X '+'<span class="product-meta__title cart-item__title product-tag">'+description+'<span class="dot"></span><span class="dot"></span></span></h2><span class="product-meta__price" data-money-convertible="">'+Shopify.formatMoney(price)+'</span></div></li></ul></div>';
$('.mini-cart__content').append(miniCart_html);
$('.is-cart__items').append('<footer class="mini-cart__footer"><div class="mini-cart__total"><span class="mini-cart__total-label">'+'Total'+'</span><span class="mini-cart__total-price" data-money-convertible="">'+Shopify.formatMoney(price)+'</span></div><form action="/cart" method="POST">'+'Continue to checkout'+'</form></footer>')
}
}
function isp_add_to_cart(event, product_id) {
$.ajax({
url: '/cart?view=mini-cart-content/add?id='+ product_id + "&quantity=1",
type: 'POST',
success: function(result) {
console.log('success');
$.getJSON('/cart.js').then(function(results) {
if (results['item_count'] > 0) {
$('.cart-icon-wrapper__count').text(results['item_count']);
$('.cart-icon-wrapper--has-items').show();
$('.cart-icon-wrapper--empty').hide();
}
});
},
error: function(result) { console.log('error'); }
});
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
return false;
}

how to count length of list created dynamically

I am creating a chat box in which chat messages are fetched in the form of list. My problem is whenever i am clicking on start chat button i have to open chat box and then count the no of list. my chat box is opening but length of list are always zero. how to solve this.
$(document).on('click', '.start_chat', function(){
var to_user_id = $(this).data('touser_id');
var to_user_name = $(this).data('tousername');
//console.log(to_user_id);
var getdata;
$.ajax({
url:"chat_id_table.php",
method:"POST",
data:{to_user_id:to_user_id},
async:false,
dataType:'json',
success:function(data)
{
//console.log(data);
getdata = JSON.parse(data);
//console.log(getdata);
}
})
if($('#user_dialog'+to_user_id).length == 0){
make_chat_box(to_user_id, to_user_name, getdata);
}
var chat_length = $('.msg_list').find("li").length;
});
Getting the chat data is an async call. so what happens is that the list is counted before the data comes in.
To solve this wrap the list counter in a function and call it after data is in.
fixed code here
$(document).on('click', '.start_chat', function(){
var to_user_id = $(this).data('touser_id');
var to_user_name = $(this).data('tousername');
//console.log(to_user_id);
var getdata;
$.ajax({
url:"chat_id_table.php",
method:"POST",
data:{to_user_id:to_user_id},
async:false,
dataType:'json',
success:function(data)
{
//console.log(data);
getdata = JSON.parse(data);
//console.log(getdata);
var chat_len = counter();
}
})
});
function counter(){
if($('#user_dialog'+to_user_id).length == 0){
make_chat_box(to_user_id, to_user_name, getdata);
}
var chat_length = $('.msg_list').find("li").length;
return chat_length;
}

Cannot POST more than one value with AJAX

I stucked on one thing. I have a 2 grid inside checkboxes. When I selected that checkboxes I want to POST that row data values like array or List. Actually when i send one list item it's posting without error but when i get more than one item it couldn't post values.
Example of my grid
Here my ajax request and how to select row values function
var grid = $("#InvoceGrid").data('kendoGrid');
var sel = $("input:checked", grid.tbody).closest("tr");
var items = [];
$.each(sel, function (idx, row) {
var item = grid.dataItem(row);
items.push(item);
});
var grid1 = $("#DeliveryGrid").data('kendoGrid');
var sel1 = $("input:checked", grid1.tbody).closest("tr");
var items1 = [];
$.each(sel1, function (idx, row) {
var item1 = grid1.dataItem(row);
items1.push(item1);
});
$.ajax({
url: '../HeadOffice/CreateInvoice',
type: 'POST',
data: JSON.stringify({ 'items': items, 'items1': items1, 'refnum': refnum }),
contentType: 'application/json',
traditional: true,
success: function (msg) {
if (msg == "0") {
$("#lblMessageInvoice").text("Invoices have been created.")
var del = $("#InvoiceOKWindow").data("kendoWindow");
del.center().open();
var del1 = $("#InvoiceDetail").data("kendoWindow");
del1.center().close();
$("#grdDlvInv").data('kendoGrid').dataSource.read();
}
else {
$("#lblMessageInvoice").text("Problem occured. Please try again later.")
var del = $("#InvoiceOKWindow").data("kendoWindow");
del.center().open();
return false;
}
}
});
This is my C# part
[HttpPost]
public string CreateInvoice(List<Pm_I_GecisTo_Result> items, List<Pm_I_GecisFrom_Result> items1, string refnum)
{
try
{
if (items != null && items1 != null)
{
//do Something
}
else
{
Log.append("Items not selected", 50);
return "-1";
}
}
catch (Exception ex)
{
Log.append("Exception in Create Invoice action of HeadOfficeController " + ex.ToString(), 50);
return "-1";
}
}
But when i send just one row it works but when i try to send more than one value it post null and create problem
How can i solve this? Do you have any idea?
EDIT
I forgot to say but this way is working on localy but when i update server is not working proper.
$.ajax({
url: '../HeadOffice/CreateInvoice',
type: 'POST',
async: false,
data: { items: items, items1: items1 }
success: function (msg) {
//add codes
},
error: function () {
location.reload();
}
});
try to call controller by this method :)

JS fires twice confirm-box onchange MVC

I have a problem, on the Telerik dropdownlist i have a function onchange selection. This function save a value with ajax call if an item from list is selected. If selection is not OK will show a confirm box, if the user press OK will be redirected on another page. If press Cancel need to populate a field with empty string.
The problem is: if the user press CANCEL button, the confirm-box fires twice...I tried to put return false after $('#Assessment').val(''); but does not work..
Any solutions please?
DropDownlist:
#(Html.Kendo().DropDownListFor(m => m)
.Name("Assessment").HtmlAttributes(new { #style = "text-align:center", onchange = "saveAssessment()" })
.OptionLabel("Select an assessment")
.DataTextField("DisplayName")
.DataValueField("Value")
.Value("DisplayName")
JS Function
function saveAssessment() {
var assessmentId = $('#Assessment').val();
var grid = $('#_gridProjectCheckList').data('kendoGrid');
var selectedItem = grid.dataItem(grid.select());
var ciId = selectedItem.Id;
var ciText = $("#Assessment").data("kendoDropDownList").text();
if (assessmentId !== null && (ciText === 'Ok' || ciText === 'NotApplicable')) {
$.ajaxSetup({ cache: false });
$.ajax({
url: 'UpdateProjectCheckItemAssessment',
type: "POST",
data: { assessmentId: assessmentId, id: ciId },
success: function (response) {
$('#Assessment').val(response.assessmentVal);
$('#_gridProjectCheckList').data('kendoGrid').dataSource.read();
}
});
}
else {
var msgRedir = confirm("You will be redirected to Assessment Page");
if (msgRedir) {
window.location.href = 'UpdateProjectCheckItem' + '/' + selectedItem.Id;
}
$('#Assessment').val('');
}
}

How to post id on checkbox in Jquery?

I want to make a simple pagination page. This is regarding delete function. I have a checkbox that user can choose to delete a row. May I know how to post/get the id of the row if user click on next link? In my case, the id will be duplicate if user click on the checkbox. Below are my codes,
jQuery
var cbNew = [],
cbAdd = [];
function addId(checkBox){
cbAdd = cbAdd.concat(checkBox);
console.log(cbAdd);
}
$(document).on("click", ".checkBox", function(){
var cb = [];
$('.checkBox:checked').each(function(){
cb.push($(this).val());
});
if(cb.length > 0) {
addId(cb);
$('#delete').fadeIn();
} else {
$('#delete').fadeOut();
}
});
//Link on Next Page
$(".nextPage").click(getFunct);
function getFunct(e){
e.preventDefault();
var url = $(this).attr('href'),
row = getURLParameter(url, 'startrow'),
cbNew = cbNew;
getParam(row,url);
}
function getParam(param1,param2){
$.ajax({
type: "POST",
url: url,
data:
{
row : param1,
url : param2,
cbNew : cbNew
}
}).done(function(data){
$('#result').html(data);
addId(cbNew);
});
}
This is the output if I click on multiple checkbox on same page console.log(cbAdd);
["25", "25", "26", "25", "26", "27"]
If I click one checkbox on page 1 and one checkbox on page 2, it get the id correcltly
["25", "59"]
You are maintaining two arrays, one capture all checked checkbox values ie cb and concatenating these to another array called cbAdd, here you are duplicating values.
lets use single array cbAdd as below -
$(document).on("change", ".checkBox", function(){
var value = $(this).val();
var index = cbAdd.indexOf(value);
if ($(this).is(":checked")) {
cbAdd.push(value); //put value
} else {
cbAdd.splice(index, 1);//remove value
}
if(cbAdd.length > 0) {
$('#delete').fadeIn();
} else {
$('#delete').fadeOut();
}
});

Categories

Resources