dericcain
dericcain

Reputation: 2290

Updating list using AJAX in Codeigniter (within a form)

I have a form that adds clients to a database clients/add_client. The add_client method has a parameter of $state which is passed to another method list_centers(). When someone is talking to a potential client, they have all of our centers in a sidebar. There is a <select> above the list of centers in which lists the states where we have centers. When they change the select to another state, it should list all of the centers in that state. Now, I have this working by passing the parameter in the URL like this: localhost/clients/add_clients/GA lists all of the centers in Georgia. The problem is that I want to do this with AJAX and not have the page refresh. I cannot figure out how to pass this data via ajax. I know that I have to reconstruct the list each time but I am stuck. Here is what I have tried:

$('#center_select').change(function(){
        var data = $(this).val();
        var url = 'add_client/' + data;
        $.ajax({
            type: 'POST',
            dataType: 'html',
            data: data,
            url: url,
            success: function(data) {
                console.log(data);
            },
            error: function(data) {
                console.log(data);  
            } 
        });
        return false;
    });

Just in case you need the method:

public function add_client($state = false) {

        $this->load->model('centers_model');

        $data = array(
            'page_title' => 'Add Client',
            'client_status' => $this->clients_model->list_client_status(),
            'centers' => $this->centers_model->list_centers(null, $state),
            'center_states' => $this->centers_model->list_center_states(),
        );

        $this->load->view('header');
        $this->load->view('clients/add_client', $data);
        $this->load->view('footer');

    }

View:

<div class="col-sm-3">
            <aside id="centers_sidebar" class="well">
                <h2>List of Centers</h2>
                <select class="form-control" name="center_select" id="center_select">
                    <option value="all">All</option>
                    <?php
                        foreach ($center_states as $center_state) {
                            echo '<option value="' . $center_state->center_state . '">' . $center_state->name . '</option>';
                        }
                    ?>
                </select>
                <ul id="center_list">
                    <?php
                        foreach ($centers as $center) {
                            $output = '<li class="center">';
                            $output .= '<h5>' . $center->center_name . '</h5>';
                            $output .= '<p>' . $center->center_type . '</p>';
                            $output .= '<p>' . $center->center_city . ', ' . $center->center_state . '</p>';
                            $output .= '<p>' . $center->center_phone . '</p>';
                            $output .= '</li>';
                            $output .= '<hr>';

                            echo $output;
                        }
                    ?>
                </ul>   
            </aside>
        </div>

Upvotes: 0

Views: 1291

Answers (1)

DFriend
DFriend

Reputation: 8964

I failed to notice that you request a POST but setup for a GET. So here we supply the proper structure to ajax.data

select handler

  $('#center_select').change(function () {
    var st = $(this).val();
      var url = 'update_centers';
    $.ajax({
      type: 'POST',
      dataType: 'html',
      data: {state: st},
      url: url,
      success: function (data) {
        console.log(data);
        $("#center_list").html(data);
      },
      error: function (jqXHR, textStatus, errorThrown) {
        //useful for trouble shooting & error handling
        console.log(textStatus, errorThrown);
      }
    });
    return false;
  });

AJAX responder method - builds html to send back to ajax.success We need to pull the input from $_POST (using input->post) I've put in a bunch of validity checks and a general purpose ajax error response function too. No extra charge.

function update_centers()
{
  $this->load->model('centers_model');
  $state = $this->input->post('state');
  if(!isset($state))
  {
    $this->ajax_bad_request_error("No state data received");
    return;
  }

  $centers = $this->centers_model->list_centers(null, $state);
  if(!isset($centers))
  {
    $this->ajax_bad_request_error("The database failed to find centers in $state");
    return;
  }

  $output = "";
  foreach($centers as $center)
  {
    $output .= "<li class='center'><h5>$center->center_name</h5>"
      ."<p>$center->center_type</p>"
      ."<p>$center->center_city, $center->center_state</p>"
      ."<p>$center->center_phone</p></li><hr>";
  }
  echo $output;
}

function ajax_bad_request_error($msg)
{
  //All purpose reporting of ajax failure
  header('HTTP/1.1 400 Bad Request');
  header('Content-Type: application/json; charset=UTF-8');
  $data = array('type' => 'error', 'message' => $msg);
  echo json_encode($data);
}

Cannot guarantee this will work perfectly as is - syntax errors may exist. But the concept is sound.

Upvotes: 1

Related Questions