title: get data from database using AJAX in codeigniter
body: <p>I'm trying to get data from my database to my view using ajax in codeigniter, but I can't get it working. I think something is going wrong with passing the grade_id to my model function.</p>
  
  <p><strong>AJAX:</strong></p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      $(document).ready(function(){    
          $('#grades').change(function(){          
              $("#classes &gt; option").remove(); 
              var grade_id = $('#grades').val();  
              $.ajax({
                  type: "POST",
                  url: "&lt;?php echo base_url(); ?&gt;index.php/login/get_classes/"+grade_id, 
                  data: {gradeid:grade_id},
                  success: function(classes) 
                  {
                      $.each(classes,function(id,name) 
                      {
                          var opt = $('&lt;option /&gt;'); 
                          opt.val(id);
                          opt.text(name);
                          $('#classes').append(opt); 
                      });
                  }        
              });
  
          });
      });
  &lt;/script&gt;
  </code></pre>
  
  <p><strong>CONTROLLER:</strong></p>
  
  <pre><code> function get_classes($gradeid)
  {
      $this-&gt;load-&gt;model('school_info_model');
      header('Content-type: application/json');
  
      if ($query = $this-&gt;school_info_model-&gt;get_all_classes($gradeid))
      {
          echo json_encode($query);
      } else {
          redirect('login/loginform');
      }
  
  }
  </code></pre>
  
  <p><strong>MODEL:</strong></p>
  
  <pre><code>function get_all_classes($gradeid)
  {
  
      $this-&gt;db-&gt;where('grade_id', $gradeid);
  
      $query = $this-&gt;db-&gt;get('classes');
  
      if($query-&gt;result()){
          $result = $query-&gt;result();
  
          foreach($result as $row)
          {
              $options[$row-&gt;id] = $row-&gt;name;
          }   
          return $options;
      } 
  }
  </code></pre>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I updated my code it is working now except for 2 things, I keep getting an error.</p>
  
  <p><strong>ERROR:</strong></p>
  
  <blockquote>
    <p>A PHP Error was encountered</p>
    
    <p>Severity: Warning</p>
    
    <p>Message: Invalid argument supplied for foreach()</p>
    
    <p>Filename: helpers/form_helper.php</p>
    
    <p>Line Number: 331</p>
  </blockquote>
  
  <p>And When I load the page for the first time the input field for classes is empty because it only activates the AJAX if the value of grades changes. </p>