Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 1 of 1
  1. #1
    Master Coder
    Join Date
    Apr 2003
    Location
    in my house
    Posts
    5,215
    Thanks
    39
    Thanked 201 Times in 197 Posts

    post data issues with ajax request

    Hi,
    New to ajax/javascript/php - perl MySQL is my usual.

    I'm clicking checkboxes to submit the name and value in 'post' to a php script that will query the db and send back the response data in json format.

    The default response - that which is given on first pageload, is a full query of the product catalogue.

    The checkboxes will limit the data returned for example, limiting the results to a specific brand or product category etc.


    Please help me to be sure the post data is being sent and sent correctly when I check a checkbox and whether my method in the php script is the correct way to process the post string. (I can probably work out the porcessing part once I am sure the post string is as I have anticipated.


    Here is the product_catalogue_display (calling) script
    Code:
    <div id="filter" style='width:300px;float:left'>
    
      <h2>Filter options</h2>
      <div class='menu_divs'>
        <input type="checkbox" name="product_category" value="Kitchen Equipment"/>
        <label for="Kitchen Equipment">Kitchen Equipment</label>
      </div>
      <div class='menu_divs'>
        <input type="checkbox" name="product_category"  value="Shoes"/>
        <label for="Shoes">Shoes</label>
      </div>
    
    
      <div class='menu_divs'>
        <input type="checkbox" name="brand_name" value="Kenwood" />
        <label for="Kenwood">Kenwood</label>
      </div>
      <div class='menu_divs'>
        <input type="checkbox" name="brand_name" value="Oxo">
        <label for="Oxo">Oxo</label>
      </div>
     <div class='menu_divs'>
        <input type="checkbox" name="brand_name" value="Brabantia">
        <label for="Brabantia">Brabantia</label>
      </div>
     <div class='menu_divs'>
        <input type="checkbox" name="brand_name" value="Gaby">
        <label for="Gaby">Gaby</label>
      </div>
     <div class='menu_divs'>
        <input type="checkbox" name="brand_name" value="Felicity Fox">
        <label for="Felicity Fox">Felicity Fox</label>
      </div>
      <div class='menu_divs'>
        <input type="checkbox" name='size' value="1.7">
        <label for="1.7">1.7</label>
      </div>
      <div class='menu_divs'>
        <input type="checkbox" name='made_from' value="stainless steel">
        <label for="stainless steel">Stainless Steel</label>
      </div>
    </div>
    
     <div>
    
    
    </div> 
    
     <table id="product_catalogue">
          <thead>
            <tr>
              <th width="15">ID</th>
              <th>Brand</th>
              <th>Category</th>
              <th>Size</th>
              <th>Size units</th>
              <th>Colour</th>
              <th>Colour code</th>
              <th>Dimensions</th>
              <th>Dimensions units</th>
              <th>Capacity</th>
              <th>Capacity units</th>          
              <th>Price type</th>
              <th>Price</th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
    
    
      <div id="debug"></div>
        <script src="https://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==='brand' )
                    {
                    v = "<a href='content.php?id=" + currRecord['id'] +"'>" + v + "</a>";
                    }
                    else if ( k==='size' )
                    {
                    v = "<span class='price'>" + v + "</span>";
                    }
                    else
                    {
                    v= "<span class='something_else'>" + v + "</span>";
                    }
    
                tbl_row += "<td>"+v+"</td>";
                })
    
                tbl_body += "<tr>"+tbl_row+"</tr>";
            })
    
        return tbl_body;
        }
     
    
    
    
        function getCatalogueFilterOptions()
        {
        var opts = [];
       
    
            \$checkboxes.each(function()
            {
                if(this.checked)
                {
                opts = {
                name: 'value'  /*I want to pass the name and value data in the 'post' string*/
                };
                }
            });
     
        return opts;
        }
     
    
    
        function updateCatalogue(opts)
        {
        var obj = \$.extend({}, opts); /* convert the array to an object */
    
            \$.ajax(
            {
            type: "POST",
            url: "/php-queries/product-catalogue-query.php",
            
            dataType : 'json',
            cache: false,
            data: \$('#filter').serializeArray() + '&' + \$.param(obj), /* merge your form with the new obj (your array) */
    
              success: function(records)
              {
              //alert('SUCCESS!');
              \$('#product_catalogue tbody').html(makeTable(records));
              }
    
            });
        }
        
    
      
        var \$checkboxes = \$("input:checkbox");
        \$checkboxes.on("change", function()
        {
        var opts = getCatalogueFilterOptions();
        updateCatalogue(opts);
        });
        
    
        \$checkboxes.trigger("change");
       
        </script> 
    );
    and this is the product_catalogue_query.php processing/returning script
    Code:
    try {
        $conn = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
        
        // set the PDO error mode to exception
        //$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
      
        $opts = $_POST['filterOpts'];
      
    
      $post = file_get_contents( 'php://input' );
      
      
      $filterOptions = explode( '&', $post);
      
    
    
    // loop through the post string to put each item into a specific array 
    // eg, product+category, brand, size etc 
    $filterParams= array();
    $product_categories = array();
    $brand_names = array();
    $sizes = array();
    
    
    
      foreach( $filterOptions as $k => $v ) 
      {
      $data = explode("=", $v);
     
      
      $data[1] = str_replace("+", " ", "$data[1]");
    
    
          if ( in_array( $data[0], $filterParams ) ) 
          {
          }
          else
          { 
          array_push( $filterParams, $data[0]);
          }
    
          if ( $data[0] === 'product_category' )
          {
    
     
              if ( in_array( $data[1], $product_categories ) )
              {
              }
              else
              {
              array_push( $product_categories, $data[1] );
              }
          }
    
    
          if ( $data[0] === 'brand_name' )
          {
    
              if ( in_array(  $data[1], $brand_names ) )
              {
              }
              else
              {
              array_push( $brand_names, $data[1] );
              }
    
           }
          
    
           
          if ( $data[0] === 'size' )
          {
    
              if ( in_array(  $data[1], $sizes ) )
              {
              }
              else
              {
              array_push( $sizes, $data[1] );
              }
    
           }
      }
    
    
     
    
      
     
    
     
        $select = 'select rpc.id as catalogue_id
                        , rpc.brand as brand
                        , rpc2.category as category
                        , rpd.size as size
                        , rpd.size_units as size_units
                        , rpd.colour as colour
                        , rpd.colour_code as colour_code
                        , rpd.dimensions as dimensions
                        , rpd.dimensions_units as dimensions_units
                        , rpd.capacity as capacity
                        , rpd.capacity_units as capacity_units 
                        , rpcp.price_type as price_type
                        , rpcp.price as price
                  ';
        $from = ' FROM retailers_product_catalogue as rpc 
               left outer 
                  join retailers_product_category as rpc2 
                    on rpc2.catalogue_id = rpc.id 
               left   
                  join retailers_product_colours as rpd 
                    on rpd.catalogue_id = rpc.id 
               left  
                  join retailers_product_catalogue_prices as rpcp
                    on rpcp.catalogue_id = rpc.id  
                  '; 
    
    
    
      
    
    
        $full_query_where = ' WHERE true';
        $filtered_query_where = ' where true ';
    
    
    
      // if the product_category was passed in (it is compulsory)
      if ( count( $product_categories ) > 0 )
      {
      $filtered_query_where .= ' rpc2.category in ' . "('" . implode( "','" , $product_categories ) . "')";
      } 
    
    
      
    
    
      if ( count($brand_names) > 0 ) 
      {  
      $filtered_query_where .= ' and rpc.brand in ' . "('" . implode( "','" , $brand_names ) . "')";
      };
    
    
         
      if ( count( $sizes ) > 0)
      {
      $filtered_query_where .= ' and ( rpd.size in ' . "('" . implode( "','" , $sizes ) . "')" . ")" ; 
      } 
    
       
      if ( count( $capacities ) > 0)
      {
      $filtered_query_where .= ' and ( rpd.capacity in ' . "('" . implode( "','" , $capacities ) . "')" . ")" ; 
      } 
      
    
         
      if ( count( $colours ) > 0)
      {
      $filtered_query_where .= ' and ( rpd.colour in ' . "('" . implode( "','" , $colours ) . "')" . ")" ; 
      } 
    
    
         
      if ( count( $dimensions ) > 0)
      {
      $filtered_query_where .= ' and ( rpd.dimensions in ' . "('" . implode( "','" , $dimensions ) . "')" . ")" ; 
      } 
    
    
      if ( count( $sizes ) > 0)
      {
      $filtered_query_where .= ' and ( rpd.size in ' . "('" . implode( "','" , $sizes ) . "')" . ")" ; 
      } 
    
    
    
        
       
    
    
    
    
       
    
      // get the filtered dataset
        $filtered_sql = $select . $from . $filtered_query_where;
        $filtered_statement = $conn->prepare($filtered_sql);
        $filtered_statement->execute();
        $filtered_results = $filtered_statement->fetchAll(PDO::FETCH_ASSOC);
    
    
    
    
    
        
      
    
      $debugInfo = array('debug' => vsprintf(str_replace("?", "%s", $filtered_statement->queryString), $post ));
      $filtered_results = array_merge($debugInfo, $filtered_results);
    
    
     
      $filtered_results_json = json_encode($filtered_results);
      echo( $filtered_results_json ); 
      
    
    
       
    
        }
        catch(PDOException $e)
        {
        echo "Error: " . $e->getMessage();
        }
    
    
    $conn = null;
    I'd appreciate any tips as well on how to output the post string received by the product_catalogue_query.php script - I mean, so I can what it looks ahead of the db query.
    Last edited by bazz; Dec 16th, 2018 at 04:08 AM.
    "The day you stop learning is the day you become obsolete"! - my late Dad.

    Why do some people say "I don't know for sure"? If they don't know for sure then, they don't know!
    Useful MySQL resource
    Useful MySQL link


 

Tags for this Thread

Posting Permissions

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