Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript variable from JSON feed object not recognized

I am using 2 JSON feeds to check the date and display the data from them depending on the current date and the date in one of the objects, but for some reason variable c which is object is undefined. When I replace the data in 'elements' function with hardcoded urls, everything works fine, but I am not sure why data isn't stored inside the c object:

jQuery(function ($) {
    var url1 = 'feed1.json';
    var url2 = 'feed2.json';
    var id = shop_id.replace(/\[|\]|\"/g, '');
    var c = {};
    var logo;

    $.when(request1(), request2()).done(function (r1, r2) {
        var results1 = $.grep(r1[0], function (e) {return e.id == id});
        var results2 = $.grep(r2[0], function (e) {return e.shop_id == id});
        var fallback = $.grep(r2[0], function (e) {return e.PSN == 'fallback160'});

        if (!$.isEmptyObject(results2)) {

            if (!$.isEmptyObject(results1)) {

                var today = new Date();
                var endDate = formatDate(results1[0].Ende);
                var startDate = formatDate(results1[0].Start);

                console.log(endDate);
                console.log(startDate);

                if (today <= endDate && today >= startDate) {
                    c = {'one': results1[0].INC_Suffix, 'separator': ' bis ', 'two': results1[0].Ende, 'link': results1[0].Deeplink, 'logo': results2[0].logo_url};
                    elements();
                }

            }
            else {
                c = {'one': results2[0].STD_INC_Factor, 'separator': ' ', 'two': results2[0].STD_INC_Suffix, 'link': results2[0].deeplink, 'logo': results2[0].logo_url};
                elements();
            }
        }
        else {
            $('#clicktag').html('<img src="' + fallback[0].logo_url + '">').attr('href', clicktag + encodeURIComponent(fallback[0].deeplink));
        }

        //resize fonts based on height of the container
        var intBoxHeight = $('#interupter').height();
        var intInnerHeight = $('#interupterInner').height();
        var intFontSize = parseInt($('#interupterInner').css('font-size'));

        while (intInnerHeight > intBoxHeight) {
            --intFontSize;
            $('#interupterInner').css('font-size', intFontSize + 'px');
            intBoxHeight = $('#interupter').height();
            intInnerHeight = $('#interupterInner').height();
        }

    }).fail(function () {
        c = {'one': 'DIE BESTEN', 'separator': ' ', 'two': 'ANGEBOTE', 'link': '#', 'logo': 'img/fallback.png'};
        elements();
    })

    function elements () {
        $('#storeLogo span').html('<img src=\'' + c.logo + '\'>');
        $('#interupterInner').html(c.one + c.separator + c.two);
        $('#clicktag').attr('href', clicktag + encodeURIComponent(c.link));
        tl.play();    
    }

    function formatDate (d) {
        var part = d.split('.');
        return new Date(part[1] + '.' + part[0] + '.' + part[2]);
    }

    console.log(elements());
    function request1 () {return $.getJSON(url1)};
    function request2 () {return $.getJSON(url2)};

})
like image 203
wintermute Avatar asked Nov 08 '22 14:11

wintermute


1 Answers

When I read the code I was wondering if you are planning to use variable c anywhere else - if not, consider to declare it locally inside each scope and pass it as parameter, i.e. elements(c).

I also stripped down the example a bit for easier analysis because you seem to have the issue only with the variable. In the simplified snippet below I added return c.one + ' ' + c.two; because that was missing in your elements() function, and I added a declaration for variable clicktag.

Besides that, I noticed that console.log(elements()); is called outside the done and fail functions - if the request is running long there could be a race condition causing c not yet being initialized when the log function is called. If your testing reveals that is the case, then put the log statement call inside each function (done and fail).

The code below - without the request delay - seems to run fine (Internet Explorer and Chrome - I don't have Firefox installed to test it, maybe you can do that with the snippet below and let me know):

jQuery(function($) {
  var c = {};
  var clicktag="https://stackoverflow.com/questions/47086470/javascript-variable-from-json-feed-object-not-recognized/47089907?noredirect=";
  $.when(SampleRequest(1), SampleRequest(2)).done(function(r1, r2) {
    c = {
      'one': 'SUCCESS - DIE BESTEN',
      'separator': ' ',
      'two': 'ANGEBOTE',
      'link': '1#',
      'logo': 'img/fallback.png'
    };
    elements();
  }).fail(function() {
    c = {
      'one': 'FAIL - DIE BESTEN',
      'separator': ' ',
      'two': 'ANGEBOTE',
      'link': '1#',
      'logo': 'img/fallback.png'
    };
    elements();
  })

  // change: commented tl.play, and added return statement
  function elements() {
    $('#storeLogo span').html('<img src=\'' + c.logo + '\'>');
    $('#interupterInner').html(c.one + c.separator + c.two);
    $('#clicktag').attr('href', clicktag + encodeURIComponent(c.link));
    //tl.play();    
    return c.one + ' ' + c.two;
  }

  function formatDate(d) {
    var part = d.split('.');
    return new Date(part[1] + '.' + part[0] + '.' + part[2]);
  }

  console.log(elements());

  function SampleRequest(reqId) {
    return "{id:'" + reqId + "'}";
  };

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id='Storelogo'></span>
<div id='interupterInner'></div>
<div id='interupterInner'></div>
<a id='clicktag'>click me</a>

Update: As per wintermute's reply in the comments, the reason for the error is the stricter Date parsing in Firefox.

I found a good link describing how to format the date properly to parse it here. In essence, it seems to help if you're using the forward slash / rather than the period . as a date separator.

However, I have now tried it with the latest Firefox version 57, but cannot retrace this behavior - the code snippet runs fine without any modification on my PC.

like image 192
Matt Avatar answered Nov 14 '22 21:11

Matt