mheavers
mheavers

Reputation: 30188

code igniter php and jquery - how to get data from multiple tables and return it via ajax

I am currently using jquery to get JSON data via ajax from a codeigniter backend / mySQL database, which works fine. The problem I'm having is that, along with the data that gets returned to the jquery function, I also need to run a PHP loop for some data in another table. Currently what I'm doing is waiting for an ajax success from the first function, then making another ajax call to the second function - but I know there is a way to do it with just one function, I'm just not sure how. Here are the two database queries:

function get_selected_member($member = null){
        if($member != NULL){
            $this->db->where('id', $member); //conditions
        }
        $query = $this->db->get('members'); //db name

        if($query->result()){
            $member_result = $query->row();
            return $member_result;
        }
    }

AND

function get_all_groups(){
        $query = $this->db->get('groups');
        $result = $query->result();
        return $result;
    }

and then in the javascript function, what I'm doing is saying:

var post_url = "/index.php/control_form/get_selected_member/" + selected_member_id;
$('#chosen_member').empty();
$.ajax({
    type: "POST",
    url: post_url,
    success: function(member)
    {
        //Add all the member data and...

        var post_url2 = "/index.php/control_form/get_all_groups/";
        $.ajax({
            type: "POST",
            url: post_url2,
            success: function(group)
            {
        //Create a dropdown of all the groups
            }
        });
    }
});

Upvotes: 5

Views: 2777

Answers (1)

Tapos
Tapos

Reputation: 601

In PHP you can combine both in one then echo it to ajax as json variable. So in php you will need a change like following

function get_member_with_group($member = null){
    $data['member'] = $this->get_selected_member($member);
    $data['group'] =  $this->get_all_groups();
    echo json_encode($data);
}

Then in javascript something like below..

var post_url = "/index.php/control_form/get_member_with_group/" + selected_member_id;
$('#chosen_member').empty();
$.getJSON(post_url, function(response){
    var member = response.member;
    //do with member
    var group = response.group;
    // do with group
});

Hope this will help you :)

Upvotes: 7

Related Questions