Sparkline with value as comma separated String instead of Array

Sparkline with value as comma separated String instead of Array

AlsatanAlsatan Posts: 6Questions: 1Answers: 0

I'm trying to implement a Sparkline into my table but using values that are passed in a comma separated string.
To have a clear understanding I just created a clean new project and replicated the default Stock Market example. The example uses data like:

 var stock_data = [
        {
            "name": "ACME Gadgets",
            "symbol": "AGDTS",
            "last": [2.57, 2.54, 2.54, 2.56, 2.57, 2.58, 2.59]
        },

Now.. how would I need to change the code in order to process the values in "last" as a comma separated values instead of an array?

 var stock_data = [
        {
            "name": "ACME Gadgets",
            "symbol": "AGDTS",
            "last": "2.57, 2.54, 2.54, 2.56, 2.57, 2.58, 2.59"
        }

I imagine that I should put some .split(", ") somewhere ,I tried to play around with the "data" in the data: 'last' Render but with no success..

Here is the full js code:

$(document).ready(function () {
    var stock_data = [
        {
            "name": "ACME Gadgets",
            "symbol": "AGDTS",
            "last": "2.57, 2.54, 2.54, 2.56, 2.57, 2.58, 2.59"
        },
        {
            "name": "Spry Media Productions",
            "symbol": "SPMP",
            "last": "1.12, 1.11, 1.08, 1.08, 1.09, 1.11, 1.08"
        },
        {
            "name": "Widget Emporium",
            "symbol": "WDEMP",
            "last": "3.40, 3.39, 3.46, 3.51, 3.50, 3.48, 3.49"
        },
        {
            "name": "Sole Goodman",
            "symbol": "SGMAN",
            "last": "16.20, 16.40, 16.36, 16.35, 16.61, 16.46, 16.19"
        },
        {
            "name": "Stanler Bits and Bobs",
            "symbol": "SBIBO",
            "last": "82.51, 83.47, 83.40, 83.68, 83.81, 83.29, 83.72"
        }
    ];

    let table = $('#example').DataTable({
        ajax: function (dataSent, callback, settings) {
            let data = this.api().ajax.json();
            if (data == undefined) {
                data = stock_data;
            } else {
                data = data.data;
                for (i = 0; i < data.length; i++) {
                    data[i].last.push(data[i].last.shift())
                }
            }

            callback({ data: data.split(", ") });
        },
        paging: false,
        initComplete: function () {
            let api = this.api();
            setInterval(function () {
                api.ajax.reload();
            }, 5000);
        },
        drawCallback: function () {
            $('.sparkline')
                .map(function () {
                    return $('canvas', this).length ? null : this;
                })
                .sparkline('html', {
                    type: 'line',
                    width: '250px'
                })
        },
        columns: [
            {
                data: 'name'
            },
            {
                data: 'symbol'
            },
            {
                data: null,
                render: function (data, type, row, meta) {
                    return row.last[row.last.length - 1].toFixed(2);
                }
            },
            {
                data: null,
                render: function (data, type, row, meta) {
                    var val = (row.last[row.last.length - 1] - row.last[row.last.length - 2]).toFixed(2);
                    var colour = val < 0 ? 'red' : 'green'
                    return type === 'display' ?
                        '<span style="color:' + colour + '">' + val + '</span>' :
                        val;
                }
            },
            {
                data: 'last',
                render: function (data, type, row, meta) {
                    return type === 'display' ?
                        '<span class="sparkline">' + data.toString() + '</span>' :
                        data;
                }
            }
        ]
    });
});

Answers

  • allanallan Posts: 63,161Questions: 1Answers: 10,406 Site admin

    Actually - I'd say you've got one less thing to do than the example!

    Line 88 in your code block above:

     data.toString()
    

    That converts the array to a comma separated list of values. So in your case, you already have a comma separated list of values, so just use data there.

    Also loose ajax.dataSrc. If your Ajax data already has the values in it, you don't need that stuff.

    Allan

  • AlsatanAlsatan Posts: 6Questions: 1Answers: 0
    edited August 2022

    Thanks @allan for the reply.

    I removed the .toString() but no data shows up now..

    A note...at line 42 I pasted the wrong code.. that was a test I did.. the original code has

    callback({ data: data });
    

    About the ajax, I don't see the ajax.dataSrc.. do you mean to simplify it like this?

            ajax: function (dataSent, callback, settings) {
                let data = this.api().ajax.json();
                    data = stock_data;
                callback({ data: data});
            },
    
  • allanallan Posts: 63,161Questions: 1Answers: 10,406 Site admin

    Oh yes, sorry I did. Does that function actually work? I don't see how it would get the initial data?

    You've got the data in the Javascript already, so ignore the ajax option and use data.

    I've put a little example together using your code from above to populate a table: http://live.datatables.net/zowecima/1/edit .

    Your homework for today is to get the sparkline running on that ;). Let me know how you get on (I've got my red pen handy).

    Allan

  • AlsatanAlsatan Posts: 6Questions: 1Answers: 0
    edited August 2022

    Yeah the code works.. and I'm trying to keep that because I'm trying first to make this "simple" example working to understand the issue but at the end I'll need to implement the solution on my webapp where I pull data from a database through a web api built with asp.net core MVC.

    Im' trying to access your link but when I click on it I get:
    NOT FOUND
    The requested URL was not found on this server.
    Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

  • AlsatanAlsatan Posts: 6Questions: 1Answers: 0

    This was solved! Some one on StackOverflow helped me. I mean... what you were saying should be right meaning that if my data is already a string then it should be enough to use data without .toString()

    The solution I implemented is thinking the other way around... you want an array to be then converted to a String? Ok here it is... adding this code:

       for(i = 0; i < data.length; i++) {
                        data[i].last = data[i].last.split(",").map(element => {
                            return Number(element);
                        });
    

    in the ajax... so it becomes:

            ajax: function (dataSent, callback, settings) {
                let data = this.api().ajax.json();
                data = stock_data;
                for (i = 0; i < data.length; i++) {
                    data[i].last = data[i].last.split(",").map(element => {
                        return Number(element);
                    });
                }
                callback({ data: data});
            },
    
  • AlsatanAlsatan Posts: 6Questions: 1Answers: 0

    ok now that the example works, I need to apply the same to my "real" project.. the problem is that in the real project the ajax part is like this:
    ajax: "api/ApartmentsAvailables",

    How can I apply a similar concept with this?

  • allanallan Posts: 63,161Questions: 1Answers: 10,406 Site admin

    Rather than using this.api().ajax.json() to get the JSON (since it can't have any - you've overridden it's ajax method) - you would need to make an Ajax call to your URL - $.ajax(...) could be used for that.

    Allan

  • AlsatanAlsatan Posts: 6Questions: 1Answers: 0

    so just using this code made it work without any data transformation...

            "ajax": {
                "url": "api/ApartmentsAvailables",
                "type": "GET",
                "contentType": "application/json; charset=utf-8",
                "dataType": "json",
            },
    
  • allanallan Posts: 63,161Questions: 1Answers: 10,406 Site admin

    Nice when things work out simpler!

    Good to hear you got it working.

    Allan

Sign In or Register to comment.