简体   繁体   中英

Jquery show/hide div area on select

I'm trying to return a PHP array on a selection menu.

For example: User selects the gender inside the selection, now the JS should call a PHP class to return a array of items. And JS should add the values from the array to another selection menu.

In case the user selects another gender now, the PHP class should be called again.

<script type="text/javascript">
    $(document).ready(function(){
        $('#fds_gender').change(function () {
            if ($(this).val() == "stud") {
                <?php
                    require_once('../handling/fds_categorys.php');
                    $fds_stealer = new fds_categorys($user->username, 'stud');
                    $data = $fds_stealer->get_template_categories();
                ?>
            }else if($(this).val() == "babe") {
                <?php
                    require_once('../handling/fds_categorys.php');
                    $fds_stealer = new fds_categorys($user->username, 'babe');
                    $data = $fds_stealer->get_template_categories();
                ?>
            }
        });
    });
</script>

<div class="col-sm-6">
    <label>Categories</label>
    <select name="categorie" data-placeholder="Select a categorie..." class="select-icons">
        <?php foreach($data['categories'] as $categorie): ?>
            <?php echo '<option value="' . $categorie['name'] . '" data-icon="woman">' . $categorie['name'] . '</option>'; ?>
        <?php endforeach; ?>
    </select>
</div>

Sadly the selection only contains the else if response and would not change on another selection.

Does anyone have a idea what im doing wrong?

PHP runs on server-side, so requiring it inside a javascript if/else will only load stuff twice at startup. (If you check the source code, your if/else is empty)

That said you have 2 different approaches here.

First Approach

The server-side approach is loading everything at startup and assembling 2 javascript arrays with your different datasets.

   <?php
      require_once('../handling/fds_categorys.php');
      $fds_stealer = new fds_categorys($user->username, 'stud');
      $dataStud = array_map(
         function($el){
            return $el['name'];
         },
         $fds_stealer->get_template_categories()
      );
      $fds_stealer = new fds_categorys($user->username, 'babe');
      $dataBabe = array_map(
         function($el){
            return $el['name'];
         },
         $fds_stealer->get_template_categories()
      )
   ?>
   var dataStud = ["<?= implode('"', $dataStud) ?>"];
   var dataBabe = ["<?= implode('"', $dataBabe) ?>"];

Now you have 2 javascript arrays with your data. On change you would use jquery to assemble the options of your select.

Second Approach

Using Ajax to call a file which returns you the JSON array. It's a whole other world so you would have to research a little before I could give you any code about this. But basically you will have to have a .php in your server that gets parameters (either via $_GET or $_POST) and returns a JSON array. Call $.post or $.get in jQuery and in the callback function you would populate the options of your select. The $.get or $.post call would run everytime you change the select value.

You must understand -

<script type="text/javascript">
$(document).ready(function(){
    $('#fds_gender').change(function () {
        if ($(this).val() == "stud") {
            <?php
                require_once('../handling/fds_categorys.php');
                $fds_stealer = new fds_categorys($user->username, 'stud');
                $data = $fds_stealer->get_template_categories();
            ?>
        }else if($(this).val() == "babe") {
            <?php
                require_once('../handling/fds_categorys.php');
                $fds_stealer = new fds_categorys($user->username, 'babe');
                $data = $fds_stealer->get_template_categories();
            ?>
        }
    });
});

below PHP script will be excecuted on the server side and server dont care about the javascript and HTML So this will not work.

<?php
            require_once('../handling/fds_categorys.php');
            $fds_stealer = new fds_categorys($user->username, 'stud');
            $data = $fds_stealer->get_template_categories();
        ?>

Rather you should make a AJAX call from jquery for and then hide/show the div using jquery methods .hide() .show()

require_once('../handling/fds_categorys.php');
            $fds_stealer = new fds_categorys($user->username, 'stud');
            $data = $fds_stealer->get_template_categories();

That's because PHP is interpreted before the page even loads, while jQuery manipulates the DOM, after that is done.

Therefore, what you are doing will not work.

You could have the select tag be part of a form that makes a request to a PHP page on change, and have the PHP do the logic (like a standard MVC app) and return the values.

Then, with the returned values, manipulate them to render as you want them on the DOM.

You can assign php results into JS array and then convert it into select options.

var dataJson;

if ($(this).val() == "stud") {
        <?php
            require_once('../handling/fds_categorys.php');
            $fds_stealer = new fds_categorys($user->username, 'stud');
            $data = $fds_stealer->get_template_categories();
            echo 'dataJson = "'.json_encode($data).'"';
        ?>
}
//convert json array into JS array
var dataArray = JSON.parse(dataJson),
    options = '';
//iterate converted array to grab option names
for (var i = 0; i < dataArray.length; i++) {
    options += '<option>'+dataArray[i].name+'</option>';
}
//now populate dropdown with values
$(this).html(options);

For a start...

}else if($(this).val() == "babe") {

...looks wrong. Your if should be inside brackets.

Secondly, your require_once statement will be rendered twice, so this is clearly not what you intend.

You need to learn the order that your code will be processed, ie:

  1. Server side code (PHP)
  2. Client side code (Javascript/jQuery)

If you want to update your page without refreshing it, you will need to make an Ajax call from your client-side script to another PHP script on the server.

This link shows you one way to do it from jQuery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM