简体   繁体   中英

Execute query & display results using AJAX in CodeIgniter

I need some help getting AJAX to work within a CodeIgniter project. Based off of a user's selection, I want to use AJAX to send a variable (Agency_Number) to my controller to execute and get query results back within my view.

Example:

  1. User selects the Agency Number from the dropdown list
  2. Agency Number sent to the controller using AJAX
  3. Agency Number sent to model to execute query to select that agency's info from database.
  4. Form inputs, such as Program_Host_Name, get populated with Agency information.

I'm able to successfully execute the query and get the Program Host Name to populate within my form, however, my select input disappears from the page when the information is returned. I suppose this is caused by reloading my view, which I don't think I should be doing in the first place. I'm not sure how to pass the Program_Host_Name value back to my view without doing this though.

Thanks for any help y'all can give!

Here's my view (create_opportunity.php)

<form submit="opportunity/create_opportunity" id="validation-form" method="POST">
<select id="Agency_Number">
  <option value=""></option>
  <?php foreach ($agencies as $agency):?>
  <option value="<?php echo $agency->Agency_Number;?>"><?php echo $agency->Agency_Number;?></option>
  <?php endforeach;?>
</select>

<input type="text" id="Program_Host_Name" value="<?php echo $Program_Host_Name ?>"/>
</form>

Here's my script within the view:

<script type="text/javascript">
$('#Lookup').click(function() {

    var AgencyNumber = $('#Agency_Number').val();

    if (!AgencyNumber || AgencyNumber == 'Agency_Number') {
        alert('Please enter an Agency Number');
        return false;
    }

    var form_data = {
        Agency_Number: $('#Agency_Number').val(),
        ajax: '1'
    };

    $.ajax({
        url: "<?php echo site_url('opportunity/create_opportunity'); ?>",
        type: 'POST',
        data: form_data,
        success: function(msg) {
            $('body').html(msg);
        }
    });

    return false;
});
</script>

Here's my controller (opportunity.php)

function create_opportunity() {

  $this->data['agencies'] = $this->ion_auth_model->get_agencies();

  if($this->input->post('ajax')) {
    $Agency_Number = $this->input->post('Agency_Number');
    $agency = $this->ion_auth_model->get_agency($Agency_Number)->row();
    $this->data['Program_Host_Name'] = $agency->Name;
    $this->data['Address_1'] = $agency->Address_1;
  } 

    $this->data['main_content'] = 'create_opportunity';
    $this->load->view('./_blocks/template', $this->data);
}

I had to use json_encode() to convert an associative array from PHP into JSON and then used $.getJSON() to return the JavaScript array.

Here's my working script:

<script type="text/javascript">
$('#Lookup').click(function() {

    var AgencyNumber = $('#Agency_Number').val();

    if (!AgencyNumber || AgencyNumber == 'Agency_Number') {
        alert('Please enter an Agency Number');
        return false;
    }

    var form_data = {
        Agency_Number: $('#Agency_Number').val(),
        ajax: '1'
    };

    $.ajax({
        url: "<?php echo site_url('opportunity/get_agency'); ?>",
        type: 'POST',
        data: form_data,
        dataType: 'json',
        cache: false,
        success: function(data) {
            $('#Program_Host_Name').val(data.Program_Host_Name);
            $('#Address_Line_1').val(data.Address_1);
        },
        error: function(thrownError) {
            alert(thrownError);
        }
    });

    return false;
});
</script>

Here's my working controller:

function get_agency() {

    if($this->input->post('ajax')) {
        $Agency_Number = $this->input->post('Agency_Number');

        $agency = $this->ion_auth_model->get_agency($Agency_Number)->row();

        echo json_encode(
            array(  "Program_Host_Name" => "$agency->Name",
                    "Address_1" => "$agency->Address_1"
            )
        );
    }

}

Thanks for the help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM