SitePoint Sponsor

User Tag List

Page 3 of 4 FirstFirst 1234 LastLast
Results 51 to 75 of 98
  1. #51
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,056
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hey there,

    It's better if I can just summarize what I have understood you to want, then implement those changes in my example.
    You can then adapt them to what you have.

    So, you would like to start off showing all records and having the check boxes unchecked.
    After that you would like to filter the results according to what is checked.
    For example, if the user checks "Samsung", only the Samsung phones should be shown.
    If the user then checks "iPhone", Samsung and iPhone phones should be displayed.
    If the user then removes unchecks all of the boxes, every record should be displayed.

    Is that correct?

  2. #52
    SitePoint Enthusiast
    Join Date
    Dec 2013
    Posts
    26
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Hello,

    Yes that is correct,

    only one thing ... that "subvention" script ...at this momment if all checkbox is unchecked...if i click on calculate, nothing happens ...but after i click on any checkbox to filter my content, automaticly the "subvention" script works.

  3. #53
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,056
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi Norbert,

    Sorry it took a while to get back to you. I was quite busy

    Anyway, it is quite simple to do what you want.

    First thing to do is to remove the checked attribute from the checkboxes:

    Code:
    <h2>Filter options</h2>
    <div>
      <input type="checkbox" id="Samsung">
      <label for="Samsung">Samsung</label>
    </div>
    <div>
      <input type="checkbox" id="iPhone">
      <label for="iPhone">iPhone</label>
    </div>
    <div>
      <input type="checkbox" id="HTC">
      <label for="HTC">HTC</label>
    </div>
    <div>
      <input type="checkbox" id="LG">
      <label for="LG">LG</label>
    </div>
    <div>
      <input type="checkbox" id="Nokia">
      <label for="Nokia">Nokia</label>
    </div>
    The JS that is responsible for fetching the records when the page loads is this:

    Code:
    $checkboxes.trigger("change");
    Replace this with the following:

    Code:
    var allBrands = [];
    $("input[type=checkbox]").each(function(){
      allBrands.push($(this)[0].id)
    })
    
    updatePhones();
    This gets a list of all the available brands that the PHP script can filter by.

    Now we need to update the updatePhones function with this:

    Code:
    if(!opts || !opts.length){
      opts = allBrands;
    }
    which checks to see if the function was passed either nothing or an empty array as a parameter.
    If this is the case, it resorts to using all available brands.

    We leave the PHP file untouched. Here's the new HTML:

    Code:
    <!DOCTYPE HTML>
    <html>
      <head>
        <meta charset="utf-8">
        <title>AJAX filter demo</title>
        <style>
          body {
            padding: 10px;
          }
     
          h1 {
              margin: 0 0 0.5em 0;
              color: #343434;
              font-weight: normal;
              font-family: 'Ultra', sans-serif;   
              font-size: 36px;
              line-height: 42px;
              text-transform: uppercase;
              text-shadow: 0 2px white, 0 3px #777;
          }
     
          h2 {
              margin: 1em 0 0.3em 0;
              color: #343434;
              font-weight: normal;
              font-size: 30px;
              line-height: 40px;
              font-family: 'Orienta', sans-serif;
          }
     
          #phones {
            font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
            font-size: 12px;
            background: #fff;
            margin: 15px 25px 0 0;
            border-collapse: collapse;
            text-align: center;
            float: left;
          }
     
          #phones th {
            font-size: 14px;
            font-weight: normal;
            color: #039;
            padding: 10px 8px;
            border-bottom: 2px solid #6678b1;
          }
     
          #phones td {
            border-bottom: 1px solid #ccc;
            color: #669;
            padding: 8px 10px;
          }
     
          #phones tbody tr:hover td {
            color: #009;
          }
     
          #filter {
            float:left;
          }
    
          fieldset{
            margin-top: 15px;
          }
    
          fieldset div{
            padding:0 0 5px 0;
          }
    
          .amount{
            width:50px;
          }
        </style>
      </head>
      <body> 
        <h1>Phones database</h1>
     
        <table id="phones">
          <thead>
            <tr>
              <th width="15">ID</th>
              <th>Brand</th>
              <th>Model</th>
              <th>Price</th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
     
    <div id="filter">
    <h2>Filter options</h2>
    <div>
      <input type="checkbox" id="Samsung">
      <label for="Samsung">Samsung</label>
    </div>
    <div>
      <input type="checkbox" id="iPhone">
      <label for="iPhone">iPhone</label>
    </div>
    <div>
      <input type="checkbox" id="HTC">
      <label for="HTC">HTC</label>
    </div>
    <div>
      <input type="checkbox" id="LG">
      <label for="LG">LG</label>
    </div>
    <div>
      <input type="checkbox" id="Nokia">
      <label for="Nokia">Nokia</label>
    </div>
    
      <fieldset>
        <legend>Subsidy</legend>
        <div>
          <label for="amount1">Amount 1:</label>
          <input type="text" class="amount" id="amount1" />
        </div>
    
        <div>
          <label for="amount2">Amount 2:</label>
          <input type="text" class="amount" id="amount2" />
        </div>
    
        <div>Total: $<span id="total">0</span></div>
        
        <button id="apply">Apply</button>
        <button id="remove" disabled>Remove</button>
      </fieldset>
    </div>
    
        <script src="http://code.jquery.com/jquery-latest.js"></script> 
        <script>
          function makeTable(data){
            var tbl_body = "";
            $.each(data, function() {
              var tbl_row = "",
                  currRecord = this;
    
              $.each(this, function(k , v) {
                if(k==='model'){
                  v = "<a href='content.php?id=" + currRecord['id'] +"'>" + v + "</a>";
                } else if (k==='price'){
                  v = "<span class='price'>" + v + "</span>";
                }
                tbl_row += "<td>"+v+"</td>";
              })
              tbl_body += "<tr>"+tbl_row+"</tr>";
            })
    
            return tbl_body;
          }
     
          function getPhoneFilterOptions(){
            var opts = [];
            $checkboxes.each(function(){
              if(this.checked){
                opts.push(this.id);
              }
            });
     
            return opts;
          }
     
          function updatePhones(opts){
            if(!opts || !opts.length){
              opts = allBrands;
            }
    
            $.ajax({
              type: "POST",
              url: "submit.php",
              dataType : 'json',
              cache: false,
              data: {filterOpts: opts},
              success: function(records){
                $('#phones tbody').html(makeTable(records));
                updatePrices();
              }
            });
          }
          
          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 = getPhoneFilterOptions();
            updatePhones(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");
          });
    
          var allBrands = [];
          $("input[type=checkbox]").each(function(){
            allBrands.push($(this)[0].id)
          })
    
          updatePhones();
          updatePrices();
        </script> 
      </body> 
    </html>
    DEMO

    Hope that helps.

  4. #54
    SitePoint Enthusiast
    Join Date
    Dec 2013
    Posts
    26
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Thank you Pullo, this is the final version
    when you have time, please make a copy - paste for the content of submit.php used for this final example and also post it here... i just want to check a few things compared with the first versions of this thread.

    Thank you

  5. #55
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,056
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    No problem

    Code:
    <?php 
      $pdo = new PDO('mysql:host=localhost;dbname=sitepoint', 'root', '****');
      $opts = $_POST['filterOpts'];
      $qMarks = str_repeat('?,', count($opts) - 1) . '?';
      $statement = $pdo->prepare("SELECT mobile_phone.id, name, model, price FROM mobile_phone INNER JOIN brand ON brand_id = brand.id WHERE name IN ($qMarks)");
      $statement -> execute($opts);
      $results = $statement -> fetchAll(PDO::FETCH_ASSOC);
      $json = json_encode($results);
      echo($json);
    ?>

  6. #56
    SitePoint Enthusiast
    Join Date
    Dec 2013
    Posts
    26
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    One short question...

    we have this line of code from submit.php
    Code:
      $statement = $pdo->prepare("SELECT mobile_phone.id, name, model, price FROM mobile_phone INNER JOIN brand ON brand_id = brand.id WHERE name IN ($qMarks)");
    hypothetically speaking just for learning ... if i don`t want to work with 2 mysql tabels and with the inner join function.

    For example if i have only one table: id, name, model, price, brand, operating_system

    and i want to use thise line of code:
    Code:
      $statement = $pdo->prepare("SELECT id, name, model, price FROM mobile_phone WHERE name in ($qMarks)");
    how to implement multiple where conditions?

    Code:
      $statement = $pdo->prepare("SELECT id, name, model, price FROM mobile_phone WHERE name IN ($qMarks) OR operating_system IN ($qMarks) OR memory_ram IN ($qMarks)");
    etc.

  7. #57
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,056
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    I suggested the above method (with the $qMarks variable) as a way of binding an array to an IN() condition?
    Kind of like:
    Code:
    SELECT * FROM table WHERE something IN(:an_array)
    However, it seems that you want to select records according to the name, operating_system and memory_ram variables, references to which you are passing into your PHP script, so this method isn't suitable.

    Instead, you would do this like this (untested):

    Code:
    $name = $_POST['name'];
    $os = $_POST['os'];
    $ram = $_POST['ram'];
    
    $statement = $pdo->prepare("SELECT id, name, model, price FROM mobile_phone WHERE name = :name OR  operating_system = :os OR memory_ram = :ram");
    $statement->bindParam(':name', $name, PDO::PARAM_STR);
    $statement->bindParam(':os', $os, PDO::PARAM_STR);
    $statement->bindParam(':ram', $ram, PDO::PARAM_STR);
    $statement -> execute($opts);
    $results = $statement -> fetchAll(PDO::FETCH_ASSOC);
    Make sense?

  8. #58
    SitePoint Enthusiast
    Join Date
    Dec 2013
    Posts
    26
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Yeeep, it make sense,

    This is the reason why people like you working in the IT industry, and people like me make this just like a hobby

    You are a smart guy Pullo, I hope someday you'll get far in this business because you deserve it.

  9. #59
    SitePoint Enthusiast
    Join Date
    Dec 2013
    Posts
    26
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Hello Pullo,

    did u notice a strange fact? ... all of this work, is not working in Internet Explorer 8

    have a look:

    http://netrenderer.com/index.php

    copy paste this url


    Please tell me with your smart brain that is some minor compatibility issue...and a new jqwery version or something like this can easly fix this
    Last edited by Pullo; Feb 9, 2014 at 00:44.

  10. #60
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,056
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    I have never heard of the site netrenderer.com, so I was interested to check this out.

    You're right, my site is broken using netrenderer's IE8 view.
    This had me scratching my head for quite a while, as there is no JS on the page that shouldn't work in IE8.

    I therefore installed Win7 on a virtual machine (I'm on Linux) so that I could test in an real IE8.
    Good news was that it works

    Attachment 64026

    You can tell that it is IE8 from the dropdown in the top right hand corner that says "Neues in Internet Explorer8"

    I guess that the problem is with netrenderer, which is a shame, a it would have been a useful resource.

  11. #61
    SitePoint Enthusiast
    Join Date
    Dec 2013
    Posts
    26
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Hello,

    hmmm strange....

    i also made a few tests,

    i want to show you my submit.php file to have a look at how i implemented the whole code in my final product:

    Code:
    <?php 
      $pdo = new PDO('mysql:host=localhost;dbname=database', 'root', '');
      $select = 'SELECT id, device_cod, device_name, price, 1year_contract, 2year_contract, renewel_contract';
      $from = ' FROM mobile_phones';
      $where = ' WHERE TRUE';
      $opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
      
      if (in_array("touchscreen", $opts))	{ $where .= " AND touchscreen = 1"; }
      if (in_array("qwerty", $opts))		{ $where .= " AND qwerty = 1"; }
      if (in_array("clasic", $opts))		{ $where .= " AND clasic = 1"; }
      if (in_array("dual_sim", $opts))		{ $where .= " AND dual_sim = 1"; }
      if (in_array("android", $opts))		{ $where .= " AND android = 1"; }
      if (in_array("ios", $opts))			{ $where .= " AND ios = 1"; }
      if (in_array("windows", $opts))		{ $where .= " AND windows = 1"; }
      if (in_array("other_os", $opts))		{ $where .= " AND other_os = 1"; }
      if (in_array("no_camera", $opts))		{ $where .= " AND no_camera = 1"; }
      if (in_array("vga_4mp", $opts))		{ $where .= " AND vga_4mp = 1"; }
      if (in_array("5mp", $opts))			{ $where .= " AND 5mp = 1"; }
      if (in_array("8mp", $opts))			{ $where .= " AND 8mp = 1"; }
      if (in_array("13mp", $opts))			{ $where .= " AND 13mp = 1"; }
      if (in_array("single_core", $opts))	{ $where .= " AND single_core = 1"; }
      if (in_array("dual_core", $opts))		{ $where .= " AND dual_core = 1"; }
      if (in_array("quad_core_core", $opts)){ $where .= " AND quad_core = 1"; }
    
    
    
      $sql = $select . $from . $where;
      $statement = $pdo->prepare($sql);
      $statement->execute();
      $results = $statement->fetchAll(PDO::FETCH_ASSOC);
      $json = json_encode($results);
      echo($json);
    ?>
    I have a mobile_phones database with 250 phones ... and as you can see with multiple filter options.

    All of this work what i done with your help (Thank you again!!!) i use it at my work (a small local gsm shop) where is implementet via intranet, where also

    90 % off different softwares and aplications is implemented to work with Internet Explorer 8 (this are the requirements).
    Now i observed a strange thing...if i acces this mobile phones filter webpage from Mozzila, Chrome, IE9 or higher ... is loading and working like a charm, if i acces it from Internet Exporer 8 i have a huge 15 - 20 second lag and almost IE 8 crash on loading. After is loaded everything is working well, if i use some filters ...is working on click...so my question is ... am i done some "hard coding" in the above submit.php file what can be corrected?

  12. #62
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,056
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi Norbert,

    I can't see anything in the code you posted which might be slowing IE8 down.

    To debug this might be quite tricky, so let's start by removing as much as we can from the JS.

    To do this, I'll need to be seeing what you see.
    Could you post a dump of your DB table, and the contents of index.php (or whatever you have called it).

  13. #63
    SitePoint Member
    Join Date
    Feb 2014
    Posts
    12
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Thank you so much for this is a great example.

    I have now got this working on my local web server and want to start to change how it works. At the moment i am editing the SQL on the submit.php page, however i am wondering how i print what SQL is being run to the to the screen, so i can test the SQL is correct. In php i would normally do an echo $SQL; exit; but this does not work. I presume i need to do something similar but not sure what?

    Can you advise please?

  14. #64
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,056
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    It should be possible.
    What does your PHP code currently look like?

  15. #65
    SitePoint Member
    Join Date
    Feb 2014
    Posts
    12
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the reply. Below is my PHP code. My PDO connection is in another file that i call.

    Code:
    require_once('include/maininclude.php');
    require_once('include/form_functions.php');
    
    $Select = "SELECT CandidateName, JobArea, CurrentLocation, ContractType, CurrentRate, RequiredRate, NoticePeriod, Locations, Europe, Asia, MiddleEast, NorthAmerica, FirstProduct, SecondProduct, ID";
    	$From = " FROM tbltrading_immediatelist";
    	$Where = " WHERE TRUE";
    	$FilterOptions = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
    		
    		//	LOCATIONS
    		if(in_array("Asia", $FilterOptions))		{$Where .= " AND Asia = 1";}
    		if(in_array("Europe", $FilterOptions))		{$Where .= " AND Europe = 1";}
    		if(in_array("MiddleEast", $FilterOptions))	{$Where .= " AND MiddleEast = 1";}
    		if(in_array("NorthAmerica", $FilterOptions)){$Where .= " AND NorthAmerica = 1";}
    		
    		//	NOTICE PERIOD
    		if(in_array("Immediate", $FilterOptions)){$Where .= " AND NoticePeriod = 'Immediate'";}
    		if(in_array("1 Week", $FilterOptions)){$Where .= " AND NoticePeriod = '1 Week'";}
    		if(in_array("2 Weeks", $FilterOptions)){$Where .= " AND NoticePeriod = '2 Weeks'";}
    		if(in_array("3 Weeks", $FilterOptions)){$Where .= " AND NoticePeriod = '3 Weeks'";}
    		if(in_array("1 Month", $FilterOptions)){$Where .= " AND NoticePeriod = '1 Month'";}
    		if(in_array("2 Months", $FilterOptions)){$Where .= " AND NoticePeriod = '2 Months'";}
    		
    $SQL = $Select . $From . $Where;
    $Statement = $PDO->prepare($SQL);
    $Statement -> execute();
    $Results = $Statement -> fetchAll(PDO::FETCH_ASSOC);
    $json = json_encode($Results);
    
    echo($json);

  16. #66
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,056
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    You would have to do the following:

    Create a <div> element with the id of "debug" directly after your opening <body> tag.
    Code:
    <body>
      <div id="debug"></div>
    At the very start of your script declare a global variable debug and set it to true.
    Code:
    debug = true;
    Change the makeTable function accordingly:

    Code:
    function makeTable(data){
      var tbl_body = "";
    
      $.each(data, function(k, v) {
        var tbl_row = "",
            currRecord = this;
    
        if(k==="debug"){
          if(debug === true){
            handleDebug(v);
          }
          return;
        }
    
        $.each(this, function(k , v) {
          if(k==='model'){
            v = "<a href='content.php?id=" + currRecord['id'] +"'>" + v + "</a>";
          } else if (k==='price'){
            v = "<span class='price'>" + v + "</span>";
          }
          tbl_row += "<td>"+v+"</td>";
        })
        tbl_body += "<tr>"+tbl_row+"</tr>";
      })
    
      return tbl_body;
    }
    Add the function handleDebug()

    Code:
    function handleDebug(debugInfo){
      $("#debug").html("<pre>" + debugInfo + "</pre>");
    }
    Add some styling:

    Code:
    pre{
      margin:0 0 20px 0;
      padding:10px;
      background: gray;
    }
    Then in your submit.php file, you'll need to alter what is returned to the ajax success callback:

    Code:
    $SQL = $Select . $From . $Where;
    $Statement = $PDO->prepare($SQL);
    $Statement -> execute();
    $Results = $Statement -> fetchAll(PDO::FETCH_ASSOC);
    $Results = array_merge(array("debug" => $SQL), $Results); <----------- this is new
    $json = json_encode($Results);
    
    echo($json);
    And that should do the trick.
    Let me know how you get on.


    Just in case you get into any difficulties, here's how I got it to work on my previous example:

    Code:
    <!DOCTYPE HTML>
    <html>
      <head>
        <meta charset="utf-8">
        <title>AJAX filter demo</title>
        <style>
          body {
            padding: 10px;
          }
     
          h1 {
              margin: 0 0 0.5em 0;
              color: #343434;
              font-weight: normal;
              font-family: 'Ultra', sans-serif;   
              font-size: 36px;
              line-height: 42px;
              text-transform: uppercase;
              text-shadow: 0 2px white, 0 3px #777;
          }
     
          h2 {
              margin: 1em 0 0.3em 0;
              color: #343434;
              font-weight: normal;
              font-size: 30px;
              line-height: 40px;
              font-family: 'Orienta', sans-serif;
          }
     
          #phones {
            font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
            font-size: 12px;
            background: #fff;
            margin: 15px 25px 0 0;
            border-collapse: collapse;
            text-align: center;
            float: left;
          }
     
          #phones th {
            font-size: 14px;
            font-weight: normal;
            color: #039;
            padding: 10px 8px;
            border-bottom: 2px solid #6678b1;
          }
     
          #phones td {
            border-bottom: 1px solid #ccc;
            color: #669;
            padding: 8px 10px;
          }
     
          #phones tbody tr:hover td {
            color: #009;
          }
     
          #filter {
            float:left;
          }
    
          fieldset{
            margin-top: 15px;
          }
    
          fieldset div{
            padding:0 0 5px 0;
          }
    
          .amount{
            width:50px;
          }
    
          pre{
            margin:0 0 20px 0;
            padding:10px;
            background: gray;
          }
        </style>
      </head>
      <body>
        <div id="debug"></div>
    
        <h1>Phones database</h1>
     
        <table id="phones">
          <thead>
            <tr>
              <th width="15">ID</th>
              <th>Brand</th>
              <th>Model</th>
              <th>Price</th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
     
        <div id="filter">
          <h2>Filter options</h2>
          <div>
            <input type="checkbox" id="Samsung">
            <label for="Samsung">Samsung</label>
          </div>
          <div>
            <input type="checkbox" id="iPhone">
            <label for="iPhone">iPhone</label>
          </div>
          <div>
            <input type="checkbox" id="HTC">
            <label for="HTC">HTC</label>
          </div>
          <div>
            <input type="checkbox" id="LG">
            <label for="LG">LG</label>
          </div>
          <div>
            <input type="checkbox" id="Nokia">
            <label for="Nokia">Nokia</label>
          </div>
    
          <fieldset>
            <legend>Subsidy</legend>
            <div>
              <label for="amount1">Amount 1:</label>
              <input type="text" class="amount" id="amount1" />
            </div>
    
            <div>
              <label for="amount2">Amount 2:</label>
              <input type="text" class="amount" id="amount2" />
            </div>
    
            <div>Total: $<span id="total">0</span></div>
            
            <button id="apply">Apply</button>
            <button id="remove" disabled>Remove</button>
          </fieldset>
        </div>
    
        <script src="http://code.jquery.com/jquery-latest.js"></script> 
        <script>
          debug = true;
          function handleDebug(debugInfo){
            $("#debug").html("<pre>" + debugInfo + "</pre>");
          }
    
          function makeTable(data){
            var tbl_body = "";
    
            $.each(data, function(k, v) {
              var tbl_row = "",
                  currRecord = this;
    
              if(k==="debug"){
                if(debug === true){
                  handleDebug(v);
                }
                return;
              }
    
              $.each(this, function(k , v) {
                if(k==='model'){
                  v = "<a href='content.php?id=" + currRecord['id'] +"'>" + v + "</a>";
                } else if (k==='price'){
                  v = "<span class='price'>" + v + "</span>";
                }
                tbl_row += "<td>"+v+"</td>";
              })
              tbl_body += "<tr>"+tbl_row+"</tr>";
            })
    
            return tbl_body;
          }
     
          function getPhoneFilterOptions(){
            var opts = [];
            $checkboxes.each(function(){
              if(this.checked){
                opts.push(this.id);
              }
            });
     
            return opts;
          }
     
          function updatePhones(opts){
            if(!opts || !opts.length){
              opts = allBrands;
            }
    
            $.ajax({
              type: "POST",
              url: "submit.php",
              dataType : 'json',
              cache: false,
              data: {filterOpts: opts},
              success: function(records){
                $('#phones tbody').html(makeTable(records));
                updatePrices();
              }
            });
          }
          
          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 = getPhoneFilterOptions();
            updatePhones(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");
          });
    
          var allBrands = [];
          $("input[type=checkbox]").each(function(){
            allBrands.push($(this)[0].id)
          })
    
          updatePhones();
          updatePrices();
        </script> 
      </body> 
    </html>
    Code:
    <?php 
      $pdo = new PDO('mysql:host=localhost;dbname=sitepoint', 'root', '*****');
      $opts = $_POST['filterOpts'];
      $qMarks = str_repeat('?,', count($opts) - 1) . '?';
      $statement = $pdo->prepare("SELECT mobile_phone.id, name, model, price FROM mobile_phone INNER JOIN brand ON brand_id = brand.id WHERE name IN ($qMarks)");
      $statement -> execute($opts);
      $results = $statement -> fetchAll(PDO::FETCH_ASSOC);
      
      $debugInfo = array('debug' => vsprintf(str_replace("?", "%s", $statement->queryString), $opts));
      $results = array_merge($debugInfo, $results);
    
      $json = json_encode($results);
      echo($json);
    ?>

  17. #67
    SitePoint Member
    Join Date
    Feb 2014
    Posts
    12
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Thank you so much. I have this working perfectly for me now. So as always i have a few more questions about possible changes to the script to make it work slightly better for me.

    I have noticed a checkbox is clicked and this runs the ajax which connects to a php page that runs some sql. This is then returned to the page and is then used to create a table using jQuery, however what i would like is to create this table using PHP as i need to manipulate the data coming back before it is displayed to the end user. How do i get the array of data back from the submit.php into an array that i can then create a while loop in php? Is this possible?

    I have renamed some of functions, but they still do the same thing:

    Code:
    function UpdateFilter(Options){
    		$.ajax({
    			type: "POST",
    			url: "submit.php",
    			dataType : 'json',
    			cache: false,
    			data: {filterOpts: Options},
    			success: function(records){
    				$('#ImmediateList tbody').html(CreateTable(records));
    			}
    		});
    	}

  18. #68
    SitePoint Member
    Join Date
    Feb 2014
    Posts
    12
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the reply, this worked perfectly....

  19. #69
    SitePoint Member
    Join Date
    Feb 2014
    Posts
    12
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I do have a couple more questions around making some changes to the code to make it work for me.

    Currently when a usher clicks a checkbox, this is then sent to the submit.php page so the sql can run against the database, once it has results it then passing these back and jquery builds a dynamic table. What i would like if possible is when the results are posted back that i build the table with PHP as i need to manipulate that data that comes back. Is this possible using a while loop or a foreach? if so how do i do it? Below is the ajax that i currently use, i presume i need to edit the success field to make this work, but i am stuck at this point until i can get the loop running in php:

    Code:
    $.ajax({
    			type: "POST",
    			url: "trading.immediatelist.report_proc.php",
    			dataType : 'json',
    			cache: false,
    			data: {filterOpts: Options},
    			success: function(records){
    				$('#ImmediateList tbody').html(CreateTable(records));
    			}
    		});

  20. #70
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,056
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Well you would build the table in your PHP code (I presume you know how to do this).

    Then you remove the datatype attribute from your ajax call and within your success callback, do something like:

    Code:
    success: function(table){
      $('#ImmediateList').html(table);
    }
    This would give you:

    Code:
    $.ajax({
      type: "POST",
      url: "trading.immediatelist.report_proc.php",
      cache: false,
      data: {filterOpts: Options},
      success: function(records){
        $('#ImmediateList').html(table);
      }
    });

  21. #71
    SitePoint Member
    Join Date
    Mar 2014
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi!
    Thank you for this great stuff, As I tested it via my xampp localhost it works great. Actually, this script i was looking for for my online project using wordpress theme framework. But am finding trouble on implementing on wordpress, as i don't have more experience on jquery/ajax, especially wordpress ajax call. Guys I badly need your help on how to do it on wordpress.

    Look forward your support/help on this. Thank you.
    Last edited by TechnoBear; Mar 4, 2014 at 08:33. Reason: Formatting

  22. #72
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,056
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    Do you have a link to the page where it is not working?

  23. #73
    SitePoint Member
    Join Date
    Mar 2014
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Pullo,

    Sorry for the late reply. It's not actually publish online, What I mean from my previous post is that "tested directly at xampp/localhost but not on wordpress framework environment." but anyway, here's what my initial action taken:
    <?php

    1. create custom template:
    Code:
    <?php
    /*
    Template Name: MYSQL Jquery Ajax Working Template
    */
    ?>
    
    <?php
    get_header();
    ?>
      <h1>Phones database</h1>
    
        <table id="phones">
          <thead>
            <tr>
              <th>ID</th>
              <th>Brand</th>
              <th>Model</th>
              <th>Price</th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
    
        <div id="filter">
          <h2>Filter options</h2>
          <div>
            <input type="checkbox" id="Samsung" checked>
            <label for="Samsung">Samsung</label>
          </div>
          <div>
            <input type="checkbox" id="iPhone" checked>
            <label for="iPhone">iPhone</label>
          </div>
          <div>
            <input type="checkbox" id="HTC" checked>
            <label for="HTC">HTC</label>
          </div>
          <div>
            <input type="checkbox" id="LG" checked>
            <label for="LG">LG</label>
          </div>
          <div>
            <input type="checkbox" id="Nokia" checked>
            <label for="Nokia">Nokia</label>
          </div>
        </div>
    
    
    <?php get_sidebar();?>
    <?php get_footer();?>
    2. cut & paste javascipt to header.php

    My question is this, How to insert the ajax part of this ajax code to wordpress function.php. Am doubt that this js script code is not all at header.php, since wordpress has it's own native built-in ajax.

    Hope this makes sense. Best regards.

  24. #74
    SitePoint Member
    Join Date
    Mar 2014
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Pullo,

    Success!
    After taking so much time, with the help of firebug, I found out that there was an error "NetworkError: 404 Not Found - http://localhost/workspace/checkbox-filter-ajax/submit.php" what I did was changed the URL structure to point to submit.php, indeed it works. As I read some wordpress ajax ebook, I am convinced that your code is really working, it's just a matter of fine tuning.

    Again Thank you very much for this stuff, It really mean a lot to me.

  25. #75
    SitePoint Member
    Join Date
    Feb 2014
    Posts
    12
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    OK,

    So have played with this filter now for so many days, i have now almost got it working, i now just need to get the SQL working correctly, as i now have 2 table to query instead of 1. What i have is

    TABLE A
    ID
    Name
    CurrentLocation
    Locations
    Europe
    Asia
    MiddleEast
    NorthAmerica
    FirstProduct
    SecondProduct

    TABLE B
    USERID - This is equal to TableA.ID
    Category

    The table joins on TableA.ID an TableB.USERID

    So when i run my filter i use the following:

    Code:
    $Select = "SELECT ID, Name, CurrentLocation, Locations, Europe, Asia, MiddleEast, NorthAmerica, FirstProduct, SecondProduct";
    $From = " FROM TableA";
    $Where = " WHERE TRUE";
    
    $FilterOptions = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
    	
    	//	LOCATIONS
    	if(in_array("Asia", $FilterOptions))		{$Where .= " AND Asia = 1";}
    	if(in_array("Europe", $FilterOptions))		{$Where .= " AND Europe = 1";}
    	
    	//	NOTICE PERIOD
    	if(in_array("Immediate", $FilterOptions)){$Where .= " AND NoticePeriod = 'Immediate'";}
    	if(in_array("1 Week", $FilterOptions)){$Where .= " AND NoticePeriod = '1 Week'";}
    	if(in_array("1 Month", $FilterOptions)){$Where .= " AND NoticePeriod = '1 Month'";}
    	if(in_array("2 Months", $FilterOptions)){$Where .= " AND NoticePeriod = '2 Months'";}
    I need to join the above SQL to Table.B and need to filter. I have done the first part i think?

    I need the $FilterOptions which will include something similar to "Category_$CategoryID" for each category now and if selected filter the SQL upon that. So for instance:
    Code:
    if(in_array("Category_$CategoryID", $FilterOptions)){$Where .= " AND *** IM STUCK HERE***";}


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •