CodeIgniter Forums

Full Version: ajax call to On success to select option
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi,
to get the view page with given below two select options , i used the following code.
how to get Selected option value  to sending with ajax ?
For second select option designation, cadre_id takes null value. how to pass selected option value here?

Can any one pls help me to solve this? 

[attachment=1361]


////////////ajax part////////////////

 $('select[name="dept_no"]').on('change', function() {
            var dept_no_ID = $(this).val();
            if(dept_no_ID) {
                $.ajax({
                    url:"<?php echo site_url('index.php/clerkAE/get_selected_dept_attached_post')?>/"+dept_no_ID,
                    type: "GET",
                    dataType: "json",
                    
                    success: function(data)
                    {
    $('#cadre_id').html('<option value="-1">-- Select Designation --</option>');

        $.each(data, function(i, data){
        $('#cadre_id').append("<option value='"+data.id+"'>"+data.designation+" / "+data.grade+"</option>");
        });
                    }
          
                });
            }else{
                $('select[name="cadre_id"]').empty();
            }
        });


/////////////controller/////////////
 public function get_selected_dept_attached_post($dept_no)
        {
           $userid=$this->session->userdata('id');
           $this->load->model('Model_user');
           $data = $this->Model_user->dept_attached_post($dept_no,$userid);
           echo json_encode($data);     
        }

/////////////model/////////////////
public function dept_attached_post($dept_no,$userid){
            
$query = $this->db->query("SELECT c.id,c.designation,c.grade 
FROM cadre c, dept_has_cadre dhc, assign_dept a_d 
WHERE c.id=dhc.cadre_id 
AND dhc.dept_id=".$dept_no." 
AND dhc.dept_id=a_d.dept_id
AND a_d.user_id=".$userid."
AND dhc.year = (SELECT MAX( YEAR ) max_year FROM dept_has_cadre ) ");  

 echo '<pre>', print_r($this->db->last_query(), true), '</pre>';
    echo '<pre>', print_r($this->db->error(), true), '</pre>';
    echo '<pre>', print_r($query->result(), true), '</pre>';
    
return $query->result(); 

/////////////view page ///////////

<div class="form-group"> <label class="col-sm-2 control-label"> Dept/Unit/Branch</label> 
    <div class="col-xs-4"> 
               
        <label><select name="dept_no" id="dept_no" class="form-control">
<option value="-1"> --- Select Dept/Unit/Branch --- </option>
         
        <?php foreach($information_assign_dept as $row) { ?>   
                      
        <option value="<?php echo $row->id; ?>" ><?php 
                 
                                         if ($row->faculty_id != 0){
                                         echo $row->dept_name. ' / '.$row->faculty_name;                                      
                                        
                                         }
                                         else{
                                           echo $row->dept_name;                                        
                                         }?>
        </option>
           
            <?php } ?>
        </select><span class="help-block"></span></label>         
    </div>
</div>


<div class="form-group"> 
    <label class="col-sm-2 control-label"> Designation </label> 
    <div class="col-xs-3"> 
        <label><select class="form-control" id="cadre_id" name="cadre_id">
            <option value="-1">--- Select Designation ---</option>
        </select><span class="help-block"></span></label>
    
    </div> 
  
    <label class="col-sm-2 control-label">Present Salary</label> 
    <div class="col-sm-2"> <label><input type="text" class="form-control" id="present_salary" name="present_salary"/><span class="help-block"></span></label></div>
</div>

 

////////////////////////out put//////////////

SELECT c.id,c.designation,c.grade
FROM cadre c, dept_has_cadre dhc, assign_dept a_d
WHERE c.id=dhc.cadre_id
AND dhc.dept_id=1
AND dhc.dept_id=a_d.dept_id
AND a_d.user_id=4
AND dhc.year = (SELECT MAX( YEAR ) max_year FROM dept_has_cadre )

Array
(
   [code] => 0
   [message] =>
)

Array
(
   [0] => stdClass Object
       (
           [id] => 1
           [designation] => Senior Lecturer
           [grade] => Grade 2
       )

)

[{"id":"1","designation":"Senior Lecturer","grade":"Grade 2"}]
Inspect the select box and see what values and labels are appended in the end. Also you the source code that inserts values is missing, but most likely you just haven't passed the value or are passing incorrect value to query.
the second option doesnot append the value based on first select option changes
Ah got it, so the SQL error wasn't the real issue - so that confused me.

Just looking at code it should work, so you should work your way backwards.

Console log the data, does the AJAX call get right data?

If it does, then is the each loop working?

If it doesn't, you need to check your controller that AJAX is calling and figure out why it's not giving you the correct data to start with.

Not sure if there's name for this method, but I tend to debug my stuff by going roughly in the middle, check if at that point data is what I expect it to be, then either go "higher" or "lower" in code execution, again splitting code in half and repeating it until I find the single point that issues occur.
It's not clear how far you have traced the execution and at what point it's breaking. But I see some ways you might improve this.

The "view" code seems to have some extra <label></label> pairs in a couple spots. Here it is cleaned up and using PHP Alternate Syntax because, for me, it's easier to read.

PHP Code:
<div class="form-group">
 
   <label class="col-sm-2 control-label"Dept/Unit/Branch</label
 
   <div class="col-xs-4"
 
       <select name="dept_no" id="dept_no" class="form-control">
 
           <option value="-1"> --- Select Dept/Unit/Branch --- </option>
 
           <?php foreach ($information_assign_dept as $row):
 
               ?>
                <option value="<?php echo $row->id?>" ><?php
                    if
($row->faculty_id != 0)
 
                   {
 
                       echo $row->dept_name.' / '.$row->faculty_name;
 
                   }
 
                   else
                    
{
 
                       echo $row->dept_name;
 
                   }
 
                   ?>
                </option>
            <?php endforeach; ?>
        </select>
        <span class="help-block"></span>         
    </div>
</div>
<div class="form-group"> 
    <label class="col-sm-2 control-label"> Designation </label> 
    <div class="col-xs-3"> 
        <select disabled class="form-control" id="cadre_id" name="cadre_id">
            <option value="-1">--- Select Designation ---</option>
        </select>
        <span class="help-block"></span>
    </div> 

    <label class="col-sm-2 control-label">Present Salary</label> 
    <div class="col-sm-2">
        <input type="text" class="form-control" id="present_salary" name="present_salary"/><span class="help-block"></span>
    </div>
</div> 

Notice that the Designation <select> element is disabled. This prevents using this element until we put some options into it. The disabled attribute will be removed in JavaScript shown later.

Here's a revised controller method. I'll explain the output from this when I talk about the JavaScript.

PHP Code:
public function get_selected_dept_attached_post($dept_no)
{
 
   $userid $this->session->userdata('id');
 
   $this->load->model('Model_user');
 
   $options $this->Model_user->dept_attached_post($dept_no$userid);
 
   if(emtpy($options)) //model returned nothing, send back a string we can use know that
 
   {
 
       echo "empty";
 
       return;
 
   }
 
   
    $out 
"<option value='-1' selected>--- Select Designation ---</option>";
 
   foreach ($options as $option)
 
   {
 
       $out .= "<option value='{$option->id}'>{$option->designation} / {$option->grade}</option>";
 
   }
 
   echo $out;


Note that the "selected" option is --- Select Designation --. It's not clear to me that you need this option because I'm not sure the model ever returns more than one row. And if it does return more than one, what are the criteria for which <option> should be selected? My assumption is that there can be multiple rows and there are not any criteria to determine which is selected. Therefore, the user needs the "select something" hint and it should be the default ("selected") option.

Now the JavaScript.

The JQuery selector for the "dept" <select> could be cleaner. This line
Code:
$('select[name="dept_no"]')
is ineffcient and hard to read.

Instead, use the "id" attribute as you did for the other <select> elsewhere in your code. Change the above to
Code:
$('#dept_no').on('change', function() {

A change in thinking about what is returned to success: might help a lot. Instead of returning JSON consider returning HTML. That would solve the problem of setting the "selected" option and would eliminate any need to process on the client-side except to put the returned HTML in the right spot on the page. The controller method above is returning HTML.

The amount of data sent back as HTML is not that large. It's not significantly larger than the JSON would be and PHP is designed for consturcting HTML. It does that really fast. On the client-side, it's much more efficient to simply replace some HTML than it is to create the HTML by runing a loop that makes multiple calls to $('#cadre_id').append.... And then there's all the string concantenation, e.g. "<option value='"+data.id+"'>"+data.designation+" / "+data.grade+"</option>" which is resource (time, memory, processing) intensive.

To return HTML instead of JSON, change dataType: "json", to dataType: "html",.

So, with all that in mind, the JavaScript should look something like this.

Code:
$('#dept_no').on('change', function () {
   var dept_no_ID = $(this).val();
   if (dept_no_ID) {
       $.ajax({
           url: "<?php echo site_url('clerkAE/get_selected_dept_attached_post').'/'; ?>" + dept_no_ID,
           type: "GET",
           dataType: "html",
           success: function (data)
           {
               var optionsList = $("#cadre_id");
               if (data !== 'empty') {
                   optionsList.prop("disabled", false); //enable the <select> element
                   optionsList.html(data);
               } else {
                   optionsList.prop("disabled", true); //make sure <select> element is disabled
               }

           }
       });
   }
});

I'm not 100% on the URL construction. First, it's not going to evaluate correctly unless the JavaScript is in-line. If the JavaScript loads from an external file it's not going to construct a proper URL string because the PHP won't evaluate meaning the constroller function never gets to execute. If that is the case you'll need to find some other way to build the URL. One way is like this.

Code:
var baseURL = location.host;
var ajaxURL = baseURL + '/clerkAE/get_selected_dept_attached_post';
//then later on
       $.ajax({
           url: ajaxURL + dept_no_ID,

Hope this helps.
still im unable to solve this problem. it says

Column 'cadre_id' cannot be null

INSERT INTO `emp_pmt` (`full_name`, `initials`, `last_name`, `first_name`, `emp_no`, `nic`, `p_file_no`, `upf_no`, `profix`, `sex`, `civil_status`, `s_name`, `s_nic`, `dob`, `address`, `home_phone`, `mobile_phone`, `email`, `cadre_id`, `present_salary`, `dept_no`, `date_appoinment`, `qualification`, `confirmed_emp`, `date_confirmed`, `due_date_confirm`, `due_date_increment`, `date_retirement`, `pensionable`, `pension_no`, `remarks`) VALUES ('uhytrhytrhtry', 'rtyt', 'twerte', 'fdsd', '3243', '76878', '5465', '908768', 'Ms.', 'Female', 'Single', '', '', '2018-10-18', ' vfdgbvg b', '324354', '9870687', '[email protected]', NULL, '50000', '1', '2018-10-01', '1st Degree', 'Yes', '2018-10-05', '', '2018-10-12', '2018-10-31', 'No', '', 'FDS VFD VGFD')
(10-15-2018, 01:49 AM)jackey Wrote: [ -> ]still im unable to solve this problem. it says

Column 'cadre_id' cannot be null

INSERT INTO `emp_pmt` (`full_name`, `initials`, `last_name`, `first_name`, `emp_no`, `nic`, `p_file_no`, `upf_no`, `profix`, `sex`, `civil_status`, `s_name`, `s_nic`, `dob`, `address`, `home_phone`, `mobile_phone`, `email`, `cadre_id`, `present_salary`, `dept_no`, `date_appoinment`, `qualification`, `confirmed_emp`, `date_confirmed`, `due_date_confirm`, `due_date_increment`, `date_retirement`, `pensionable`, `pension_no`, `remarks`) VALUES ('uhytrhytrhtry', 'rtyt', 'twerte', 'fdsd', '3243', '76878', '5465', '908768', 'Ms.', 'Female', 'Single', '', '', '2018-10-18', ' vfdgbvg b', '324354', '9870687', '[email protected]', NULL, '50000', '1', '2018-10-01', '1st Degree', 'Yes', '2018-10-05', '', '2018-10-12', '2018-10-31', 'No', '', 'FDS VFD VGFD')

Basically what it's saying is that field 'cadre_id' requires a value (cannot be null) and you have not supplied a value to be inserted.

Hard to offer any more advice about the problem because you don't show us any code related to inserting data.
PHP Code:
///////////controller//////////////

public function add_new_emp() {
 
  
//$this-> _validate_add_new_emp(); 
 
     
$data 
= array( 
'full_name' => $this->input->post('full_name'), 
'initials' => $this->input->post('initials'),
'last_name' => $this->input->post('last_name'),
'first_name' => $this->input->post('first_name'),  
'emp_no' => $this->input->post('emp_no'),
'nic' => $this->input->post('nic'),
'p_file_no' => $this->input->post('p_file_no'),   
'upf_no' => $this->input->post('upf_no'),
'profix' => $this->input->post('profix'),   
'sex' => $this->input->post('sex'),
'civil_status' => $this->input->post('civil_status'),
's_name' => $this->input->post('spouse_name'),  
's_nic' => $this->input->post('spouse_nic'),
'dob' => $this->input->post('dob'), 
'address' => $this->input->post('address'),
'home_phone' => $this->input->post('home_phone'),  
'mobile_phone' => $this->input->post('mobile_phone'), 
'email' => $this->input->post('email'),  
'cadre_id' => $this->input->post('designation'), 
'present_salary' => $this->input->post('present_salary'),    
'dept_no'  => $this->input->post('dept_no'),  
'date_appoinment' => $this->input->post('date_appoinment'),
'qualification' => $this->input->post('qualification'),
'confirmed_emp' => $this->input->post('confirmed_emp'),   
'date_confirmed' => $this->input->post('date_confirmed'),  
'due_date_confirm' => $this->input->post('due_date_confirm'),   
'due_date_increment' => $this->input->post('due_date_increment'),   
 
'date_retirement' => $this->input->post('due_date_retirement'),   
 
'pensionable' => $this->input->post('pensionable'),   
 
'pension_no' => $this->input->post('pension_no'),   
 
'remarks' => $this->input->post('remarks')
 
 );  

      
$data_increment_tbl 
= array(        
'emp_no' => $this->input->post('emp_no'),     
'cid' => $this->input->post('designation'), 
'appoinment_date' => $this->input->post('date_appoinment'),      
'next_date_increment' => $this->input->post('due_date_increment'),
'send_form_bit' => 0   
 
);
 
$data_confirm_tbl = array(        
'emp_no' => $this->input->post('emp_no'),     
'date_confirmed' => $this->input->post('date_confirmed'),
'dueDate_confirm' => $this->input->post('due_date_confirm'      
 
);       
             $this
->load->model('Model_user');
     
    $this->Model_user->model_add_new_emp($data,$data_increment_tbl,$data_confirm_tbl);                   
             $this
->session->set_flashdata('message'' Successfully ADDED New Employee ......');
     
    echo json_encode(array("status" => TRUE));  
 
}
 



/////////////model/////////////

public function model_add_new_emp($data$data_increment_tbl$data_confirm_tbl) {  
          
            $this
->db->insert('emp_pmt'$data);
            
            $this
->db->insert('increment'$data_increment_tbl);
            $this->db->insert('confirm'$data_confirm_tbl);
            
              
return $this->db->insert_id(); 
        

PHP Code:
'cadre_id' => $this->input->post('designation'), 


On your view you have the field named 'cadre_id' as well, not 'designation' so shouldn't it be:
PHP Code:
'cadre_id' => $this->input->post('cadre_id'), 
thank you very much droidjv.

now it works properly.