Hashir Anwaar Hashir Anwaar - 5 months ago 36
Javascript Question

Send and retrive data from database and display in select box without refreshing page in CodeIgniter

The PLAN

I am working in CodeIgniter; on Click Add button, a modal will pop Out and user will add new Item (Item ID, Item Desc, Rate and UoM) and then press submit button.

I send the data to database using AJAX without refreshing page and its working properly.

The PROBLEM

Now I want to retrieve data from database and append in SELECT BOX of item-ID and ITEM Desc respectively. I have done writing the code of MODEL and CONTROLLER in CodeIgniter, and now need AJAX code to append my fetched data at end of my pre-populated select boxes (on first time page load, select boxes get populated through php dynamically).

I want all work done without refreshing page.

Any kind of help or suggestion?

CODE OF MODEL in CODEIGNITER

<?php
class PostModel extends CI_Model {

function getLastRecord(){
$query = "select * from sale order by itemid DESC limit 1";
$res = $this->db->query($query);

if($res->num_rows() > 0) {
return $res->result();
}
return result();
}
}
?>


CODE OF CONTROLLER

public function index()
{
$data['last'] = $this->PostModel->getLastRecord();
$this->load->view('header');
$this->load->view('salevocher', $data);
$this->load->view('footer');
}

Answer

Your ajax should populate your selectbox after the success response:

$.ajax({
    url: ...,
    success: function(data) {
        loadMySelectbox();
    }
});

function loadMySelectbox() {
    $.ajax({
        url: 'controller/getSelectboxData',
        success: function(data) {
            $.each(data, function(key, value) {
                $('#mySelectbox').append($('<option>').text(value.item_desc).attr('value', value.item_id));
            });
        }
    });
}

PHP

//model
function getLastRecord(){
    //select only data you really need
    $query = "select itemid, itemdesc from sale order by itemid DESC limit 1";

//controller
public function getSelectboxData() {
    $data = $this->PostModel->getLastRecord();
    $this->output->set_content_type('application/json')
         ->set_output(json_encode($data));
}