1

I have this dynamic dropdown which fetches result on selection of one select menu, but the challenge I am facing after it auto populates the results on the second dropdown on submit of form the value of second select disappears. How to make it not disappear even after submit?

Here is my HTML & PHP

 <div class="row form-group">
                    <div class="col-md-12">
                    <label class="sr-only" for="job_category">Select Job Category</label>
            <select name="job_category" id="category" class='form-control'>
            <option value='' selected='selected' disabled='disabled'>Select Job Category</option>
            <?php           
            $sql="select * from job_category ";             
            foreach ($db->query($sql) as $row) {
            ?>
            <option value='<?php echo $row[cat_id]; ?>' <?php if($job_category == ''.$row[cat_id].'') echo 'selected="selected"'; ?>><?php echo $row[cat_name]; ?></option>
            <?php   
            }
            ?>          
            </select>
            </div>
        </div>

                <div class='row form-group'>
                    <div class='col-md-12'>
                    <label class='sr-only' for='job_subcategory'>Select Job Industry</label>
                <select name='job_subcategory' id='sub-category' class='form-control'>
                <option value='' selected='selected' disabled='disabled'>Select Job Industry</option>
                </select>
                </div>
            </div>  

Here is my JQ

$(document).ready(function() {
    $('#category').change(function(){
        var cat_id=$('#category').val();
        $('#sub-category').empty(); 
        $.get('fetchCategories.php',{'cat_id':cat_id},function(return_data){            
        $.each(return_data.data, function(key,value){
                $("#sub-category").append("<option value='" + value.subcat_id +"'>"+value.subcat_name+"</option>");
            });

        }, "json");
        });
    });

And my fetchCategories.php

@$cat_id=$_GET['cat_id'];
//$cat_id=2;
/// Preventing injection attack //// 
if(!is_numeric($cat_id)){
echo "Data Error";
exit;
 }
/// end of checking injection attack ////
require "includes/config.php";

$sql="select subcat_name,subcat_id from job_subcategory where cat_id='$cat_id'";
$row=$db->prepare($sql);
$row->execute();
$result=$row->fetchAll(PDO::FETCH_ASSOC);

$main = array('data'=>$result);
echo json_encode($main);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Sherline
  • 53
  • 6
  • on page load you can create one function which will call your php where you have written your select code and show the same using ajax or use localStorage ? – Swati May 31 '20 at 07:27
  • Hi, @Swati can you guys help me out here? really need this favor i am unable to understand how i could. – Sherline May 31 '20 at 14:19
  • @Dharman thanks i will take care of it. could you help me out with my current situation? – Sherline May 31 '20 at 14:19

1 Answers1

1

You can use localStorage to store the current value which is selected by user on change of select-box and then when your page gets reload just fetch the stored data from localStorage and then call your ajax to retrieve required data.

Your jquery code will somewhat look like below (Sorry for any syntax error) :

$(document).ready(function() {
  //check if there is any value in localStorage
  if (localStorage.getItem("save") != null) {
    //get that value
    var value = localStorage.getItem("save");
    console.log(value);
    //set value in selected box
    $("#sub-category").val(value);
  }
  //onchange of subcategory
  $('#sub-category').change(function() {
    var values = $(this).val();
    localStorage.clear(); //clear previous data
    localStorage.setItem("save", values); //add data to storage

  });


  $('#category').change(function() {
    var cat_id = $('#category').val();
    $('#sub-category').empty();
    $.get('fetchCategories.php', {
      'cat_id': cat_id
    }, function(return_data) {
      $.each(return_data.data, function(key, value) {
        $("#sub-category").append("<option value='" + value.subcat_id + "'>" + value.subcat_name + "</option>");
      });

    }, "json");
  });

}); 
Swati
  • 28,069
  • 4
  • 21
  • 41
  • What doesn't work? Did you got any error? Select-box doesn't got populated ? – Swati May 31 '20 at 15:08
  • Swati once a value from category if selected then sub category results show and after i select a record from subcategory and hit submit then only category value remains selected sub category selected data disappears – Sherline May 31 '20 at 15:10
  • Ohh I misunderstood your question .. I thought you need to show select-box again .. so you need to show selected value in your select-box ? Also when you refresh the select box is still there but the selected value disappear? am I right? – Swati May 31 '20 at 15:13
  • Yes that was what i was talking about selected value in subcategory remains selected :) – Sherline May 31 '20 at 15:15
  • Disappears on submit :) I heartily appreciate you being patient with me. – Sherline May 31 '20 at 15:27
  • i added selected='selected' attr but then the selected result do not change $("#sub-category").append(""); – Sherline May 31 '20 at 15:36
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/215037/discussion-between-swati-and-sherline). – Swati May 31 '20 at 15:59
  • still disappear on submit :D – Sherline Jun 01 '20 at 12:04