1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Search Form sub-category only populates after Submit and return to Form

Discussion in 'PHP' started by chrisj, Sep 18, 2016.

  1. #1
    With this basic Search Form when I bring up the page that has the Search Form and select Category, from the Search Form, my two choices show in the drop-down. When I select either one, and then select Sub-Category, that drop-down shows no choices (just "Sub-Category"). If I refresh the page, same result. But if I select "Submit" go to the results page, and then return to Search Form page, the Form works properly with all Categories and sub-categories available. If I refresh the page, the choices are still available. And, if I close the page, and then return, by retyping the url, no choices in sub-category again, until I submit and return. This same scenario in Chrome & IE. Any way to remedy this so, all choices are available without Submitting and returning first? Here's the code:

    <form method="get" action="../search.php" name="" />
    <input id="keyword" name="keyword" value="SEARCH WORDS" onfocus="if (this.value=='SEARCH WORDS') {this.value=''; this.style.color='#000000';}" onclick="clickclear(this, 'Enter Search Words')" onblur="clickrecall(this,'Enter Search Words')" value="" />
    <select size="1" name="channel" class="dropdown" />
    <option value="">SELECT</option>
    <option value="All">ALL</option>
    <option value="1">Channel1</option>
    <option value="2">Channel2</option>
    </select>
    <select size="1" name="sub_category" class="dropdown" />
    <option value="All">Sub-Category</option>
    </select>
    <input type="submit" value="VIEW"/>
    </td>
    </form>
    Code (markup):
    <script> $(document).ready(function() { $("select[name='channel']").change(function() { var channel_id = $(this).val(); console.log(channel_id); $("select[name='sub_category']").html("<option value='All'>Sub Category</option>"); $.ajax({ type: "POST", url: "../ajax.php", data: "channel_id="+channel_id, dataType: 'json', statusCode: { 200: function(data) { for(i = 0; i < data.length; i ++) { $("select[name='sub_category']").append("<option value='"+data["sub_channel_id"]+"'>"+data["sub_channel_name"]+"</option>"); } } } }); }); }); </script>

    You can see the Form in SearchForm1.png. In SearchForm2.png I select Channel1. In SearchForm3.png when I select Sub-Category it shows no choices, but after I select Submit(View) and return to this Form you can see from that I now have Sub-Category choices after selecting channel1 (SearchForm4.png).


    Any help will be appreciated.
     

    Attached Files:

    chrisj, Sep 18, 2016 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    That code is... Very bad, and it doesn't belong in the PHP category. Why aren't you just using $.post, and what's with the inline js? On my phone, so can't rewrite it now, but... And, why aren't you using ids on the selects instead of picking them by name-attribute? All of them should have an id to match labels to inputs. But then, you're missing labels as well, so...
     
    PoPSiCLe, Sep 19, 2016 IP
  3. mmerlinn

    mmerlinn Prominent Member

    Messages:
    3,197
    Likes Received:
    818
    Best Answers:
    7
    Trophy Points:
    320
    #3
    I can't see your code, so I can't pinpoint where the problem is. However, your code needs to populate your choices BEFORE you access the drop downs, so find out where the code allowing you to access the drop downs before the contents are loaded. One or more of several things is happening. First is your code even capable of populating the drop downs (This should be a yes considering that they properly populate after submission)? If it is, where is your code bypassing that process? Or is that part of your code even active when it should be active? Or is that part of your code choking on an error and therefore skipping the process?

    Add some break points in the code and examine what is happening and in what order. Or use a debugger and step through the code one line at a time to find out where things are getting out of kilter.
     
    mmerlinn, Sep 19, 2016 IP
  4. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #4
    Okay, first off, your HTML code has some serious issues. You're using XHTML closures, even when you're not meant to. Unless you're using XHTML, drop those (the /> on the ends).

    Try this, and see if it works:
    HTML:
    
    <form method="get" action="../search.php">
    <input id="keyword" name="keyword" placeholder="Search words">
    <select size="1" id="channel" name="channel" class="dropdown">
    <option value="" selected disabled>Select an option</option>
    <option value="all">All</option>
    <option value="1">Channel1</option>
    <option value="2">Channel2</option>
    </select>
    <select size="1" id="sub_category" name="sub_category" class="dropdown">
    <option value="all">Sub-Category</option>
    </select>
    <input type="submit" value="Select">
    </form>
    
    Code (markup):
    jQuery:
    
    $("#channel").change(function() {
       var channelID = $(this).val();
      console.log(channelID);
      $.post("../ajax.php", {channel_id:channelID}, function(data) {
         data = $.parseJSON(data);
         for(i = 0; i < data.length; i++) {
         $("#sub_category").append('<option value="'+data.sub_channel_id+'">'+data.sub_channel_name+'</option>');
      }
      });
    });
    
    Code (markup):
     
    PoPSiCLe, Sep 19, 2016 IP
  5. chrisj

    chrisj Well-Known Member

    Messages:
    606
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #5
    Thanks so much for your replies.
    I tried the code without success. Same result.
    Also, I'm not sure what you mean by "what's with the inline js"?
    Any other ideas will be appreciated.
     
    chrisj, Sep 19, 2016 IP
  6. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #6
    same result? Really? That makes no sense - it should effectively do what you want it to do on _change_ - not submit.
    I'm suspecting there is other issues with your (complete) code that might make this hard to work out.
    Also, with ajax-calls, it's always a bit hard to know what is being returned, if there are any errors, etc. Without actually seeing the page itself.

    As for the inline js, you have onfocus and onblur in the HTML - completely pointless garbage.
     
    PoPSiCLe, Sep 19, 2016 IP
  7. chrisj

    chrisj Well-Known Member

    Messages:
    606
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #7
    Thanks for your reply.

    If seeing the ajax.php code would help, here it is:

    
    <?php
    error_reporting(0);
    include_once (__DIR__.'/classes/config.php');
    include_once (__DIR__.'classes/sessions.php');
    
    if(isset($_POST["channel_id"]) && is_numeric($_POST["channel_id"])) {
        $sql = "SELECT sub_channel_id, sub_channel_name FROM sub_channels where parent_channel_id = ".$_POST["channel_id"]." ORDER BY sub_channel_name";
        $result = @mysql_query($sql);
        $response = array();
        while ($row = @mysql_fetch_array($result, MYSQL_ASSOC)) {
            $response[] = $row;
        }
        echo json_encode($response);
    }
    ?>
    Code (markup):
    Any additional help will be appreciated.
     
    chrisj, Sep 19, 2016 IP
  8. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #8
    Well, that should return something - the code is atrocious, but that's not the problem.

    Okay, I rewrote it a bit to test on my own server, and this works:
    
    <!DOCTYPE html>
    <html lang="no">
    <head>
    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    $("#channel").change(function() {
      var channelID = $(this).val();
      console.log(channelID);
      $.post("ajax.php", {channel_id:channelID}, function(data) {
      data = $.parseJSON(data);
      for(i = 0; i < data.length; i++) {
      $("#sub_category").append('<option value="'+data[i].sub_channel_id+'">'+data[i].sub_channel_name+'</option>');
      }
      });
    });
    
    })
    </script>
    </head>
    <body>
    <form method="get" action="../search.php">
    <input id="keyword" name="keyword" placeholder="Search words">
    <select size="1" id="channel" name="channel" class="dropdown">
    <option value="" selected disabled>Select an option</option>
    <option value="all">All</option>
    <option value="1">Channel1</option>
    <option value="2">Channel2</option>
    </select>
    <select size="1" id="sub_category" name="sub_category" class="dropdown">
    <option value="all">Sub-Category</option>
    </select>
    <input type="submit" value="Select">
    </form>
    </body>
    </html>
    
    Code (markup):
    That was the html - you will see that I've changed a few things, among them the script location for ajax.php, but that is minor stuff.

    I did just this on the ajax.php:
    
    <?php
    // error_reporting(0);
    // include_once (__DIR__.'/classes/config.php');
    // include_once (__DIR__.'classes/sessions.php');
    
    // if(isset($_POST["channel_id"]) && is_numeric($_POST["channel_id"])) {
    //  $sql = "SELECT sub_channel_id, sub_channel_name FROM sub_channels where parent_channel_id = ".$_POST["channel_id"]." ORDER BY sub_channel_name";
    //  $result = @mysql_query($sql);
    //  $response = array();
    //  while ($row = @mysql_fetch_array($result, MYSQL_ASSOC)) {
    //  $response[] = $row;
    //  }
    //  echo json_encode($response);
    // }
    if (isset($_POST['channel_id'])) {
       echo json_encode([0=>['sub_channel_id'=>1,'sub_channel_name'=>'Test 1'],1=>['sub_channel_id'=>2,'sub_channel_name'=>'Test 2']]);
    }
    ?>
    
    PHP:
    The reason I changed the data-bit in the javascript is that I'm sending back a multidimensional array - if that never happens, you can of course drop that bit.

    But the code works just fine, and populates the second dropdown on first dropdown change.
     
    PoPSiCLe, Sep 19, 2016 IP