0

I need your help to set cookies in a select.

I just need save the value of this select for the next time load the page, the value will be the same that last time selected. Really I dont have so much experience with javascript/ajax for that reason my post. I hope you guys can help me. Please find bellow my short code:

value to save as cookies (data-url)

<select id="timePeriod">
  <option data-url="https://api.myjson.com/bins/12at1e">Minute</option>
  <option data-url="https://api.myjson.com/bins/16cjya">Hour</option>
  <option data-url="https://api.myjson.com/bins/1fecci">Day</option>
  <option data-url="https://api.myjson.com/bins/1fecci">Forever</option>
</select>

function drawHighchart(timeFramUrl) {
    $.ajax({url: timeFramUrl, success: function(data){

        var currentValue = (data[data.length - 1][1]);

        Highcharts.chart('container', {

        chart: {
          zoomType: 'x',
          events: {
            load: function() {
              var series = this.series[0];
              var chart  = this;
              var yAxis  = chart.yAxis[0],
                           plotLine,
                           d,
                           newY;

              yAxis.addPlotLine({
                value: currentValue,
                color: '#ff5959',
                width: 2,
                zIndex: 5,
                id: 'plot-line-1',
                label: {
                  text: currentValue,
                  style: {
                    color: '#ff5959',
                    fontWeight: 'bold'
                  }
                }
              });

              reload = setInterval(function() {

                $.getJSON(timeFramUrl + '?v=' + Math.random(), function(recData) {
                    
                  var currentValue = (recData[recData.length - 1][1]); 
                  var currenttime  = (recData[recData.length - 1][0]);

                  series.setData(recData);

                  var x = currenttime,
                      y = currentValue;

                  series.addPoint([x, y], true, true);    

                  plotLine  = yAxis.plotLinesAndBands[0].svgElem;
                  d         = plotLine.d.split(' ');
                  newY      = yAxis.toPixels(y) - d[2];
                  plotlabel = yAxis.plotLinesAndBands[0].label;

                  plotlabel.animate({
                  translateY: newY,
                  text: Highcharts.numberFormat(y, 2)
                  }, {
                    duration: 400,
                    step: function() {
                      $(this.element).html(y);
                    },
                    complete: function() { }
                  }),


                  plotLine.animate({
                    translateY: newY
                  }, 400);

                });

              }, 5000);


            }
          }
    },  
        title:         { text:        ''},
        exporting:     { enabled: false },
        credits:       { enabled: false },
        xAxis:         { type: 'datetime'},
        yAxis:         { opposite: true,
                         labels: {
                            align: 'left',
                         },
                         gridLineWidth: 0, 
                         title: {
                            text: 'Exchange rate'
                        }, 
        },
        plotOptions: {
          areaspline: { 
            marker: {
              enabled: false
            }
          }
        },
        series: [{
            name: 'Exchange BTC to EUR',
            data: data,
            type: 'areaspline',
            threshold: null,
            animation: true,
            tooltip: {
                valueDecimals: 2
            },
            fillColor: {
                linearGradient: { x1: 5, y1: 0, x2: 0, y2: 0
            },
            stops: [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ]
            }
        }]
    });
    }});
}

// To save as cookie
$(document).ready(function() {

    var srcURL = $(':selected', '#timePeriod').data('url');
    drawHighchart(srcURL);

    $('#timePeriod').change(function(){

        var srcURL = $(':selected', this).data('url');

        drawHighchart(srcURL);
    });
});
$('#timePeriod').change(function(){
     clearInterval(reload); 
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<!-- To save as cookies -->

<select id="timePeriod">
  <option data-url="https://api.myjson.com/bins/12at1e">Minute</option>
  <option data-url="https://api.myjson.com/bins/16cjya">Hour</option>
  <option data-url="https://api.myjson.com/bins/1fecci">Day</option>
  <option data-url="https://api.myjson.com/bins/1fecci">Forever</option>
  </select>
<div id="container" style="height: 400px; width: 100%"></div> 
FullDISK
  • 27
  • 6
  • 1
    Please show any research you've done on the subject. For instance, searching for "javascript set cookie" yielded this question almost immediately: [How do I create and read a value from cookie?](https://stackoverflow.com/q/4825683) – Heretic Monkey Jun 24 '18 at 17:57
  • @MikeMcCaughan Of course I found a lot of threads, but as I explained I have difficult to add it in my script... for that reason I asked for any help.. – FullDISK Jun 24 '18 at 18:00
  • Well, the answers to that question I linked to show how to create a cookie to store a value. Since you want to save the value selected, it would be logical to store the value in the cookie at the time it is selected. Can you see how to call the `createCookie` function with the `change` event handler you already have? Please try doing that and [edit] your question with the results of those attempts, and a specific question or problem you are facing. – Heretic Monkey Jun 24 '18 at 18:07
  • I fixed my problem using js-cookie – FullDISK Jun 24 '18 at 18:17

1 Answers1

0

You could use this library: https://github.com/carhartl/jquery-cookie

and then use something like:

$(document).ready(function () {
    $('#timePeriod').on('change', function() {
        $.cookie('myCookie', $('#timePeriod').val());
    });

    var cookieValue = $.cookie('myCookie');
    if (typeof cookieValue !== "undefined") {
        $('#timePeriod').val(cookieValue);
    }
});

In fact, I would use the value property of options in order to store the URL's, not a data-url attribute:

<select id="timePeriod">
  <option value="https://api.myjson.com/bins/12at1e">Minute</option>
  <option value="https://api.myjson.com/bins/16cjya">Hour</option>
  <option value="https://api.myjson.com/bins/1fecci">Day</option>
  <option value="https://api.myjson.com/bins/1fecci">Forever</option>
</select>

Unless there is any reason that forces you to use data-url?

Jean-François Beauchamp
  • 5,485
  • 8
  • 43
  • 77