Difficulty merging ajax results with html - frustrated

Hi,

New to JS last week, I think I have made reasonable progress but I am stuck and becoming frustrated :frowning:

The code below is quite long. sorry about that.

The code shows the html of one nav filter ( in ‘filtering_div’), which has been generated by my script server-side. It shows all categories, sub_categories and colours available across the product_department and when anything is clicked, it fires of through ajax to bring back the various products for a shopping catalogue. It doesn’t however adjust its listings only to show choices that are still available after having made a selection eg
if I choose kitchen equipment => ‘pedal bins’ I only want the colours that bins are sold in to be selectable.

My code then shows a ‘filters_div’ - which is similar to the above except that it is returned by ajax and shows only the links that can be selected in category or sub_category or colours, once an initial selection has been made in one of those divisions. This means, if I select ‘Pedal bins’ the only colours that will show are those that ‘pedal bins’ are made in.
So it does as I want but there are issues with it.

Current issues:-

  1. I don;t want both selectable drop-down type filter menus on the same page - I want them merged.
  2. the ‘filters_div’ (ajax-generated) menu won’t work unless the filtering div is also in the html.

Please also help me to understand why the ajax filter won’t work without the filtering_div being in the html.

I’ll appreciate whatever assistance you may be able to offer.
Oh, nearly forgot: Here’s the code

HTML

<!DOCTYPE html>

  <html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta name=viewport content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
  <title></title>
  <meta name="keywords" content="" />
  
  <meta name="description" content="0" />
  <meta name="Copyright" content="2016" />
  <meta name="distribution" content="Global" />
  <meta name="Language" content="en" />
  <meta name="revisit-after" content="7 days" />
  <meta name="SKYPE_TOOLBAR" content="SKYPE_TOOLBAR_PARSER_COMPATIBLE"/>	<!-- load jQuery -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script> 
  <!-- start of default fonts -->
           
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <!-- end of default fonts -->
    <link rel="stylesheet" href="/cgi-bin/library/stylesheets_screen_default.pl/62593/" type='text/css' media='screen' />
	<link rel="stylesheet" href="/cgi-bin/library/stylesheets_print_default.pl/62593/" type='text/css' media='print' /> 
    <link rel="stylesheet" href="/cgi-bin/library/stylesheets_screen_override.pl/62593/" type='text/css' media='screen' />
	<link rel="stylesheet" href="/cgi-bin/library/stylesheets_print_override.pl/62593/" type='text/css' media='print' /> 
  </head> 
    <body> 

 
<div id='main_content'>

  <div id="filtering_div">
      <h1>home & garden</h1>
          <div class="tab">
           <input id="tab-zero" type="checkbox" name="tabs" />
           <label for="tab-zero"></label> 
              <div class="tab-content">  
                <p>
                  <input type="checkbox" id="product_department:home & garden" checked=checked />
                  <label for="product_department:home & garden">home & garden</label>
                </p>
              </div>
          </div>

          <div class="tab">
            <input id="tab-one" type="checkbox" name="tabs">
            <label for="tab-one">product category</label>
            <div class="tab-content">  
                  <p>
                    <input type="checkbox" id="product_category:kitchen equipment" />
                    <label for="product_category:kitchen equipment">kitchen equipment <span class='lowercase'></span></label>
                  </p> 
            </div>
          </div>
          <div class="tab">
            <input id="tab-two" type="checkbox" name="tabs">
            <label for="tab-two">sub category</label>
            <div class="tab-content">  
                  <p>
                    <input type="checkbox" id="sub_category:kettles" />
                    <label for="sub_category:kettles">kettles <span class='lowercase'></span></label>
                  </p> 
                  <p>
                    <input type="checkbox" id="sub_category:pedal bins" />
                    <label for="sub_category:pedal bins">pedal bins <span class='lowercase'></span></label>
                  </p> 
                  <p>
                    <input type="checkbox" id="sub_category:tea makers" />
                    <label for="sub_category:tea makers">tea makers <span class='lowercase'></span></label>
                  </p> 
                  <p>
                    <input type="checkbox" id="sub_category:utensils" />
                    <label for="sub_category:utensils">utensils <span class='lowercase'></span></label>
                  </p> 
            </div>
          </div>
          <div class="tab">
            <input id="tab-three" type="checkbox" name="tabs">
            <label for="tab-three">brand name</label>
            <div class="tab-content">  
                  <p>
                    <input type="checkbox" id="brand_name:brabantia" />
                    <label for="brand_name:brabantia">brabantia <span class='lowercase'></span></label>
                  </p> 
                  <p>
                    <input type="checkbox" id="brand_name:goodgrips" />
                    <label for="brand_name:goodgrips">goodgrips <span class='lowercase'></span></label>
                  </p> 
                  <p>
                    <input type="checkbox" id="brand_name:kenwood" />
                    <label for="brand_name:kenwood">kenwood <span class='lowercase'></span></label>
                  </p> 
            </div>
          </div>
          <div class="tab">
            <input id="tab-four" type="checkbox" name="tabs">
            <label for="tab-four">colours</label>
            <div class="tab-content">  
                  <p>
                    <input type="checkbox" id="colours:red black and silver" />
                    <label for="colours:red black and silver">red black and silver <span class='lowercase'></span></label>
                  </p> 
                  <p>
                    <input type="checkbox" id="colours:stainless steel" />
                    <label for="colours:stainless steel">stainless steel <span class='lowercase'></span></label>
                  </p> 
                  <p>
                    <input type="checkbox" id="colours:stainless steel & black" />
                    <label for="colours:stainless steel & black">stainless steel & black <span class='lowercase'></span></label>
                  </p> 
            </div>
          </div>
          
  <div id='filters_div' style='font-size:0.5em;width: 850px;'></div>

  <div id="shopping_index" class='four'>  </div>

  <div id="debug" style='float:none;background:#ccc;width: 500px;'></div>

ajax/javascript


    <script src="https://code.jquery.com/jquery-latest.js"></script> 
    <script>

    debug = true;
    function handleDebug(debugInfo)
    {
    $("#debug").html("" + debugInfo + "");
    }


    function makeTable(data)
    {
    var tbl_body = "";
    
    



        $.each(data, function(k, v) 
        {
        var row = "",
        currRecord = this;


           // if( k === "debug" )
           // {
           //
           //     if( debug === true )
           //     {
           //     //handleDebug(v);
           //     }
           // return;
           // }





            $.each(this, function(k , v) 
            {
              
                if( k === 'product_name' )
                {

                /* trim the product name to be just 'length' characters */
                var string = currRecord['product_name'];
                var length = 25;
                var trimmedString = (string.substring(0, length));



                v =  "<table><tr><td class='product_image'>"
                     + "<a href='/cgi-bin/catalogue_detail/" 
                     + currRecord['stock_data_id'] 
                     + "/"
                     + currRecord['product_name'] 
                     + "'>"
                     + "<img class='galleryThumbnail' src='/cgi-bin/mask.pl?client=" 
                     + currRecord['business_id'] 
                     + "&size=small-size&img=" 
                     + currRecord['image_name'] 
                     + "' rel='lightbox[" 
                     + currRecord['product_id'] 
                     + "]' title='" 
                     + currRecord['product_name'] 
                     + " - "
                     + currRecord['colour']
                     + "' /></a>"
                     + "</td></tr><tr><td>"
                     + "<h2>"
                     + "<a href='/cgi-bin/catalogue_detail/" 
                     + currRecord['stock_data_id'] 
                     + "/"
                     + currRecord['product_name'] 
                     + "'>" 
                     + currRecord['brand_name'] 
                     + "</a></h2></td></tr><tr><td class='price'>"
                     + "<div class='price_data'>"
                     + "<p>" + trimmedString + "</p>"
         
                     + "<p>" + currRecord['colour'] + "(" + currRecord['size'] + ")</p>"
                     + "<p>"  + currRecord['stock_availability'] + "</p>"
                     + "<p>"  + currRecord['currency_symbol_left'] + "&nbsp;" + currRecord['price'] + "</p>"
                     + "</div></td></tr></table>";
                row += ""+v+ "";
                }
                else if ( k === 'size' )
                {
                //v = "<div>" + v + "</div>";  
                //row += "<p>"+v+"</p>";
                }
                else if ( k === '' )
                {
                //row += "<h1>sorry no results here</h1>";
                }
                else
                {

                } 

         
            })
 


            tbl_body += "<div class='image_tab'>"+row+"</div>";
        })

    
    
    return tbl_body;
    }
 
 



    function getCatalogueFilterOptions()
    {
    var opts = [];
   

        $checkboxes.each(function()
        {
            if(this.checked)
            {
            opts.push(this.id);
            }
        });
 
    return opts;
    }
 


    function updateCatalogue(opts)
    {
 
        $.ajax(
        {
        type: "POST",
        url: "/php-queries/product-catalogue-query.php",
        
        dataType : 'json',
        cache: false,
        data: {filterOpts: opts},
          success: function(records)
          {
          //alert('SUCCESS!');
          // alert(records);
           $('#shopping_index').html(makeTable(records));
          },

          failure: function()
          {
          alert('NO RESULTS'); 
          }    


         

        });
    }
    




    function makeFilter(data)
    {
    var dataset="";
    var product_data = [];
    var product_data1=[]; 
  
    var available_departments = [];
    var restricted_departments = [];
    var available_categories = [];
    var restricted_categories = [];

    var available_sub_categories = [];
    var restricted_sub_categories = [];

    var available_colours = [];
    var restricted_colours = [];



        $.each(data, function(k, v) 
        {
        var row = "",
        currRecord= this;
        var dataString = '';
              
           if( k === "debug" )
           {
          
               if( debug === true )
               {
               handleDebug(v);
               }
           //return;
           }

            $.each(this, function(k , v) 
            {
            var department = currRecord['product_department'];
            var cat = currRecord['category'];
            var sub_cat = currRecord['sub_category'];
            var colour = currRecord['colour'];


                   
           
            // build array of available_departments
            var obj = available_departments.find( o => o.product_department === department );
            if ( !( obj ) )
            {
            available_departments.push({product_department: department } );
            }



            // build array of available categories
            var obj = available_categories.find(o => o.product_category === cat );
            if ( !(obj) )
            {
            available_categories.push({product_category: cat });
            }

            // build array of available_sub_categories
            var obj = available_sub_categories.find(o => o.sub_category === sub_cat );
            if ( !(obj) )
            {
            available_sub_categories.push({sub_category: sub_cat });
            }


            // build array of available_colours
            obj = available_colours.find(o => o.colours === colour );
            if ( !(obj) )
            {
            available_colours.push({colours: colour });
            }




              
            //row += v;
            })
        //  dataset = "" +row+ "";
        })

 

  // sort the array avalable_colours alphabetically
  
   var sac= available_colours.sort(function(a, b)
  { // sort object by colour

	var colourA=a.colours, colourB=b.colours
	if (colourA < colourB) //sort string ascending
 		return -1 
	if (colourA > colourB)
		return 1
	return 0 //default return value (no sorting)
  })
  

 
//console.log(available_categories);
//console.log(available_sub_categories);
//console.log(available_colours);


//////////////////////////////////////////////////////
// output the html for the nav filter
//////////////////////////////////////////////////////
//   if ( available_departments )
//   {
//  dataset = "<div class='tab'>"
//           + "  <input id='tab-zzero' type='checkbox' name='tabs' />" 
//           + "  <label for='tab-zzero'>Product Department</label>" 
//           + "  <div class='tab-content'>"  
//           + "    <p>"
//           + "      <input type='checkbox' id='product_department:home & garden'  />"
//           + "      <label for='product_department:home & garden'>home & garden</label>"
//           + "    </p>"
//           + "  </div>"
//           + "</div>";
//  }


  if ( available_categories )
  {
  dataset += "<div class='tab'>" + "<input id='tab-zone' type='checkbox' name='tabs' />" + "<label for='tab-zone'>product category</label>" + "<div class='tab-content'>";

  // loop through the array to output more data
  $.each(available_categories, function(k , v) 
  {

      $.each(this, function(k , v) 
      {
      dataset += "<p>" + "<input type='checkbox' id='product_category:" + v + "' />" + "<label for='product_category:" +v+ "'>" +v+ "</label>" + "</p>";
      })
  })
  dataset += "</div></div>";
  }



  if ( available_sub_categories )
  {
  dataset += "<div class='tab'>"
           + "<input id='tab-ztwo' type='checkbox' name='tabs' />"
           + "<label for='tab-ztwo'>sub category</label>"
           + "<div class='tab-content'>";

  //loop through the array to output more data
  $.each(available_sub_categories, function(k , v) 
  {

      $.each(this, function(k , v) 
      {
      dataset += "<p>"
               + "<input type='checkbox' id='sub_category:"
               + v
               + "' />"
               + "<label for='sub_category:"
               + v
               + "'>"
               + v
               + "</label>"
               + "</p>";
      })
  })
  dataset += "</div></div>";
  }

//console.log(available_colours);

  if ( available_colours )
  {
  dataset += "<div class='tab'>"
           + "  <input id='tab-zfour' type='checkbox' name='tabs' />"
           + "  <label for='tab-zfour'>colours</label>"
           + "  <div class='tab-content'>";

  

  

  
  //loop through the array to output more data
  $.each(sac, function(k , v) 
  {
  
      
      $.each(this, function(k , v) 
      {

      dataset += "<p>"
               + "<input type='checkbox' id='colours:"
               + v
               + "' />"
               + "<label for='colours:"
               + v
               + "'>"
               + v
               + "</label>"
               + "</p>";
          
      })
  })
  dataset += "</div></div>";
  }




//console.log(sac);
//console.log(dataset);



 


return dataset;
}



   






    function update_nav_filter(opts)
    {
 
        $.ajax(
        {
        type: "POST",
        url: "/php-queries/product-filter-query.php",
        
        dataType : 'json',
        cache: false,
        data: {filterOpts: opts},
          success: function(records)
          {
          //alert('SUCCESS!');
          // alert(records);
          $('#filters_div').html(makeFilter(records));
          },

          // failure: function()
          // {
          // alert('NO RESULTS'); 
          // }    


         

        });
    }








    function subsidyIsValid()
    {
    var amount1 = $("#amount1").val(),
    amount2 = $("#amount2").val(),
    regex = /^\d+$/,
    inputValid = false;

        if(regex.test(amount1) && regex.test(amount2))
        {
        var newTotal = Number(amount1) + Number(amount2)
        
        $("#total").text(newTotal);
        inputValid = true;
        }

    return inputValid
    }





    function updatePrices()
    {
    var subsidyTotal = Number($("#total").text());

        $(".price").each(function()
        {
        var origVal = Number($(this).text())
        $(this).text(origVal - subsidyTotal)
        })
    }




    var $checkboxes = $("input:checkbox");
    $checkboxes.on("change", function()
    {
    var opts = getCatalogueFilterOptions();
    updateCatalogue(opts);
    update_nav_filter(opts);
    });
    





  
    $("#apply").on("click", function()
    {
    
         if(subsidyIsValid())
         {
         $(this).prop("disabled", true);
         $(this).next().prop("disabled", false);
         updatePrices();
         }
         else 
         {
         alert("Subsidy invalid!")
         }
    });




    $("#remove").on("click", function()
    {
    $("#amount1").val("");
    $("#amount2").val("");
    $("#total").text("0");
    $(this).prop("disabled", true);
    $(this).prev().prop("disabled", false);
    $checkboxes.trigger("change");
    });



    $checkboxes.trigger("change");
    updatePrices();
    </script>

CSS and remaining html



<style>
#filtering_div{
  width: 300px; /* !important;*/
  text-transform: capitalize;
  margin:0 auto !important;
  font-size: 1em !important;
  zheight: 600px;
}
#filtering_div h1{
  font-size: 1em;
}
#shopping_index{
clear:left;
}
/* Acordeon styles */
.tab {
  position: relative;
  margin-bottom: 0;
  width: 100%;
  color: #fff;
text-transform: capitalize;
}
.tab input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}
.tab label {
  position: relative;
  display: block;
  padding: 0 0 0 10px; /* 0 0 1em;*/
  background: #717074; /*#16a085;*/
  font-weight: bold;
  line-height: 1.5em;
  cursor: pointer;
}
.blue label {
  background: #2980b9;
}
.tab-content {
  max-height: 0;
  width: 100%;
  overflow: hidden;
  font-size: 0.7em;
  background: inherit; 
  -webkit-transition: max-height .50s;
  -o-transition: max-height .50s;
  transition: max-height .50s;
}
.blue .tab-content {
  background: #3498db;
}
.tab-content label{
  background-color: #fff;
  margin:0;
  padding:0;
  border:0;
  color: #717074;
}
.tab-content p {
  clear:left;
  display:block;
  text-align:left;
  margin: 0; /*1em;*/
  border: 1px solid #1b1b1b;
  border-left: 0;
  border-right:0;
  border-top:0;
}
/* :checked */
.tab input:checked ~ .tab-content {
  max-height: 200vh;
}


/* Icon */

.tab label::after {
  position: absolute;
  right: 0;
  top: 0;
  display: inline-block;
  vertical-align:middle;
  -webkit-transition: all 1.35s;
  -o-transition: all 1.35s;
  transition: all 1.35s;
  
}

.tab input[type=checkbox] + label::after {
  content: "+";
  display:none;
}
.tab input[type=radio] + label::after {
  content: "\25BC";
}
.tab input[type=checkbox]:checked + label::after {
  transform: rotate(315deg);
}
.tab input[type=radio]:checked + label::after {
  transform: rotateX(180deg);
}


/*  my mods */
.lowercase{
text-transform:lowercase;
}
.tab-content input{
  position: initial;
  display:none;
  opacity: 0;
  z-index:initial;
  margin: 1em;
}
.tab-content label{
  display: block;
  line-height: 1.5em;
}
.tab-content input[type=checkbox] + label::after{
  display:none;
  content:'';
}

.tab-content input[type=checkbox] + label::before{
  content: '\2713';
  color: #dad8da;
  margin-right: 10px;
  -webkit-transition: all .75s;
  -o-transition: all .75s;
  transition: all .75s;
}

.tab-content input[type=checkbox]:checked + label::before {
  content: "\2713"; 
  transform: none;
  color: green; /*#a31e22;*/
  font-weight: 700;
}
/* end of my mods*/
</style>
 
 
 
 
 
 
 
 
 
 
<!-- end of main content div -->
</div>
 
 
   
 
  </body>
</html>


Bazz

I have edited my introduction above, so I hopefully make my problem easier to understand.
If any of you wish to help, I shall send you a link to the page because it’s much easier to understand the issue when you can see it in action. Its on a sub-domain of a live domain so I don’t want to post it here.

Basically, I have narrowed it down.

  1. the ajax generated nav bar functions if the script-generated one has its tags empty.
  2. even with that, the css works in the script generated one but the ::before and ::after elements don’t play.

Bazz

I appear to have resolved the functionality issues but the css doesn’t take effect correctly in the JS parts of the page. I’ll post that issue as a new question.

Bazz

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.