Welcome Guest, Not a member yet? Register   Sign In
Ajax data from controller
#1

I'm new to the forum and fairly new to CodeIgniter but I very much enjoy it. When I perform an onchange submit (using a dropdown and refreshing the page) the ID gets sent over no problem to the controller which then sends back an encoded json to the view (without ajax):

[{"rowID":"48","FirstName":"Scott","LastName":"Currie","Email":"[email protected]","Phone":"579-887-7352"}]

Controller:
Code:
public function test() {
    if($this->input->post('list')){
          $id = $this->input->post('list');
          $query = $this->Booking_model->get_test_user($id);
          echo json_encode($query);
    }else{
          $data['users'] = $this->Booking_model->get_users();
          $this->load->view('home/test',$data);    
    }          
}

You can see in the code above this returns the json if an ID has been posted or else it just shows the list of users.

Now when I use Ajax and manually create an array in the controller returning the ID that also works (see code below).
Code:
public function test_ajax() {
   $id = $this->input->post('list');
   $data = array(
     'list' => $id
   );
   echo json_encode($data);
}

Here is what the ajax code looks like in the view:
View:
Code:
<script>
   $(document).ready(function(){
       $('#list').change(function(){
           var id = $('#list').val();
           console.log(id);
           $.ajax({
               type: 'POST',
               url: '<?php echo base_url();?>' + 'home/test_ajax',
               dataType: 'json',
               data: {list: id},
               success: function(data){
                   $('#result').html(data.list);
               }
           });
       });
   });
</script>

So, I want to be able to send the ID over to the controller via Ajax and return the encoded json like the first example without refreshing the page. I could then display the FirstName, LastName, Email and Phone being returned in the query from the model. Also, what is the proper way of displaying data returned from the ajax call. Is the $('').html(data.??) correct?

I hope that makes some sense and I apologize for the long winded question.

Thanks very much,

Scott
Reply


Messages In This Thread
Ajax data from controller - by scott3322 - 03-27-2018, 10:21 AM
RE: Ajax data from controller - by jreklund - 03-27-2018, 11:50 AM
RE: Ajax data from controller - by scott3322 - 03-28-2018, 08:17 AM
RE: Ajax data from controller - by jreklund - 03-28-2018, 11:31 AM
RE: Ajax data from controller - by scott3322 - 03-28-2018, 12:07 PM
RE: Ajax data from controller - by InsiteFX - 03-28-2018, 08:20 PM
RE: Ajax data from controller - by jordi_1h - 04-28-2020, 07:37 PM



Theme © iAndrew 2016 - Forum software by © MyBB