5

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)};

})
8
  • At a guess, the results of the requests never meet the conditions that lead to assigning c a value. My advice would be to step through with your browser's JavaScript debugger Commented Nov 3, 2017 at 0:10
  • Sorry, I forgot to mention that the issue nly occurs in Firefox, in Chrome it works just fine. Commented Nov 3, 2017 at 0:12
  • Also, I cannot seem to log anything into console. Commented Nov 3, 2017 at 0:13
  • And there's no other errors or messages in the console? Check the Network console. Do the requests resolve successfully? Commented Nov 3, 2017 at 0:15
  • I get this: prntscr.com/h5ixon Commented Nov 3, 2017 at 0:20

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

thanks for your help! I think the issue is in date formatting. when I log endDate and startDate vars in Chrome it shows dates, but in FF says 'invalid date'
That would make sense, especially if the 2 browsers have different date and/or language settings. Try to catch the error inside the formatDate function and handle the different cases there. Or use ISO date format (yyyy-mm-dd), which should be interpreted the same way by each browser (e.g. "2017-11-06 17:42:00"). Omit the time if not required.
The thing is that dates in the feed object are formatted like "06.11.2017". Actually they are strings, not dates, and when they are parsed and inserted into new date object, for some reason they are not recognized as valid dates only in FF, while in Chrome they are.
Sorry for late reply and thanks for your help! I just had to replace dots in formatDate function with '/' due to Firefox's more strict date formatting rules, and it worked.
@wintermute - thank you for the hint, I have updated my answer. Please click on "accept answer" if it is the answer to your issue.
0

Are you sure that you are correctly loading jquery? Try to place the jquery.min.js file in your server and load it from your domain.

1 Comment

Definitely not a jquery issue, I tried it, no change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.