Pontus Nordh
Pontus Nordh

Reputation: 25

Display returned JSON objects with jQuery

I'm having trouble figuring out how to display some return JSON objects.

My script works like this:

I'm making an ajax call, sending some params to a CodeIgniter Controller where I'm processing it with a model, making some queries towards an database and then returning the json_encoded rows to the ajax callback function. This works great btw.

Here is what I want to do now and here its where I'm stuck. I want the new JSON objects (contains database rows) to "replace" the old rows in a html table. So I want it to update the table depending on the params I'm passing but only in the tbody mind.

I'm new at jquery so I've tried i few things. I've tried iterate trough the json data and use the $.html(string) function but i guess this replace everything and it will eventually just display the last object(Am i right?).

So I wonder how in a general sense I would do this?

Upvotes: 2

Views: 1663

Answers (3)

Philip
Philip

Reputation: 4592

What are the params your passing in?

for example you might use a select or input field to trigger an ajax call and pass its value as the param.

var tableObj = {

    var init : function(){
        //check that your selectors id exists, then call it
        this.foo();
    },
    foo : function(){

        var requestAjax = function(param){
            var data = {param : param}
            $.ajax({

                data : data,
                success : function(callback){
                    console.log(callback);//debug it

                    $("tbody").empty();//remove existing data

                    for(var i =0; i < callback.data.length; i++){}//run a loop on the data an build tbody contents

                    $("tbody").append(someElements);//append new data
                }
            });
        }
        //trigger event for bar
        $("#bar").keyup(function(){
              requestAjax($(this).val());
        });
    }

}

$(function(){
    tableObj.init();
})

Your php method

public function my_method(){
    if($this->input->is_ajax_request())
    {
       //change the output, no view
       $json = array(
           'status' => 'ok',
           'data' => $object
       );

       $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($json));
    }
    else
    {
       show_404();
    }
}

Upvotes: 0

landons
landons

Reputation: 9547

You don't have to return JSON objects in an AJAX request. Try setting the data_type config setting for the $.ajax call to "html" (or leave it blank--jQuery is really good about figuring it out from the response data).

I usually factor out the <tbody>...</tbody> portion of a view to its own view partial. Then, the "original" page load can use it, and so can an updating AJAX call.

The only asterisk to this is if you need some sort of object-oriented response along with the HTML. I would usually do something like this:

{
    "stat": "ok",
    "payload": "<tr><td>row1</td></tr><tr><td>row2</td></tr>"
}

And then in the ajax success function:

$.post('/controller/action', { some: 'data' }, function(response) {
    $('#my_table tbody').append(response.payload);
}, 'json');

Upvotes: 1

Kristian
Kristian

Reputation: 21810

$.ajax({
   type: 'GET',
   url: 'someSite.com/someEndpoint'
   data: xyz.
   success: function( response ) {
      //lets say you have an object like this: object = {  data: { ... } }
      var html = '';
      for(var i = 0; i<response.data.length; i++) {
          html += '<tr><td>'+response.data[i].title+'</td></tr>';
      }
      $('#someTable tbody').html(html);
   }
});

Upvotes: 2

Related Questions