Problem with select for PHP MYSQL JQuery price filter

0

I have a form which contains a select , to be able to filter by higher or lower price, when I select an option if it performs filtering, the problem is that the select never changes the option always stays in the first option.

I think it has to do something with the selected= "selected" attribute, I've tried it in the following way but it has not worked, and I've even tried to put .atrr('selected', true) from JQuery , but when I try this does not respect the instruction $("#search_form").submit();

Another thing for the front use materializecss

------------------- HTML -----------------

      <form method="get" id="search_form"><!--Formulario para filtros-->

      <select name="prices" id="price">
      <option value="ASC"<?php
      if (isset($_GET['prices'])
       && $_GET['prices'] == 'ASC') {
      $selected = ' selected="selected"';
      }
       ?> <?php $selected?>>ASC</option>

      <option value="DESC"<?php
      if (isset($_GET['prices'])
       && $_GET['prices'] == 'DESC') {
     $selected = ' selected="selected"';
      }
      ?> <?php $selected?>>DESC</option>

      </select>

       <label>Ordena Por:</label>

-------------------- JQuery -------------------------- --------

     $('select#price').change(function(){

      $("#search_form").submit();
       return false;  



       });

------------------ PHP ---------------------------- ------------

      if(isset($_GET['prices']) && $_GET['prices']!="") :

       if($_GET['prices']=='ASC'):

       $sql .= " ORDER BY precio ASC";   


       elseif($_GET['prices']=='DESC'):

       $sql .=" ORDER BY precio DESC";


        endif;   

       endif;
    
asked by Eduardo Sinaloa 07.07.2018 в 00:32
source

1 answer

1

Although your problem can be solved by adding a simple echo , it is good that you learn to develop more readable code, using the best practices. For example, you do not need to mix HTML code with PHP. You can generate all your HTML by saving it in an output variable.

Another good practice is indentation. Although HTML is a string, it is always good to carry the indentation as if you were writing regular HTML. In your case it is a simple form, but when the content is more extensive, that will help you not to make mistakes. Here is an example:

<?php
  $HTML = '<form method="get" id="search_form">
              <select name="prices" id="price">
                  <option value="ASC"';
  if (isset($_GET['prices']) && $_GET['prices'] == 'ASC') {
       $HTML .= ' selected="selected"';
  }
  $HTML .=        '>ASC</option>
                  <option value="DESC"';
  if (isset($_GET['prices']) && $_GET['prices'] == 'DESC') {
      $HTML .= ' selected="selected"';
  }
  $HTML .=       '>DESC</option>
              </select>
              <label>Ordena Por:</label>
          </form>';
  echo $HTML;
?>
    
answered by 07.07.2018 в 01:57