SitePoint Sponsor

User Tag List

Results 1 to 19 of 19
  1. #1
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    11
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Multiple slider range php and javascript

    Hello everyone!

    Well I have three sliders range but only one work and I would like to know how can I do to work with three sliders at the same time and in the same page.


    This is my code html for the slider range:

    Code:
    <p>
         <label for="hot" style="font-size: 18px;" >Hotel</label>
         <input type="text" name="preco" id="hot" style="color:#f6931f; font-size: 13px; font-weight:bold; width: 170px;">
    </p>
          <div id="slider-hotel" style="height: 10px;"></div>
    <hr/>
    <br/>
    <p>
         <label for="preco" style="font-size: 18px;">Preo</label>
         <input type="text" name="preco" id="precos" style="color:#f6931f; font-size: 13px; font-weight:bold; width: 100px;">
    </p>
          <div id="slider-preco" style="height: 10px; "></div>
    <hr/>
    <br/>
    <p>
         <label for="during" style="font-size: 18px;" >Duracao</label>
         <input type="text" name="preco" id="during" style="color:#f6931f; font-size: 13px; font-weight:bold; width: 150px;">
    </p>
          <div id="slider-duracao" style="height: 10px;"></div>
    
    This is my code to show the list of products:
    
    <div id="containerLista" style="margin-left: -10px;" data-hotel="<?php echo $hotel ?> data-duracao = "<?php echo $noite ?>
    	<div class="leftBox"  data-checkbox="<?php echo $idtema ?>">	
    		 <div id="left"> 			
    			<img src="/img/<?php echo $nomeImagem ?>" style="width: 250px; height: 183px; padding-left: 5px; padding-top: 5px; padding-right: 5px;"/>
                     </div>
    		 <div id="right" style="border-left: 2px solid #CFCFCF;">	
    			<h3><?php echo $titulo ?></h3>		
    			<div class="info_row" style="margin-top: 5px;">
                                   <span>Pas:</span>
                                            <?php echo utf8_encode($pais) ?>
                            </div>		
    			<div class="info_row" style="margin-top: 5px;">
                                       <span>Durao:</span><?php echo $dia . ' dias e ' ?><?php echo $noite . ' noites' ?>
                            </div>
    			<div class="info_row2">
       				    <span style="margin-top: 10px;">Preo</span>
                            </div>
    			<span class="vacationsDetails-header-buy">	
                                    <span class="price" itemprop="price" style="color: #EF4CC8; font-size: 1.7em; float: right; margin-top: 33px;"><?php echo $preco . '€' ?></span>	
    			        <span class="icon-perperson"></span>
    			</span>
    			<div class="vacationsDetails-included" style="margin-top:5px; padding-bottom: 0px; margin-bottom: 0px;"><br/><br/><br/><br/><br/>
    				<div>
    					<p class="vacationsDetails-header-buy Promocao" style="margin-top: -53px; height: 45px;">	
    						<a href="verOferta.php?idProduto=<?php echo $idProduto ?>" class="botaoPromocao" style="top: 7px; margin-right: 70px;font-size: 1.5em;">Comprar</a>																
                                             </p>
                                    </div>
                         </div>  
               </div>
     </div>
    </div>

    And the javascript code(the same with the other two sliders):


    Code:
    <script>
    	function showProducts(minPrice, maxPrice) {
    		$("div#containerLista").hide().filter(function() {
    			var price = parseInt($(this).data("duracao"), 10);
    			return price >= minPrice && price <= maxPrice;
    		}).show();
    	}
    	
    	 $( "#slider-duracao" ).slider({
    		range: true,
    		min: <?php echo $noiteMIN ?>,
    		max: <?php echo $noiteMAX ?>,
    		values: [<?php echo $noiteMIN ?>,<?php echo $noiteMAX ?>],
    		slide: function(event, ui){
    				var minDuracao= ui.values[0],
    					maxDuracao = ui.values[1];
    			$("#during").val(ui.values[0] + " Noites - " + ui.values[1] + " Noites");
    			showProducts(minDuracao,maxDuracao);
    		}									
    	});
    	$("#during").val($("#slider-duracao").slider("values",0) + " Noites - " + $("#slider-duracao").slider("values",1) + " Noites");									
    </script>
    I'm using this variables data-hotel="<?php echo $hotel ?> data-duracao = "<?php echo $noite ?> to filtering.

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    Can you post a link to a page where I can see this not working?

  3. #3
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    11
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

  4. #4
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    When you open the page and look at the console, there are a several missing js files (including jQuery):

    Code:
    GET http://viagenstriba.bonvoyage.pt/css/validationEngine.jquery.css 404 (Not Found) ferias.php:34
    GET http://viagenstriba.bonvoyage.pt/modernizr.min.js 404 (Not Found) ferias.php:47
    GET http://viagenstriba.bonvoyage.pt/js/jquery/jquery.js 404 (Not Found) ferias.php:48
    GET http://viagenstriba.bonvoyage.pt/js/jquery/jquery.hashchange.js 404 (Not Found) ferias.php:49
    GET http://viagenstriba.bonvoyage.pt/fe/site/resources/img/sprite.png?v20130301 404 (Not Found) jquery.tools.min.js:36
    You also have the following error:

    Code:
    Uncaught RangeError: Maximum call stack size exceeded %7Bmain,adsense,geometry,zombie%7D.js:11
    Try replacing the missing files and see if that helps.
    If not it would be great if you could describe your problem in a little more detail.
    Tell us what you expect to happen and what is actually happening.

  5. #5
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    11
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you Pullo to saw the several erros on my page.

    I cleaned the erros unless the last one because I don't know what it is.

    Well, if you saw the page I have three slider range but only one work.. At the moment, I let the last one of the slider range. When I moved the slider, I filter the list of the products depending the value on it. But I can do this if I work with the three sliders at the same time and my problem is that.

    How Can I filter the list of the products using the three sliders at the same time?

    Thanks

  6. #6
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    I just had a look at the page and your first two sliders are gone. The third one is working (which it wasn't yesterday).

    I'm sure this can be solved, but to make life a little easier, could you make a test page with only three sliders and the results (nothing else - no header, no images, no add, no footer etc).

    Let me know when you have done that and I'll have another look.

  7. #7
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    11
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Pullo,

    I make an example on jsFiddle to make much easier. And this example just can only work with one.

    http://jsfiddle.net/QQCsz/

    Like I said, I would like to work with the three at the same time.

  8. #8
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    So, I've had a chance to play around with this and I have come up with a suggestion of how you might do it.

    Demo.

    Code:
    <!DOCTYPE HTML>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Multiple sliders</title>
    
        <link rel='stylesheet' href='http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css' type='text/css' />
        <style>
          .ui-slider{
            position:relative;
            text-align:left
          }
    
          #sliderControlsContainer{
            width:300px;
            margin:15px;
            padding: 25px 25px 0 25px;
            float: left;
          }
    
          #sliderControlsContainer div{
            margin-bottom: 25px;
          }
    
          #sliderControlsContainer label{
            font-size: 18px;
            display: inline-block;
            width: 60px;
            text-align: right;
            padding-bottom: 15px;
          }
    
          #sliderControlsContainer input[type=text]{
            color:#f6931f; 
            font-size: 13px; 
            font-weight:bold; 
          }
    
          #hotels{
            float: left;
            width: 300px;
          }
    
          h3{
            margin-bottom: -10px;
          }
        </style>
      </head>
    
      <body>
        <div id="hotels">
          <div class="hotel" data-stars="5", data-stay="5", data-price="1000">
            <h3>Hotel de Posh</h3>
            <p>
              Stars: Five<br />
              Stay: 5 nights<br />
              Price: 1,000€
            </p>
          </div>
    
          <div class="hotel" data-stars="5", data-stay="5", data-price="900">
            <h3>The Ritz</h3>
            <p>
              Stars: Five<br />
              Stay: 5 nights<br />
              Price: 900€
            </p>
          </div>
    
          <div class="hotel" data-stars="4", data-stay="5", data-price="800">
            <h3>Hotel Maratim</h3>
            <p>
              Stars: Four<br />
              Stay: 5 nights<br />
              Price: 800€
            </p>
          </div>
    
          <div class="hotel" data-stars="4", data-stay="4", data-price="700">
            <h3>The Hilton</h3>
            <p>
              Stars: Four<br />
              Stay: 4 nights<br />
              Price: 700€
            </p>
          </div>
          
          <div class="hotel" data-stars="3", data-stay="4", data-price="600">
            <h3>Holiday Inn</h3>
            <p>
              Stars: Three<br />
              Stay: 4 nights<br />
              Price: 600€
            </p>
          </div>
          
          <div class="hotel" data-stars="3", data-stay="3", data-price="500">
            <h3>Bates Motel</h3>
            <p>
              Stars: Three<br />
              Stay: 3 nights<br />
              Price: 500€
            </p>
          </div>
          
          <div class="hotel" data-stars="2", data-stay="3", data-price="400">
            <h3>Happy Chef</h3>
            <p>
              Stars: Two<br />
              Stay: 3 nights<br />
              Price: 400€
            </p>
          </div>
          
          <div class="hotel" data-stars="2", data-stay="2", data-price="300">
            <h3>Hotel de Grimm</h3>
            <p>
              Stars: Two<br />
              Stay: 2 nights<br />
              Price: 300€
            </p>
          </div>
    
          <div class="hotel" data-stars="1", data-stay="5", data-price="200">
            <h3>Hotel Cheap n Easy</h3>
            <p>
              Stars: One<br />
              Stay: 5 nights<br />
              Price: 200€
            </p>
          </div>
          
          <div class="hotel" data-stars="1", data-stay="1", data-price="100">
            <h3>Joe's Dosshouse</h3>
            <p>
              Stars: One<br />
              Stay: 1 night<br />
              Price: 100€
            </p>
          </div>
      </div>
    
    
        <fieldset id="sliderControlsContainer">
          <legend>Refine your choice</legend>
    
          <div>
            <label for="stars">Estrelas</label>
            <input type="text" name="stars" id="stars" data-unit="stars"/>
            <div class="slider"></div>
          </div>
          
          <div>
            <label for="price">Preo</label>
            <input type="text" name="price" id="price" data-unit="Euros"/>
            <div class="slider" data-options='{"min": 100, "max": 1000, "values": [100, 1000], "step": 100}'></div>
          </div>
    
          <div>
            <label for="stay">Duracao</label>
            <input type="text" name="stay" id="stay" data-unit="nights"/>
            <div class="slider"></div>
          </div>
        </fieldset>
    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <script>
          function filterResults(sliderValues){
            var starsMin = sliderValues["stars"][0],
                starsMax = sliderValues["stars"][1],
                priceMin = sliderValues["price"][0],
                priceMax = sliderValues["price"][1],
                stayMin = sliderValues["stay"][0],
                stayMax = sliderValues["stay"][1];
    
            $hotels = $(".hotel").show();
    
            $hotels.each(function() {
              var stars = $(this).data("stars"),
                  price = $(this).data("price"),
                  stay = $(this).data("stay");
    
              if ( 
                  (stars >= starsMin && stars <= starsMax) && 
                  (price >= priceMin && price <= priceMax) &&
                  (stay >= stayMin && stay <= stayMax) 
                 ){
                $(this).show();
              } else {
                $(this).hide();
              }
    
            });
    
            $("#hotels").html($hotels);
          }
    
          function updateSliderInputs(){
            var allSliderValues = {};
    
            $(".slider").each(function(){
              var slider = $(this).prev().attr("id"),
                  currentSliderValues = $(this).slider("values"),
                  unit = $(this).prev().data("unit"),
                  newValue = currentSliderValues[0] + 
                             " - " + 
                             currentSliderValues[1] + 
                             " " + 
                             unit;
    
              allSliderValues[slider] = currentSliderValues;
              $(this).prev().val(newValue);
            });
    
            return allSliderValues;
          }
    
          function handleSliderChange(){
            var currentValues = updateSliderInputs();
            filterResults(currentValues);
          }
    
          $(".slider").each(function(){
            var defaultOpts = {
                  range: true,
                  min: 1,
                  max: 5,
                  values: [1, 5],
                  change: handleSliderChange
                }, 
                sliderOpts = $(this).data("options"),
                opts = $.extend(defaultOpts, sliderOpts);
    
            $(this).slider(opts);
          });
    
          updateSliderInputs();
        </script>
      </body>
    </html>
    To be honest however, this feels brittle and messy.
    It would be much better to store the hotels as records in a database and use AJAX to update your list.

  9. #9
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    11
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Pullo,

    I would like to thank you for helping me.
    Your demo works perfectly and like I want.

    I have a database to store the hotels, stars, prices, time etc... But I don't know how to work with AJAX yet.

    For me, is much simple that way but If you show me this example how to work with AJAX, I will see and try to understand.

    Thanks a lot

  10. #10
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Hi jonito,

    Sure I can show you how that would work.
    Could you post a dump of the relevant DB tables?

  11. #11
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    11
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Pullo,

    I think you want this,


    Code:
    CREATE TABLE IF NOT EXISTS `produto` (
      `idProduto` int(20) unsigned NOT NULL AUTO_INCREMENT,
      `titulo` varchar(250) NOT NULL,
      `preco` int(25) NOT NULL,
      `descricao` varchar(250) NOT NULL,
      `idimagem` int(20) unsigned NOT NULL,
      `dia` int(10) DEFAULT NULL,
      `noite` int(10) DEFAULT NULL,
      `hotel` int(10) DEFAULT NULL,
      `zonaGoogle` varchar(250) NOT NULL,
      `Promocao` varchar(200) NOT NULL,
      `dataFim` date DEFAULT NULL,
      `ofertaEspecial` int(20) DEFAULT NULL,
      `estado` varchar(200) DEFAULT NULL,
      PRIMARY KEY (`idProduto`),
      KEY `idimagem` (`idimagem`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=63 ;
    
    --
    -- Extraindo dados da tabela `produto`
    --
    
    INSERT INTO `produto` (`idProduto`, `titulo`, `preco`, `descricao`, `idimagem`, `dia`, `noite`, `hotel`, `zonaGoogle`, `Promocao`, `dataFim`, `ofertaEspecial`, `estado`) VALUES
    (1, 'A testar', 1, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>assim é que é</p>\r\n</body>\r\n</html>', 5, NULL, 0, NULL, '', '', '0000-00-00', NULL, NULL),
    (2, 'Brasil', 300, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>Sambá</p>\r\n</body>\r\n</html>', 13, NULL, 0, NULL, '', '', '0000-00-00', NULL, NULL),
    (3, 'Serra da estrela', 50, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>Férias em fam*lia</p>\r\n</body>\r\n</html>', 14, NULL, 0, NULL, '', '', '0000-00-00', NULL, NULL),
    (4, 'Alpes', 150, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>Passa as suas férias nos Alpes</p>\r\n</body>\r\n</html>', 15, NULL, 0, NULL, '', '', '0000-00-00', NULL, NULL),
    (5, 'A testar', 80, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>Estamos a testar um novo conteúdo.</p>\r\n</body>\r\n</html>', 22, NULL, 0, NULL, '', '', '0000-00-00', NULL, NULL),
    (6, 'Testing', 20, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>Estamos a testar um novo conteúdo.</p>\r\n</body>\r\n</html>', 23, NULL, 0, NULL, '', '', '0000-00-00', NULL, NULL),
    (7, 'Testing', 150, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>Vamos lá testar isto tudo</p>\r\n</body>\r\n</html>', 24, NULL, 0, NULL, '', '', '0000-00-00', NULL, NULL),
    (8, 'Novidade', 800, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>ndnffndslndgbaorbg+rgnrgndsjdklf</p>\r\n</body>\r\n</html>', 29, 5, 4, 5, '', '', '0000-00-00', NULL, NULL),
    (9, 'nouveauté', 500, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>gdsaertyuinm,lmjhvyuxxdcvgbhnj</p>\r\n</body>\r\n</html>', 30, 4, 3, 4, '', '', '0000-00-00', NULL, NULL),
    (10, 'Nouvelle', 200, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>çplokijuhygtfrde</p>\r\n</body>\r\n</html>', 31, 6, 5, 4, '', '', '0000-00-00', NULL, NULL),
    (11, 'Novo', 1000, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>çplokijuhygtfrdeswaq</p>\r\n</body>\r\n</html>', 32, 6, 5, 4, '', '', '0000-00-00', NULL, NULL),
    (12, 'Nueva', 180, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>zawsexdcrtfvgbyhunijmko</p>\r\n</body>\r\n</html>', 33, 3, 2, 3, '', '', '0000-00-00', NULL, NULL),
    (13, 'Vamos', 250, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>qwaszxerdfcvtyghbnuijkplç</p>\r\n</body>\r\n</html>', 34, 4, 3, 3, '', '', '0000-00-00', NULL, NULL),
    (14, 'Trabalha', 350, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>dshshfhewfhfdsfndbfdbfjbfjdsbfbfjqpojfqsamsbdlndasld</p>\r\n</body>\r\n</html>', 35, 4, 3, 4, '', '', '0000-00-00', NULL, NULL),
    (15, 'velho', 180, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>azwesxdcrtfgybhnjmko,pl</p>\r\n</body>\r\n</html>', 36, 5, 4, 4, '', '', '0000-00-00', NULL, NULL),
    (16, 'Mariparque', 600, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>azwsexdrctfvgybhunijmokplç</p>\r\n</body>\r\n</html>', 37, 6, 5, 5, '', '', '0000-00-00', NULL, NULL),
    (17, 'fazer o teste', 200, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>ertgyhuijko</p>\r\n</body>\r\n</html>', 38, 4, 3, 3, '', '', '0000-00-00', NULL, NULL),
    (18, 'badoca', 350, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>rrxclhgvcfz&lt;zxcvkjgdszxcvybhj</p>\r\n</body>\r\n</html>', 39, 6, 4, 4, '', '', '0000-00-00', NULL, NULL),
    (19, 'Boa', 450, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>&lt;zesxdcrtfvybuinop+</p>\r\n</body>\r\n</html>', 40, 6, 5, 5, '', '', '0000-00-00', NULL, NULL),
    (20, 'Espanha', 130, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>msqdenwifhbrhedomkojnwhbrfeindjw</p>\r\n</body>\r\n</html>', 41, 5, 4, 4, '', '', '0000-00-00', NULL, NULL),
    (21, 'Espanha', 350, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>dskdanlsjdbsajfbahvchboabjoaef</p>\r\n</body>\r\n</html>', 42, 6, 5, 4, '', '', '0000-00-00', NULL, NULL),
    (22, 'Mariparque', 350, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>vfcxsztyu,kreresrctyunm,</p>\r\n</body>\r\n</html>', 43, 4, 3, 4, '', '', '0000-00-00', NULL, NULL),
    (23, 'badoca', 210, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>mjinhbugvytfcdrxsexdrcfgvbhjnkm</p>\r\n</body>\r\n</html>', 44, 3, 2, 3, '', '', '0000-00-00', NULL, NULL),
    (24, 'dui', 400, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>mjnihbguvycftdrxszeawzesrxdctfvygbhuinj</p>\r\n</body>\r\n</html>', 45, 4, 3, 4, '', '', '0000-00-00', NULL, NULL),
    (25, 'tarde', 600, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>okmjinhubgyvftcdrxsewazesxdrctfvygbhunij</p>\r\n</body>\r\n</html>', 46, 6, 5, 3, '', '', '0000-00-00', NULL, NULL),
    (26, 'vazio', 10200, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>zsxdrctfgvybhinjmok</p>\r\n</body>\r\n</html>', 47, 5, 4, 1, '', '', '0000-00-00', NULL, NULL),
    (27, 'Novo teste', 450, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>zesrxdctfgvybhunijmokomjnugfdxs</p>\r\n</body>\r\n</html>', 48, 4, 3, 2, '', '', '0000-00-00', NULL, NULL),
    (28, 'Novamente a testar', 900, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>zaaesrdtyuinjihugvyctfdrxrxdctvygbh</p>\r\n</body>\r\n</html>', 49, 4, 3, 2, '', '', '0000-00-00', NULL, NULL),
    (29, 'testar novamente tudo', 1000, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>jinbhuvcdrsrdtygbhnjkl</p>\r\n</body>\r\n</html>', 50, 3, 2, 3, '', '', '0000-00-00', NULL, NULL),
    (30, 'vamos la testar', 345, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>bdsesrxctvybuinjojhgftdr</p>\r\n</body>\r\n</html>', 51, 2, 1, 5, '', '', '0000-00-00', NULL, NULL),
    (31, 'qwer', 123, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>kmonhgfvcdrsxerdtfvybuhj</p>\r\n</body>\r\n</html>', 52, 2, 1, 5, '', '', '0000-00-00', NULL, NULL),
    (32, 'qazxxxswed', 311, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>ibugvyctfdrxszerxdtfygbh</p>\r\n</body>\r\n</html>', 53, 3, 2, 5, '', '', '0000-00-00', NULL, NULL),
    (33, 'azsxdcfvgbnhjm', 100, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>aqwsdrtfgyhuo</p>\r\n</body>\r\n</html>', 54, 3, 2, 4, '', '', '0000-00-00', NULL, NULL),
    (34, 'çpolkiuytgfreds', 435, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>çployujhgfdsa</p>\r\n</body>\r\n</html>', 55, 2, 1, 5, '', '', '0000-00-00', NULL, NULL),
    (35, 'niuvyctdrxdctvyb', 150, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>jbgvytxzsrxtfgvbhnmk,lç</p>\r\n</body>\r\n</html>', 56, 3, 2, 4, '', '', '0000-00-00', NULL, NULL),
    (36, 'qawserfgtyhjki', 120, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>mjhuvycdaesdctfgvybhun</p>\r\n</body>\r\n</html>', 57, 4, 3, 4, '', '', '0000-00-00', NULL, NULL),
    (37, 'a testar novamente', 4321, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>jnihbugvyfctdrxszeawzesrxdctfvygbhuinjkmo</p>\r\n</body>\r\n</html>', 58, 4, 3, 3, '', '', '0000-00-00', NULL, NULL),
    (38, 'vamos la ver se trabalha', 1234, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>mkojinbhgvytfdcrxsezawesxdrctvgybhuinjmok</p>\r\n</body>\r\n</html>', 59, 4, 3, 4, '', '', '0000-00-00', NULL, NULL),
    (39, 'Portugal', 6543, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>*hgfcdrxszeaxcfghnhbgfvdcrsxdcfgvybhunj</p>\r\n</body>\r\n</html>', 60, 4, 3, 4, '', '', '0000-00-00', NULL, NULL),
    (40, 'Testing.......', 432, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>pkojinhbgvyctfdrsxzeawesrxcfvgbh</p>\r\n</body>\r\n</html>', 61, 4, 3, 3, '', '', '0000-00-00', NULL, NULL),
    (41, 'ahahahahh', 987, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>,mnbhgvfdrsxezdrxctfgbhuinjmok,l</p>\r\n</body>\r\n</html>', 62, 4, 3, 3, '', '', '0000-00-00', NULL, NULL),
    (42, 'polo', 124, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>kmjinbhgvfctdrxszea</p>\r\n</body>\r\n</html>', 63, 4, 3, 5, '', '', '0000-00-00', NULL, NULL),
    (43, 'mais uma vez', 345, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>hbgyfvctdrxesesxdrtfgvyuijko</p>\r\n</body>\r\n</html>', 64, 5, 4, 4, '', '', '0000-00-00', NULL, NULL),
    (44, 'mais uma vez dois', 654, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>kjhbguvytrxeszxdvbhuinjmk</p>\r\n</body>\r\n</html>', 65, 5, 4, 3, '', '', '0000-00-00', NULL, NULL),
    (45, 'outra vez', 654, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>bhgvyctdrserxctvybhnjm</p>\r\n</body>\r\n</html>', 66, 6, 5, 4, '', '', '0000-00-00', NULL, NULL),
    (46, 'again', 765, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>mnbvyctrszrxtybhunjm</p>\r\n</body>\r\n</html>', 67, 5, 4, 4, '', '', '0000-00-00', NULL, NULL),
    (47, 'encore une foi', 876, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>oibhgvfctdswrtfyghj</p>\r\n</body>\r\n</html>', 68, 5, 4, 2, '', '', '0000-00-00', NULL, NULL),
    (48, 'Em fase de teste', 987, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>qwertyuioplkjhgfdsazxcvbnm</p>\r\n</body>\r\n</html>', 69, 5, 4, 4, '', '', '0000-00-00', NULL, NULL),
    (49, 'Lisboa', 150, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>Um fim de semana romântico para Lisboa na qual será poss*vel desfrutar de uma vista fenomenal</p>\r\n</body>\r\n</html>', 79, 5, 4, 4, 'Lisboa', '', '0000-00-00', NULL, NULL),
    (50, 'Porto', 90, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>A descuberta da cidade do Porto</p>\r\n</body>\r\n</html>', 80, 6, 5, 4, 'Porto', '', '0000-00-00', NULL, NULL),
    (51, 'Braga', 100, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>Uma cidade nunca antes vista</p>\r\n</body>\r\n</html>', 81, 6, 5, 5, 'Braga', '', '0000-00-00', NULL, NULL),
    (52, 'Leiria', 300, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>Uma excelente cidade</p>\r\n</body>\r\n</html>', 82, 5, 4, 4, 'Leiria', '', '0000-00-00', NULL, NULL),
    (53, 'France', 250, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>França</p>\r\n</body>\r\n</html>', 83, 6, 5, 4, 'França', '', '0000-00-00', NULL, NULL),
    (54, 'Guimaraes', 100, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>vamos la testar isto</p>\r\n</body>\r\n</html>', 84, 6, 5, 3, 'Guimaraes', '', '0000-00-00', NULL, NULL),
    (55, 'Faro', 200, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>teste</p>\r\n</body>\r\n</html>', 85, 6, 5, 3, 'Faro', '', '0000-00-00', NULL, NULL),
    (56, 'Santarem', 200, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>santarem</p>\r\n</body>\r\n</html>', 86, 6, 5, 1, 'Santarem', 'sim', '0000-00-00', 0, 'ativo'),
    (57, 'Coimbra', 40, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>Cidade maravilha</p>\r\n</body>\r\n</html>', 87, 5, 4, 4, 'Coimbra', '', '0000-00-00', NULL, NULL),
    (58, 'Londres', 200, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>outra vez a testar</p>\r\n</body>\r\n</html>', 89, 5, 4, 4, 'Londres', 'sim', '2014-01-17', 30, 'ativo'),
    (59, 'Estados Unidos', 100, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>Um dos grandes pa*ses do mundo na qula podemos ver grandes cidades tais como Las Vegas, Nova Iorque, Washington</p>\r\n</body>\r\n</html>', 90, 3, 2, 1, 'New York', 'sim', '0000-00-00', 0, 'ativo'),
    (60, 'Italia', 300, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>itália</p>\r\n</body>\r\n</html>', 91, 3, 2, 4, 'Florença', 'sim', '0000-00-00', NULL, 'ativo'),
    (61, 'teste', 123, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>dasdssdadad</p>\r\n</body>\r\n</html>', 92, 5, 4, 4, 'teste', 'sim', '0000-00-00', 0, 'ativo'),
    (62, 'teste', 123, '<!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n<p>ererewrerew</p>\r\n</body>\r\n</html>', 93, 5, 4, 4, 'teste', 'sim', '0000-00-00', 0, 'ativo');
    
    --
    -- Constraints for dumped tables
    --
    
    --
    -- Limitadores para a tabela `produto`
    --
    ALTER TABLE `produto`
      ADD CONSTRAINT `produto_ibfk_1` FOREIGN KEY (`idimagem`) REFERENCES `imagem` (`idImagem`) ON UPDATE CASCADE;
    Last edited by Pullo; Jan 19, 2014 at 07:15. Reason: Added code tags

  12. #12
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Hello,

    I decided to create a new hotel table for this demo, just to keep things a little simpler:

    Code:
    CREATE TABLE hotels (
      id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(256),
      stars INT,
      price INT,
      nights INT
    ) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;
    Add some data:

    Code:
    INSERT INTO TABLE hotel (name, stars, price, nights) VALUES(
        ("Hotel de Posh", 5, 1000, 1),
        ("The Ritz", 5, 999, 5),
        ("Hotel Maratim", 5, 950, 5),
        ("The Hilton", 5, 900, 5),
        ("Holiday Inn", 5, 900, 5),
        ("Bates Motel", 4, 899, 4),
        ("Happy Chef", 4, 850, 4),
        ("Hotel de Grimm", 4, 750, 4),
        ("Hotel Cheap n Easy", 4, 799, 4),
        ("Joe's Dosshouse", 4, 701, 2),
        ("Trump Plaza", 3, 699, 5),
        ("Hotel Bender", 3, 650, 5),
        ("Mo's Guesthouse", 3, 600, 3),
        ("ABC Hotel", 3, 500, 5),
        ("Hotel de Sitepoint", 3, 550, 2),
        ("Hotel Moscow", 2, 599, 5),
        ("Crossroads Motel", 2, 400, 5),
        ("Hotel de Ville", 2, 450, 4),
        ("Hotel de Pays", 2, 300, 5),
        ("Hotel de Hotel", 2, 350, 2),
        ("Disney's All-Star Resort", 1, 399, 5),
        ("Luxor", 1, 299, 5),
        ("The Mirage", 1, 250, 3),
        ("Oasis Beach Hotel", 1, 199, 3),
        ("Sheraton", 1, 150, 3)
    );
    Then we set up the sliders in the same way as before, creating a div "hotels", which we will fill with, well, hotels.

    Code:
    <div id="hotels"></div>
    
    <fieldset id="sliderControlsContainer">
      <legend>Refine your choice</legend>
    
      <div>
        <label for="stars">Estrelas</label>
        <input type="text" name="stars" id="stars" data-unit="stars"/>
        <div class="slider"></div>
      </div>
      
      <div>
        <label for="price">Preo</label>
        <input type="text" name="price" id="price" data-unit="Euros"/>
        <div class="slider" data-options='{"min": 100, "max": 1000, "values": [100, 1000], "step": 100}'></div>
      </div>
    
      <div>
        <label for="nights">Duracao</label>
        <input type="text" name="nights" id="nights" data-unit="nights"/>
        <div class="slider"></div>
      </div>
    </fieldset>
    The sliders get initialized as before:

    Code:
    function handleSliderChange(){
      updateSliderInputs();
      getHotels();
    }
    
    $(".slider").each(function(){
      var defaultOpts = {
            range: true,
            min: 1,
            max: 5,
            values: [1, 5],
            change: handleSliderChange
          }, 
          sliderOpts = $(this).data("options"),
          opts = $.extend(defaultOpts, sliderOpts);
    
      $(this).slider(opts);
    });
    When a slider value changes, now two things happen: the inputs are updated as before and we contact the server to get a list of hotels which match the currently selected criteria.

    Updating the inputs is the same as before:

    Code:
    function updateSliderInputs(){
      var allSliderValues = {};
    
      $(".slider").each(function(){
        var slider = $(this).prev().attr("id"),
            currentSliderValues = $(this).slider("values"),
            unit = $(this).prev().data("unit"),
            newValue = currentSliderValues[0] + 
                       " - " + 
                       currentSliderValues[1] + 
                       " " + 
                       unit;
    
        allSliderValues[slider] = currentSliderValues;
        $(this).prev().val(newValue);
      });
    
      return allSliderValues;
    }
    The getHotels() method is where the AJAX happends:

    Code:
    function getHotels(){
      $.ajax({
        type: "POST",
        url: "submit.php",
        cache: false,
        data: {sliderValues: getSliderValues()},
        success: function(data){
          $('#hotels').html(data);
        }
      });
    }
    This will send a POST request to a script entitled submit.php, which is expected to be in the same directory.
    This also calls the method getSliderValues() to get all of the values currently selected and pass them to the PHP script:

    Code:
    function getSliderValues(){
      var sliderValues = {};
    
      $(".slider").each(function(){
        var slider = $(this).prev().attr("id"),
            value = $(this).slider("values");
    
        sliderValues[slider] = value;
      });
    
      return sliderValues;
    }
    In submit PHP we connect to the database, then use placeholders to build our query:

    Code:
    $pdo = new PDO('mysql:host=localhost;dbname=sitepoint', 'root', '****');
    
    $select = 'SELECT *';
    $from = ' FROM hotel';
    $where = ' WHERE (stars BETWEEN :starsMin AND :starsMax) AND';
    $where .= ' (price BETWEEN :priceMin AND :priceMax) AND';
    $where .= ' (nights BETWEEN :nightsMin AND :nightsMax)';
    After that fish all of the necessary variables out of $_POST:

    Code:
    $starsMin = $_POST["sliderValues"]["stars"][0];
    $starsMax = $_POST["sliderValues"]["stars"][1];
    $priceMin = $_POST["sliderValues"]["price"][0];
    $priceMax = $_POST["sliderValues"]["price"][1];
    $nightsMin = $_POST["sliderValues"]["nights"][0];
    $nightsMax = $_POST["sliderValues"]["nights"][1];
    Then bind them to our query and execute:

    Code:
    $sql = $select . $from . $where;
    $statement = $pdo -> prepare($sql);
    $statement -> bindParam(':starsMin', $starsMin, PDO::PARAM_INT);
    $statement -> bindParam(':starsMax', $starsMax, PDO::PARAM_INT);
    $statement -> bindParam(':priceMin', $priceMin, PDO::PARAM_INT);
    $statement -> bindParam(':priceMax', $priceMax, PDO::PARAM_INT);
    $statement -> bindParam(':nightsMin', $nightsMin, PDO::PARAM_INT);
    $statement -> bindParam(':nightsMax', $nightsMax, PDO::PARAM_INT);
    $statement -> execute();
    $hotels = $statement -> fetchAll(PDO::FETCH_ASSOC);
    This will give us a bunch of hotel records, which we need to iterate over and construct a lump of HTML to return to the JS:

    Code:
    $retVal = "";
    
    foreach ($hotels as $hotel) {
      $retVal .= "<p>";
      $retVal .= "Name: " . $hotel["name"] . "<br />";
      $retVal .= "Stars: " . $hotel["stars"] . "<br />";
      $retVal .= "Price: " . $hotel["price"] . "<br />";
      $retVal .= "Nights: " . $hotel["nights"];
      $retVal .= "</p>";
    }
    
    echo($retVal);
    Back in the JS, we specify a success callback, which will be executed when the AJAX request returns successfully:

    Code:
    success: function(data){
      $('#hotels').html(data);
    }
    The variable data will hold whatever the server echoed back to us (in this case some HTML) which we can then insert into the hotels div.

    And that's it

    Here's the complete code:

    index.html

    Code:
    <!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>AJAX Sliders</title>
        <link rel='stylesheet' href='http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css' type='text/css' />
        <style>
          .ui-slider{
            position:relative;
            text-align:left
          }
    
          #sliderControlsContainer{
            width:300px;
            margin:15px;
            padding: 25px 25px 0 25px;
            float: left;
          }
    
          #sliderControlsContainer div{
            margin-bottom: 25px;
          }
    
          #sliderControlsContainer label{
            font-size: 18px;
            display: inline-block;
            width: 60px;
            text-align: right;
            padding-bottom: 15px;
          }
    
          #sliderControlsContainer input[type=text]{
            color:#f6931f; 
            font-size: 13px; 
            font-weight:bold; 
          }
    
          #hotels{
            float: left;
            width: 300px;
          }
    
          h3{
            margin-bottom: -10px;
          }
        </style>
      </head>
    
      <body> 
        <div id="hotels"></div>
    
        <fieldset id="sliderControlsContainer">
          <legend>Refine your choice</legend>
    
          <div>
            <label for="stars">Estrelas</label>
            <input type="text" name="stars" id="stars" data-unit="stars"/>
            <div class="slider"></div>
          </div>
          
          <div>
            <label for="price">Preo</label>
            <input type="text" name="price" id="price" data-unit="Euros"/>
            <div class="slider" data-options='{"min": 100, "max": 1000, "values": [100, 1000], "step": 100}'></div>
          </div>
    
          <div>
            <label for="nights">Duracao</label>
            <input type="text" name="nights" id="nights" data-unit="nights"/>
            <div class="slider"></div>
          </div>
        </fieldset>
    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <script>
          function getSliderValues(){
            var sliderValues = {};
    
            $(".slider").each(function(){
              var slider = $(this).prev().attr("id"),
                  value = $(this).slider("values");
    
              sliderValues[slider] = value;
            });
    
            return sliderValues;
          }
    
          function updateSliderInputs(){
            var allSliderValues = {};
    
            $(".slider").each(function(){
              var slider = $(this).prev().attr("id"),
                  currentSliderValues = $(this).slider("values"),
                  unit = $(this).prev().data("unit"),
                  newValue = currentSliderValues[0] + 
                             " - " + 
                             currentSliderValues[1] + 
                             " " + 
                             unit;
    
              allSliderValues[slider] = currentSliderValues;
              $(this).prev().val(newValue);
            });
    
            return allSliderValues;
          }   
    
          function getHotels(){
            $.ajax({
              type: "POST",
              url: "submit.php",
              cache: false,
              data: {sliderValues: getSliderValues()},
              success: function(data){
                $('#hotels').html(data);
              }
            });
          }
    
          function handleSliderChange(){
            updateSliderInputs();
            getHotels();
          }
    
          $(".slider").each(function(){
            var defaultOpts = {
                  range: true,
                  min: 1,
                  max: 5,
                  values: [1, 5],
                  change: handleSliderChange
                }, 
                sliderOpts = $(this).data("options"),
                opts = $.extend(defaultOpts, sliderOpts);
    
            $(this).slider(opts);
          });
    
          handleSliderChange();
        </script> 
      </body> 
    </html>
    submit.php

    Code:
    <?php 
      $pdo = new PDO('mysql:host=localhost;dbname=sitepoint', 'root', '****');
     
      $select = 'SELECT *';
      $from = ' FROM hotel';
      $where = ' WHERE (stars BETWEEN :starsMin AND :starsMax) AND';
      $where .= ' (price BETWEEN :priceMin AND :priceMax) AND';
      $where .= ' (nights BETWEEN :nightsMin AND :nightsMax)';
    
      $starsMin = $_POST["sliderValues"]["stars"][0];
      $starsMax = $_POST["sliderValues"]["stars"][1];
      $priceMin = $_POST["sliderValues"]["price"][0];
      $priceMax = $_POST["sliderValues"]["price"][1];
      $nightsMin = $_POST["sliderValues"]["nights"][0];
      $nightsMax = $_POST["sliderValues"]["nights"][1];
      
      $sql = $select . $from . $where;
      $statement = $pdo -> prepare($sql);
      $statement -> bindParam(':starsMin', $starsMin, PDO::PARAM_INT);
      $statement -> bindParam(':starsMax', $starsMax, PDO::PARAM_INT);
      $statement -> bindParam(':priceMin', $priceMin, PDO::PARAM_INT);
      $statement -> bindParam(':priceMax', $priceMax, PDO::PARAM_INT);
      $statement -> bindParam(':nightsMin', $nightsMin, PDO::PARAM_INT);
      $statement -> bindParam(':nightsMax', $nightsMax, PDO::PARAM_INT);
      $statement -> execute();
      $hotels = $statement -> fetchAll(PDO::FETCH_ASSOC);
    
      $retVal = "";
    
      foreach ($hotels as $hotel) {
        $retVal .= "<p>";
        $retVal .= "Name: " . $hotel["name"] . "<br />";
        $retVal .= "Stars: " . $hotel["stars"] . "<br />";
        $retVal .= "Price: " . $hotel["price"] . "<br />";
        $retVal .= "Nights: " . $hotel["nights"];
        $retVal .= "</p>";
      }
    
      echo($retVal);
    ?>
    Hope that helps.

  13. #13
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    11
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Pullo,

    Well, I put the first example into my website but didn't work because I have a lot of errors when I move my sliders like: Object has no method slider.
    I have the script at the same order but nothings happen.

    Thank you for posting an example with AJAX. It's a little more complicated but essencial to understand how it works

  14. #14
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    11
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It's possible to join search box, checkbox, sliders and radio buttons in AJAX?
    If you saw my website, I have the fourth and I have some querys to filtering. My radio buttons and my search box works fine but I would like to know how I can combine all the filters.
    I show you my querys to filtering:

    Code:
    $pesquisar = $_POST['search'];
    	    $etiqueta = $_GET["etiqueta"];							
    	    $radio = $_POST['zona'];
    	    switch ($radio){
    			case 'Europa' : $result = "SELECT p.idProduto,p.titulo,p.descricao,p.preco,p.dia,p.noite,p.hotel,t.idTema,e.nome,i.nome,pa.nome
    												FROM produto as p
    												LEFT JOIN produtoetiqueta as pe on p.idProduto = pe.idProduto
    	   										        LEFT JOIN paises as pa on pa.iso = pe.idpaises
    												LEFT JOIN etiqueta as e on pe.idEtiqueta = e.idEtiqueta
    												LEFT JOIN imagem as i on p.idimagem = i.idImagem
    												LEFT JOIN tema as t on pe.idtema = t.idTema
    												WHERE pe.idpaises NOT LIKE 'PT' AND e.nome = ? AND p.titulo LIKE '%$pesquisar%'
    												ORDER BY p.preco ASC
    												LIMIT $start, $per_page  "; 
    				                                                                break;
    			case 'Portugal' :   $result = "SELECT p.idProduto,p.titulo,p.descricao,p.preco,p.dia,p.noite,p.hotel,t.idTema,e.nome,i.nome,pa.nome
    														FROM produto as p
    														LEFT JOIN produtoetiqueta as pe on p.idProduto = pe.idProduto
    														LEFT JOIN paises as pa on pa.iso = pe.idpaises
    														LEFT JOIN etiqueta as e on pe.idEtiqueta = e.idEtiqueta
    														LEFT JOIN tema as t on pe.idtema = t.idTema
    														LEFT JOIN imagem as i on p.idimagem = i.idImagem
    														WHERE pe.idpaises LIKE 'PT' AND e.nome = ? AND p.titulo LIKE '%$pesquisar%'
    														ORDER BY p.preco ASC
    														LIMIT $start, $per_page"; 
    	                                                                                                          break;
    			case Null:	$result = "SELECT p.idProduto,p.titulo,p.descricao,p.preco,p.dia,p.noite,p.hotel,t.idTema,e.nome,i.nome,pa.nome
    									FROM produto as p
    									LEFT JOIN produtoetiqueta as pe on p.idProduto = pe.idProduto
    									LEFT JOIN etiqueta as e on pe.idEtiqueta = e.idEtiqueta
    									LEFT JOIN tema as t on pe.idtema = t.idTema
    									LEFT JOIN imagem as i on p.idimagem = i.idImagem
    									LEFT JOIN paises as pa on pa.iso = pe.idpaises
    									WHERE e.nome = ? AND p.titulo LIKE '%$pesquisar%'
    									ORDER BY p.preco ASC
    									LIMIT $start, $per_page";
    									break;				 
    												
    											}
    										}
    Last edited by Pullo; Jan 22, 2014 at 04:46. Reason: Added code tags

  15. #15
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Basically, as demonstrated, you just use AJAX to send the relevant values of your form elements to your server-side script every time the values of one of the form elements changes.
    You then build your query based on whatever values you have received.

    I would also avoid these lengthy switch statements and build up the WHERE part of the request as in my previous example.
    For a checkbox, it might look like this (untested):

    Code:
    $continent = $_POST("continent");
    
    $select = 'SELECT *';
    $from = ' FROM hotel';
    $where = ' WHERE (stars BETWEEN :starsMin AND :starsMax) AND';
    $where .= ' (price BETWEEN :priceMin AND :priceMax) AND';
    $where .= ' (nights BETWEEN :nightsMin AND :nightsMax) AND';
    $where .= 'continent LIKE :continent';
    ...
    $statement -> bindParam(':continent', $nightsMax, PDO::PARAM_STR);
    $statement -> execute();
    HTH

  16. #16
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    11
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Pullo,

    Thanks for helping me but I have a problem now.
    I put checkbox with the sliders. When I select a checkbox, show me the data list correctly but when I'm starting to move the slider, the data list "restart".
    I will show you what I'm done and I would like to know how can I do to use the sliders and the checkbox at the same time.

    Submit.php

    Code:
    $pdo = new PDO('mysql:host=localhost;dbname=sitepoint', 'root', '******');
     
      $select = 'SELECT *';
      $from = ' FROM produto as p ';
      $where = ' WHERE (hotel BETWEEN :starsMin AND :starsMax) AND';
      $where .= ' (price BETWEEN :priceMin AND :priceMax) AND';
      $where .= ' (nightsBETWEEN :nightsMin AND :nightsMax)';
    
      $starsMin = $_POST["sliderValues"]["stars"][0];
      $starsMax = $_POST["sliderValues"]["stars"][1];
      $priceMin = $_POST["sliderValues"]["price"][0];
      $priceMax = $_POST["sliderValues"]["price"][1];
      $nightsMin = $_POST["sliderValues"]["nights"][0];
      $nightsMax = $_POST["sliderValues"]["nights"][1];
      $opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
      
      var_dump($_POST['filterOpts']);
      
      if (in_array("test", $opts)){
    	$where .= " AND theme= 'test'";
    	} 
    	if (in_array("mountain", $opts)){
    	$where .= " AND theme= 'mountain'";
    	} 
    	if (in_array("fun", $opts)){
    	$where .= " AND theme= 'fun'";
    	} 
      
      $sql = $select . $from . $where;
      $statement = $pdo -> prepare($sql);
      $statement -> bindParam(':starsMin', $starsMin, PDO::PARAM_INT);
      $statement -> bindParam(':starsMax', $starsMax, PDO::PARAM_INT);
      $statement -> bindParam(':priceMin', $priceMin, PDO::PARAM_INT);
      $statement -> bindParam(':priceMax', $priceMax, PDO::PARAM_INT);
      $statement -> bindParam(':nightsMin', $nightsMin, PDO::PARAM_INT);
      $statement -> bindParam(':nightsMax', $nightsMax, PDO::PARAM_INT);
      $statement -> execute();
    
      $retVal = "";
    
      while ($teste = $statement->fetch(PDO::FETCH_BOUND)) {
    	
        $retVal .= "<p>";
        $retVal .= "Name: " .$teste["title"] . "<br />";
        $retVal .= "Stars: " . $teste["price"] . "<br />";
        $retVal .= "Price: " . $teste["nights"] . "<br />";
        $retVal .= "Nights: " . $teste["hotel"] . "<br />";
        $retVal .= "Theme: " . $teste["theme"];
        $retVal .= "</p>";
      }
    
      echo($retVal);
    ?>
    index.html

    Code:
    <!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>AJAX Sliders</title>
        <link rel='stylesheet' href='http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css' type='text/css' />
        <style>
          .ui-slider{
            position:relative;
            text-align:left
          }
    
          #sliderControlsContainer{
            width:300px;
            margin:15px;
            padding: 25px 25px 0 25px;
            float: left;
          }
    
          #sliderControlsContainer div{
            margin-bottom: 25px;
          }
    
          #sliderControlsContainer label{
            font-size: 18px;
            display: inline-block;
            width: 60px;
            text-align: right;
            padding-bottom: 15px;
          }
    
          #sliderControlsContainer input[type=text]{
            color:#f6931f; 
            font-size: 13px; 
            font-weight:bold; 
          }
    
          #hotels{
            float: left;
            width: 300px;
          }
    
          h3{
            margin-bottom: -10px;
          }
        </style>
      </head>
    
      <body> 
        <div id="hotels"></div>
    
        <fieldset id="sliderControlsContainer">
          <legend>Refine your choice</legend>
    
          <div>
            <label for="stars">Estrelas</label>
            <input type="text" name="stars" id="stars" data-unit="stars"/>
            <div class="slider"></div>
          </div>
          
          <div>
            <label for="price">Preo</label>
            <input type="text" name="price" id="price" data-unit="Euros"/>
            <div class="slider" data-options='{"min": 100, "max": 1000, "values": [100, 1000], "step": 100}'></div>
          </div>
    
          <div>
            <label for="nights">Duracao</label>
            <input type="text" name="nights" id="nights" data-unit="nights"/>
            <div class="slider"></div>
          </div>
    	  
    	  
    		<div>
            <label for="check">Teste</label>
            <input type="checkbox" name="teste" id="check"/>
    		</div>
    		
    		<div>
            <label for="check">Montanha</label>
            <input type="checkbox" name="montanha" id="check"/>
    		</div>
    		
    		<div>
            <label for="check">Divertimento</label>
            <input type="checkbox" name="divertimento" id="check"/>
    		</div>
    	  
    	  
        </fieldset>
    	
    	
    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <script>
          function getSliderValues(){
            var sliderValues = {};
    
            $(".slider").each(function(){
              var slider = $(this).prev().attr("id"),
                  value = $(this).slider("values");
    
              sliderValues[slider] = value;
            });
    
            return sliderValues;
          }
    	  
    	  //Here I add the new lines to getcheckbox
    	  function getHotelsFilterOptions(){
    			var options = [];
    			$checkboxes.each(function(){
    			if(this.checked){
    				options.push(this.name);
    				}
    			});
    			return options;
    		}
    	  
    		var $checkboxes = $("input:checkbox");
    		  $checkboxes.on("change", function(){
    		  var options = getHotelsFilterOptions();
    		  getHotels(options);
    		});
    
          function updateSliderInputs(){
            var allSliderValues = {};
    
            $(".slider").each(function(){
              var slider = $(this).prev().attr("id"),
                  currentSliderValues = $(this).slider("values"),
                  unit = $(this).prev().data("unit"),
                  newValue = currentSliderValues[0] + 
                             " - " + 
                             currentSliderValues[1] + 
                             " " + 
                             unit;
    
              allSliderValues[slider] = currentSliderValues;
              $(this).prev().val(newValue);
            });
    
            return allSliderValues;
          }  
    	  
          //And I add into this method
          function getHotels(options){
            $.ajax({
              type: "POST",
              url: "submit.php",
              cache: false,
              data: {sliderValues: getSliderValues(),
    				 filterOpts: options},
              success: function(data){
                $('#hotels').html(data);
              }
            });
          }
    	  
    	  
          function handleSliderChange(){
            updateSliderInputs();
            getHotels();
          }
    
    
          $(".slider").each(function(){
            var defaultOpts = {
                  range: true,
                  min: 1,
                  max: 5,
                  values: [1, 5],
                  change: handleSliderChange
                }, 
                sliderOpts = $(this).data("options"),
                opts = $.extend(defaultOpts, sliderOpts);
    
            $(this).slider(opts);
          });
    	  
          handleSliderChange();
        </script> 
      </body> 
    </html>

    Thanks
    Last edited by Pullo; Jan 23, 2014 at 10:52. Reason: Added code tags

  17. #17
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    It should be possible.

    Can you tell me what it is exactly that these checkboxes should do?

  18. #18
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    11
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Pullo,

    Well, like you saw, I'm building a filters and I need checkbox, radio buttons and sliders to do this.

    The checkbox has the same purpose.
    Filter the theme of the product list like mountain, snow, sun, have fun and more.....
    The slider just has the price, nights and hotel
    And I would like do to the same to filtering the countries but with radio buttons. I have just two countries: Europe and Portugal.

    And I would like to join this entire filters and works everything at the same time.

    this is my page test....http://viagenstriba.bonvoyage.pt/teste2.php
    I think it's easiler if you saw directly.

    Thanks Pullo

  19. #19
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Ok, well here's how I would expand my example to incorporate checkboxes.

    Create the table anewm with a country column:

    Code:
    CREATE TABLE IF NOT EXISTS `hotels` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(256) DEFAULT NULL,
      `stars` int(11) DEFAULT NULL,
      `price` int(11) DEFAULT NULL,
      `nights` int(11) DEFAULT NULL,
      `country` varchar(256) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
    Add data:

    Code:
    INSERT INTO `hotels` (`id`, `name`, `stars`, `price`, `nights`, `country`) VALUES
    (1, 'Hotel de Posh', 5, 1000, 1, 'EN'),
    (2, 'The Ritz', 5, 999, 5, 'DE'),
    (3, 'Hotel Maratim', 5, 950, 5, 'EN'),
    (4, 'The Hilton', 5, 900, 5, 'EN'),
    (5, 'Holiday Inn', 5, 900, 5, 'DE'),
    (6, 'Bates Motel', 4, 899, 4, 'EN'),
    (7, 'Happy Chef', 4, 850, 4, 'DE'),
    (8, 'Hotel de Grimm', 4, 750, 4, 'DE'),
    (9, 'Hotel Cheap n Easy', 4, 799, 4, 'EN'),
    (10, 'Joe''s Dosshouse', 4, 701, 2, 'EN'),
    (11, 'Trump Plaza', 3, 699, 5, 'DE'),
    (12, 'Hotel Bender', 3, 650, 5, 'DE'),
    (13, 'Mo''s Guesthouse', 3, 600, 3, 'EN'),
    (14, 'ABC Hotel', 3, 500, 5, 'DE'),
    (15, 'Hotel de Sitepoint', 3, 550, 2, 'EN'),
    (16, 'Hotel Moscow', 2, 599, 5, 'DE'),
    (17, 'Crossroads Motel', 2, 400, 5, 'EN'),
    (18, 'Hotel de Ville', 2, 450, 4, 'EN'),
    (19, 'Hotel de Pays', 2, 300, 5, 'DE'),
    (20, 'Hotel de Hotel', 2, 350, 2, 'DE'),
    (21, 'Disney''s All-Star Resort', 1, 399, 5, 'EN'),
    (22, 'Luxor', 1, 299, 5, 'DE'),
    (23, 'The Mirage', 1, 250, 3, 'EN'),
    (24, 'Oasis Beach Hotel', 1, 199, 3, 'EN'),
    (25, 'Sheraton', 1, 150, 3, 'DE');
    Add checkboxes:

    Code:
    <div>
      <label class="cb"><input type="checkbox" name="EN" checked/> England</label>
      <label class="cb"><input type="checkbox" name="DE" checked/> Germany</label>
    </div>
    Then I renamed handleSliderChange to handleFilterOptsChange, as we are now dealing with more than sliders.

    Add an event handler to the checkboxes:

    Code:
    $("input:checkbox").on("change", function(){
      handleFilterOptsChange();
    });
    Then change the parameter being passed to the PHP script into data: {filterOpts: getFilterOpts()}

    Update the filter method to include the ceckboxes:

    Code:
    function getFilterOpts(){
      var filterOpts = {},
          countries = [];
    
      $(".slider").each(function(){
        var slider = $(this).prev().attr("id"),
            value = $(this).slider("values");
    
        filterOpts[slider] = value;
      });
    
      $("input:checkbox:checked").each(function(){
        countries.push(this.name);
      })
      filterOpts["countries"] = countries;
    
      return filterOpts;
    }
    In the PHP script we then get a reference to the countries:

    Code:
    $countries = $_POST["filterOpts"]["countries"];
    Then use the REGEXP operator to construct the query.
    This will make it easy to add more checkboxes in the future:

    Code:
    $regex = [];
    
    if(in_array("EN", $countries)){
      array_push($regex, "EN");
    }
    
    if(in_array("DE", $countries)){
      array_push($regex, "DE");
    }
    
    $regex = implode("|", $regex);
    $where .= " country REGEXP '" . $regex . "'";
    More about REGEXP here: http://www.tutorialspoint.com/mysql/mysql-regexps.htm

    And that's it. We can now filter our results set via country.

    DEMO

    index.html

    Code:
    <!DOCTYPE HTML>
    <html>
      <head>
        <!-- http://www.sitepoint.com/forums/showthread.php?1187119-Multiple-slider-range-php-and-javascript -->
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>AJAX Sliders</title>
        <link rel='stylesheet' href='http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css' type='text/css' />
        <style>
          .ui-slider{
            position:relative;
            text-align:left
          }
    
          #sliderControlsContainer{
            width:300px;
            margin:15px;
            padding: 25px 25px 0 25px;
            float: left;
          }
    
          #sliderControlsContainer div{
            margin-bottom: 25px;
          }
    
          #sliderControlsContainer label{
            font-size: 16px;
            display: inline-block;
            width: 60px;
            text-align: right;
          }
    
          #sliderControlsContainer label.cb{
            display: inline-block;
            width: 100px;
            text-align: left;
          }
    
          #sliderControlsContainer input[type=text]{
            color:#f6931f; 
            font-size: 13px; 
            font-weight:bold; 
          }
    
          #hotels{
            float: left;
            width: 300px;
          }
    
          h3{
            margin-bottom: -10px;
          }
        </style>
      </head>
    
      <body> 
        <div id="hotels"></div>
        
        <fieldset id="sliderControlsContainer">
          <legend>Refine your choice</legend>
    
          <div>
            <label for="stars">Estrelas</label>
            <input type="text" name="stars" id="stars" data-unit="stars"/>
            <div class="slider"></div>
          </div>
          
          <div>
            <label for="price">Preo</label>
            <input type="text" name="price" id="price" data-unit="Euros"/>
            <div class="slider" data-options='{"min": 100, "max": 1000, "values": [100, 1000], "step": 100}'></div>
          </div>
    
          <div>
            <label for="nights">Duracao</label>
            <input type="text" name="nights" id="nights" data-unit="nights"/>
            <div class="slider"></div>
          </div>
    
          <div>
            <label class="cb"><input type="checkbox" name="EN" checked/> England</label>
            <label class="cb"><input type="checkbox" name="DE" checked/> Germany</label>
          </div>
        </fieldset>
    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <script>
          function getFilterOpts(){
            var filterOpts = {},
                countries = [];
    
            $(".slider").each(function(){
              var slider = $(this).prev().attr("id"),
                  value = $(this).slider("values");
    
              filterOpts[slider] = value;
            });
    
            $("input:checkbox:checked").each(function(){
              countries.push(this.name);
            })
            filterOpts["countries"] = countries;
    
            return filterOpts;
          }
    
          function updateSliderInputs(){
            var allSliderValues = {};
    
            $(".slider").each(function(){
              var slider = $(this).prev().attr("id"),
                  currentSliderValues = $(this).slider("values"),
                  unit = $(this).prev().data("unit"),
                  newValue = currentSliderValues[0] + 
                             " - " + 
                             currentSliderValues[1] + 
                             " " + 
                             unit;
    
              allSliderValues[slider] = currentSliderValues;
              $(this).prev().val(newValue);
            });
    
            return allSliderValues;
          }   
    
          function getHotels(){
            $.ajax({
              type: "POST",
              url: "submit.php",
              cache: false,
              data: {filterOpts: getFilterOpts()},
              success: function(data){
                $('#hotels').html(data);
              }
            });
          }
    
          function handleFilterOptsChange(){
            updateSliderInputs();
            getHotels();
          }
    
          $(".slider").each(function(){
            var defaultOpts = {
                  range: true,
                  min: 1,
                  max: 5,
                  values: [1, 5],
                  change: handleFilterOptsChange
                }, 
                sliderOpts = $(this).data("options"),
                opts = $.extend(defaultOpts, sliderOpts);
    
            $(this).slider(opts);
          });
    
          $("input:checkbox").on("change", function(){
            handleFilterOptsChange();
          });
    
          handleFilterOptsChange();
        </script> 
      </body> 
    </html>
    submit.php

    Code:
    <?php 
      $pdo = new PDO('mysql:host=localhost;dbname=sitepoint', 'root', '****');
    
      $select = 'SELECT *';
      $from = ' FROM hotels';
      $where = ' WHERE (stars BETWEEN :starsMin AND :starsMax) AND';
      $where .= ' (price BETWEEN :priceMin AND :priceMax) AND';
      $where .= ' (nights BETWEEN :nightsMin AND :nightsMax) AND';
    
      $starsMin = $_POST["filterOpts"]["stars"][0];
      $starsMax = $_POST["filterOpts"]["stars"][1];
      $priceMin = $_POST["filterOpts"]["price"][0];
      $priceMax = $_POST["filterOpts"]["price"][1];
      $nightsMin = $_POST["filterOpts"]["nights"][0];
      $nightsMax = $_POST["filterOpts"]["nights"][1];
      $countries = $_POST["filterOpts"]["countries"];
      $regex = [];
    
      if(in_array("EN", $countries)){
        array_push($regex, "EN");
      }
    
      if(in_array("DE", $countries)){
        array_push($regex, "DE");
      }
    
      $regex = implode("|", $regex);
      $where .= " country REGEXP '" . $regex . "'";
    
      $sql = $select . $from . $where;
      $statement = $pdo -> prepare($sql);
      $statement -> bindParam(':starsMin', $starsMin, PDO::PARAM_INT);
      $statement -> bindParam(':starsMax', $starsMax, PDO::PARAM_INT);
      $statement -> bindParam(':priceMin', $priceMin, PDO::PARAM_INT);
      $statement -> bindParam(':priceMax', $priceMax, PDO::PARAM_INT);
      $statement -> bindParam(':nightsMin', $nightsMin, PDO::PARAM_INT);
      $statement -> bindParam(':nightsMax', $nightsMax, PDO::PARAM_INT);
      $statement -> execute();
      $hotels = $statement -> fetchAll(PDO::FETCH_ASSOC);
    
      $retVal = "";
    
      foreach ($hotels as $hotel) {
        $retVal .= "<p>";
        $retVal .= "Name: " . $hotel["name"] . "<br />";
        $retVal .= "Country: " . $hotel["country"] . "<br />";
        $retVal .= "Stars: " . $hotel["stars"] . "<br />";
        $retVal .= "Price: " . $hotel["price"] . "<br />";
        $retVal .= "Nights: " . $hotel["nights"];
        $retVal .= "</p>";
      }
    
      echo($retVal);
    ?>


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
  •