-3

I'm makig REST API requests from which i would like to get some data and output it on website.

I made a for loop which starts gathering all the data but the problem is that data is not outputed on website.

I checked with Chrome tools and under network tab all of the items are successfuly received but not inserted onto webpage.

JS code

$(document).ready(function(){
    // ARRAY FOR ITEMS
    var items = [];





    /* ***********************************************
    HVAC_VALVE01_SCHED01 - READ
    **************************************************
    */

    for(var r = 1; r < 11; r++) {
    var request = $.ajax
    ({
        type       : "GET",
        url        : "http://localhost:8080/rest/items/HVAC_VALVE01_SCHED" + r + "_ONOFF/state"
    });

    request.done( function(data) 
    {

        if(data == "ON") {
            $('.HVAC_VALVE01_SCHED' + r + '_ONOFF').prop('checked', true);
        } else {
            $('.HVAC_VALVE01_SCHED' + r + '_ONOFF').prop('checked', false);
        }

        items["HVAC_VALVE01_SCHED" + r + "_ONOFF"] = data;
    });

    /* */

    var request = $.ajax
    ({
        type       : "GET",
        url        : "http://localhost:8080/rest/items/HVAC_VALVE01_SCHED" + r + "_URA/state"
    });

    request.done( function(data) 
    { 
        $(".HVAC_VALVE01_SCHED" + r + "_URA").val(data);
        items["HVAC_VALVE01_SCHED" + r + "_URA"] = data;
    });

    /* */

    var request = $.ajax
    ({
        type       : "GET",
        url        : "http://localhost:8080/rest/items/HVAC_VALVE01_SCHED" + r + "_MINUTA/state"
    });

    request.done( function(data) 
    { 
        $(".HVAC_VALVE01_SCHED" + r + "_MINUTA").val(data);
        items["HVAC_VALVE01_SCHED" + r + "_MINUTA"] = data;
    });

    /* */

    var request = $.ajax
    ({
        type       : "GET",
        url        : "http://localhost:8080/rest/items/HVAC_VALVE01_SCHED" + r + "_PO/state"
    });

    request.done( function(data) 
    { 

        if(data == "ON") {
            $(".HVAC_VALVE01_SCHED" + r + "_PO").css('background', 'blue');
            items["HVAC_VALVE01_SCHED" + r + "_PO"] = "ON";
        } else {
            $(".HVAC_VALVE01_SCHED" + r + "_PO").css('background', 'black');
            items["HVAC_VALVE01_SCHED" + r + "_PO"] = "OFF";
        }
    });

    /* */

    var request = $.ajax
    ({
        type       : "GET",
        url        : "http://localhost:8080/rest/items/HVAC_VALVE01_SCHED" + r + "_TO/state"
    });

    request.done( function(data) 
    { 

        if(data == "ON") {
            $(".HVAC_VALVE01_SCHED" + r + "_TO").css('background', 'blue');
            items["HVAC_VALVE01_SCHED" + r + "_TO"] = "ON";
        } else {
            $(".HVAC_VALVE01_SCHED" + r + "_TO").css('background', 'black');
            items["HVAC_VALVE01_SCHED" + r + "_TO"] = "OFF";
        }
    });

    /* */

    var request = $.ajax
    ({
        type       : "GET",
        url        : "http://localhost:8080/rest/items/HVAC_VALVE01_SCHED" + r + "_SR/state"
    });

    request.done( function(data) 
    { 

        if(data == "ON") {
            $(".HVAC_VALVE01_SCHED" + r + "_SR").css('background', 'blue');
            items["HVAC_VALVE01_SCHED" + r + "_SR"] = "ON";
        } else {
            $(".HVAC_VALVE01_SCHED" + r + "_SR").css('background', 'black');
            items["HVAC_VALVE01_SCHED" + r + "_SR"] = "OFF";
        }
    });

    /* */

    var request = $.ajax
    ({
        type       : "GET",
        url        : "http://localhost:8080/rest/items/HVAC_VALVE01_SCHED" + r + "_CE/state"
    });

    request.done( function(data) 
    { 

        if(data == "ON") {
            $(".HVAC_VALVE01_SCHED" + r + "_CE").css('background', 'blue');
            items["HVAC_VALVE01_SCHED" + r + "_CE"] = "ON";
        } else {
            $(".HVAC_VALVE01_SCHED" + r + "_CE").css('background', 'black');
            items["HVAC_VALVE01_SCHED" + r + "_CE"] = "OFF";
        }
    });

    /* */

    var request = $.ajax
    ({
        type       : "GET",
        url        : "http://localhost:8080/rest/items/HVAC_VALVE01_SCHED" + r + "_PE/state"
    });

    request.done( function(data) 
    { 

        if(data == "ON") {
            $(".HVAC_VALVE01_SCHED" + r + "_PE").css('background', 'blue');
            items["HVAC_VALVE01_SCHED" + r + "_PE"] = "ON";
        } else {
            $(".HVAC_VALVE01_SCHED" + r + "_PE").css('background', 'black');
            items["HVAC_VALVE01_SCHED" + r + "_PE"] = "OFF";
        }
    });

    /* */

    var request = $.ajax
    ({
        type       : "GET",
        url        : "http://localhost:8080/rest/items/HVAC_VALVE01_SCHED" + r + "_SO/state"
    });

    request.done( function(data) 
    { 

        if(data == "ON") {
            $(".HVAC_VALVE01_SCHED" + r + "_SO").css('background', 'blue');
            items["HVAC_VALVE01_SCHED" + r + "_SO"] = "ON";
        } else {
            $(".HVAC_VALVE01_SCHED" + r + "_SO").css('background', 'black');
            items["HVAC_VALVE01_SCHED" + r + "_SO"] = "OFF";
        }
    });

    /* */

    var request = $.ajax
    ({
        type       : "GET",
        url        : "http://localhost:8080/rest/items/HVAC_VALVE01_SCHED" + r + "_NE/state"
    });

    request.done( function(data) 
    { 

        if(data == "ON") {
            $(".HVAC_VALVE01_SCHED" + r + "_NE").css('background', 'blue');
            items["HVAC_VALVE01_SCHED" + r + "_NE"] = "ON";
        } else {
            $(".HVAC_VALVE01_SCHED" + r + "_NE").css('background', 'black');
            items["HVAC_VALVE01_SCHED" + r + "_NE"] = "OFF";
        }
    });
}

});

I really don't know what to do so i would appreciate any help.

With best regards,

Jan Keber
  • 327
  • 1
  • 2
  • 8
  • 1
    Welcome to Stack Overflow! The full content of your question must be **in** your question, not just linked. Links rot, making the question and its answers useless to people in the future, and people shouldn't have to go off-site to help you. Put a [mcve] **in** the question, ideally using Stack Snippets (the `<>` toolbar button) to make it runnable ([here's how to do one](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-do-a-runnable-example-with-stack-snippets-how-do-i-do-tha)). More: [*How do I ask a good question?*](/help/how-to-ask) – T.J. Crowder Feb 15 '18 at 11:05
  • 1
    I would also suggest you research DRY principles, as all those requests can be made using a loop – Rory McCrossan Feb 15 '18 at 11:09
  • Thank you for editing the code in to the question. Your issue is because you're overwriting the `request` variable before each previous request returns any data - remember the requests are asynchronous – Rory McCrossan Feb 15 '18 at 11:10

2 Answers2

1

There's a couple of issues here. The main issue is that you're overwriting the value of request with each new call. As the requests themselves are asynchronous the reference to the previous request is lost. Secondly, you're attempting to store key/value pairs in an array, which will not work in JS. I'd suggest storing an array of objects instead.

Also note that you can make the logic much more succinct by using another loop for each suffix to the request URL, something like this:

$(document).ready(function() {
  var items = [];
  var types = [{
      suffix: '_ONOFF',
      handler: function(data, $el) {
        $el.prop('checked', data == 'ON');
      }
    },
    {
      suffix: '_URA',
      handler: function(data, $el) {
        $el.val(data);
      }
    },
    {
      // ...
    }
  ];

  for (var r = 1; r < 11; r++) {
    var result = {};
    types.forEach(function(type) {
      var key = `HVAC_VALVE01_SCHED${r}${type.suffix}`;
      $.ajax({
        type: "GET",
        url: `http://localhost:8080/rest/items/${key}/state`
      }).done(function(data) {
        type.handler(data, $('.' + key));
        result[key] = data;
      });
    });
    items.push(result);
  }
});

Note that it would be unsafe to work with the items array until all the AJAX requests have completed. To achieve that you can store the deferred objects returned from the $.ajax call in their on array then apply() that to $.when. See this question for more information on that.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thank you. This should work for me but i have a followup question. If a suffux is "ONOFF" it's output should be sent to checkbox but if it's "URA" or "MINUTA" it needs to be send to input box. How can i do that? – Jan Keber Feb 15 '18 at 11:43
  • Ah yes. In that case I'd change `suffixes` to an array objects which contain the suffix as a string, and the handler function to execute your logic when the AJAX request completes. – Rory McCrossan Feb 15 '18 at 11:44
  • I've updated the answer to give you a rough example. – Rory McCrossan Feb 15 '18 at 11:49
  • I really appreciate all of your help and i have one last question. Where suffixes are PO, TO, SR it needs to change color in CSS. If it's on then blue if it's off then black. I tried something with if statements but nothing is working. – Jan Keber Feb 15 '18 at 12:25
  • You can do that in the `handler` function. I'd suggest using `toggleClass()` and putting the styling in CSS. – Rory McCrossan Feb 15 '18 at 12:35
  • I tried something like this, `{ suffix: '_PO', handler: function(data, $el) { if(data == "ON") { $el.css('background-color', 'blue'); } else { $el.css('background-color', 'black'); } } },` – Jan Keber Feb 15 '18 at 12:43
  • That seems like it should work. I'd start a new question about that logic, showing the relevant HTML and CSS too, if you can – Rory McCrossan Feb 15 '18 at 12:52
  • Everything works. Now i have trouble reading those values. items["HVAC_VALVE01_SCHED1_ONOFF"] won't work. – Jan Keber Feb 15 '18 at 14:35
0

The reason is nicely summed up in this comment:

'Than you for editing the code in to the question. Your issue is because you're overwriting the request variable before each previous request returns any data - remember the requests are asynchronous' - @Rory McCrossan

Try to either naming your variables differently, isolating them in their own scope or using the request object directly after the construction.

Different names:

var request1 = $.ajax({ ... });
request1.done(data => { ... });

var request2 = $.ajax({ ... });
request2.done(data => { ... });

// Etc.

Scope isolation:

(function (ajax, data) {
    var request = $.ajax(ajax);
    request.done(data);
})(
    { .. /* ajax object */ ..},
    data => { .. /* data function */ ..},
)
(function (ajax, data) {
    var request = $.ajax(ajax);
    request.done(data);
})(
    { .. /* ajax object */ ..},
    data => { .. /* data function */ ..},
)

// Etc.

Request object directly:

$.ajax({ ... })
.done(data => { ... });

$.ajax({ ... })
.done(data => { ... });

// Etc.
scagood
  • 784
  • 4
  • 11