Ramesh Pareek
Ramesh Pareek

Reputation: 1669

using json data from ajax call in rendering html elements in datatables

I'm using Ajax data source (objects) for rendering datatables. here is the example json:

"data": [{
    "news_id": 22,
    "news_title": "Annual function held in school",
    "news_details": "Annual function was held in school",
    "created_at": "2016-02-19 17:01:38",
    "imgurl": "uploads/images/8.JPG"
}]

now, using last element "imgurl", I want to render a link in the last column of the datatables. like this one:uploads/images/8.JPG. I tried rendering a custom column as follows:

$('#example').DataTable( {
        "ajax": '?r=news/ajaxdata',
        "columns": [
            { "data": "news_id" },
            { "data": "news_title" },
            { "data": "news_details" },
            { "data": "created_at" },
            { "render": function (data, type, row, meta) {
            return $('<a>')
                        .attr('href', {"data": "imgurl"})
                        .text('link')
                        .wrap('<div></div>')
                        .parent()
                        .html();
    } },

        ]
    } );

It does not seem to be a proper way to do as it renders a link but the href element says [object][object]. I couldn't find the right documentation to do this either. can anybody help?

tried this:

{ "render": function (data, type, row, meta) {
                var d = JSON.parse(data);
                var d = d.imgurl; 
            return $('<a>')
                        .attr('href', d)
                        .text('link')
                        .wrap('<div></div>')
                        .parent()
                        .html();

    } },

the problem is to handle the ajax response.

Upvotes: 3

Views: 3399

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58860

First argument data holds data for the cell so it will have image URL uploads/images/8.JPG.

Use the code below instead:

{ 
    data: 'imgurl', //<----
    render: function (data, type, row, meta) {
        return 
           $('<a>')
              .attr('href', data)
              .text('link')
              .wrap('<div></div>')
              .parent()
              .html();
   } 
},

See columns.render for more information.

Upvotes: 4

Related Questions