Load view and make json data available in ajax request (Codeigniter)

10,037

Solution 1

You can turn the whole response into json.

$this->load->view() has a third argument that lets you return the view as a string to a variable.

I don't understand why you are json encoding $models to pass into the view so I will assume you want that as part of the main response

PHP

 public function letUsKnow() {
    $models = $this->dbmodel->get_models();
    $data = ?? ; // why is it json_encoded?
    $output = array(
        'html'=>$this->load->view("letUsKnow",$data, true),
        'data' = >$models
    );
    // should set Content Type header for json here - see output docs
    echo json_encode($output);
}

AJAX

$.ajax({
    type: "POST",
    url: base_url + "init/letUsKnow", //calling method in controller
    data: {},
    dataType:'json',
    success: function (response) {
        var modelsData = response.data;
        $("#ads_container").html(response.html);
    },
    error: function(){ alert('Ooops ... server problem'); }
});  

Solution 2

    //PHP
    public function letUsKnow() {
        $models = $this->dbmodel->get_models();
    $data =[];// why is it json_encoded?
            header( "Content-Type: application/json" );
        $output = array(
            'html'=>$this->load->view("letUsKnow",$data, true),
            'data' = >$models
        );
        // should set Content Type header for json here - see output docs
        echo json_encode($output);
return;
    }


    //AJAX
    $.ajax({
        type: "POST",
        url: base_url + "init/letUsKnow", //calling method in controller
        data: {},
        dataType:'json',
        success: function (response) {
            var modelsData = response.data;
            $("#ads_container").html(response.html);
        },
        error: function(){ alert('Ooops ... server problem'); }
    });
Share:
10,037
user254153
Author by

user254153

I am the student studying bachelor in computer application and currently trying to make the project From php.

Updated on June 04, 2022

Comments

  • user254153
    user254153 almost 2 years

    I want ajax request to load view as well as make json data available for same loaded view. In bellow ajax request, I am making request to letUsKnow method which loads views and also I want json data to be available in same loaded views. I tried following code but its not working.

    $(document).on("click", "#letKnow", function(){
            $.ajax({
            'type': "POST",
            'url': base_url + "init/letUsKnow",    //calling method in controller
            'data': {},
            success: function (response)
            {
                $("#ads_container").html(response.html);
                alert(response.data[0].model_name);     //undefined
            },
            complete: function()
            {
    
            }
        });
    });
    

    init (controller)

     public function letUsKnow() {
        $models = $this->dbmodel->get_models();
        $data = json_encode($models);
        $this->load->view("letUsKnow",$data);
    
    }
    

    Can this functionality be obtained from single ajax request. I can do with two ajax request that after loading view from one ajax request and again another ajax to request json data. But, How to fulfill this with single ajax request.

    Edit

    You can turn the whole response into json.

    $this->load->view() has a third argument that lets you return the view as a string to a variable.

    I don't understand why you are json encoding $models to pass into the view so I will assume you want that as part of the main response

    PHP

     public function letUsKnow() {
        $models = $this->dbmodel->get_models();
    
        $output = array(
            'html'=>$this->load->view("letUsKnow",$models, true),
            'data' = >$models
        );
        // should set Content Type header for json here - see output docs
        echo json_encode($output);
    }
    

    array ($models)

     // $models after json encode in ajax response
         {"abc":[{"id":"76","brand_id":"23","model_name":"iphone 4"},{"id":"77","brand_id":"23","model_name":"iphone 4s"}]}
    
     // after making array of views and data and after json encode in ajax response I get:
          {"html":"this is html views <\/div>\r\n<\/div>\r\n\r\n\r\n\r\n",
           "data":{"abc":[{"id":"76","brand_id":"23","model_name":"iphone 4"},{"id":"77","brand_id":"23","model_name":"iphone 4s"}]}} 
    
     // but in real my view's html is:
          <div>this is html views</div><div id="iop"></div>    //html in controller
    
     // also when I tried to access json object like:
          response.hm   // I get undefined
          response.data.model_name    //I get undefined.
    

    AJAX

    $.ajax({
        type: "POST",
        url: base_url + "init/letUsKnow", //calling method in controller
        data: {},
        dataType:'json',
        success: function (response) {
            var modelsData = response.data;             //undefined
            $("#ads_container").html(response.html);    //undefined
        },
        error: function(){ alert('Ooops ... server problem'); }
    });  
    
  • user254153
    user254153 about 9 years
    I didn't know view can be assigned to variable. I json encoded $models because I need this in view letUsKnow. Now, view is also json encoded. I will try and let you know. Thanks for response.
  • charlietfl
    charlietfl about 9 years
    but $data needs to be array when passed to view , then you access the array keys as variables ... or so I always thought in codeigniter. Are you using codeigniter3?
  • user254153
    user254153 about 9 years
    No I am not using codeigniter 3.0. since its not completed version yet. Okey, but does this functionality accepted in codeigniter below 3.0.\
  • charlietfl
    charlietfl about 9 years
    yes definitely... I have one project i do a lot of work on and use this approach all the time. Using 2.13
  • user254153
    user254153 about 9 years
    Its not working. Its throwing error ` json_encode() [<a href='function.json-encode'>function.json-encode</a>]: type is unsupported, encoded as null`
  • charlietfl
    charlietfl about 9 years
    That html is meaningless to me. I don't know anything about your view or $models. Concept will work fine , I do it all the time
  • user254153
    user254153 about 9 years
    Yea I can access that data in view but I cannot access that data in ajax success.
  • charlietfl
    charlietfl about 9 years
    I can't help much more without being able to see dumps of that data or template.
  • user254153
    user254153 about 9 years
    I edited my question hope it would helpful for you. I get undefined when access json object in ajax success.
  • charlietfl
    charlietfl about 9 years
    log the whole response to console, it isn't undefined if success fires and you already showed the array is being converted. zneed to travlers the data part properly. It is an array inside reseponse.data.abc ...there is no response.data.model_name in that structure. You would have to loop over array of objects to access the model_name