0

I'm trying to generate dynamic variables for my form web page that runs on my Siemens S7-1200 PLC. The issue that I'm having is that as most issues (as far as I've read) is that my xmlhttprequest.responseText is working if I do console.log(xhttp.responseText) but I can't get the value of the responseText into a variable as those stay "undefined". Even when I try putting it into a global variable. I've seen quite a lot of answers with "callback" but I have no idea what this means.

Here's my code:

var json

function refreshVar(){


    if(window.XMLHttpRequest){
        xhttp = new XMLHttpRequest();
    } else {
        xhttp = new ActiveXobject("Microsoft.XMLHTTP");
    }

        xhttp.onreadystatechange = function()
        {
            if(xhttp.readyState == 4 && xhttp.status == 200)
            {   
        console.log(xhttp.responseText);
        console.log(json);
        json = xhttp.responseText;

            }
        }
        xhttp.open("GET", "IOCounter.html",false); 
    xhttp.send();

}

and here's an image of the result in the console:

https://i.stack.imgur.com/zUHNM.png

in the "xhttp.open()" function I've both tried false and true and there was no difference. I've also tried getting a "return(xhttp.responseText)" which didn't work either

The function is also ran in a repeating loop every 30ms so it updates more than enough. Keep in mind this isn't the whole code and some stuff is censored due to secrecy of my company.

I hope I'll get some help soon!

Thanks already!

ZF007
  • 3,708
  • 8
  • 29
  • 48
Wouterkdc
  • 1
  • 1
  • You log `json` *before* you assign to it, so it will indeed be undefined. Assign then log. – Alex K. Apr 17 '19 at 12:40
  • Omg I totally overlooked this. Now I can export it! thank you! only issue is that I can't convert it to a json using JSON.parse() - any way I can fix this? [EDIT] I get the "invalid character" error – Wouterkdc Apr 17 '19 at 12:51
  • @Wouterkdc — JSON.parse converts **from** JSON, not to it. If the JSON is invalid. It is invalid. There's not enough information in your question to tell why or how to fix it. – Quentin Apr 17 '19 at 13:02
  • Looks like the input string is enclosed in single quotes, you would need to remove them first: `var json = JSON.parse(xhttp.responseText.substr(1, xhttp.responseText.length - 2))` – Alex K. Apr 17 '19 at 13:03
  • They aren't needed? I added them manually so I can just remove this. I read that needs those to be able to get converted to a json. – Wouterkdc Apr 17 '19 at 13:06
  • They should not be there if the json is in a variable. – Alex K. Apr 17 '19 at 13:08
  • Lovely now that works, issue now is that I'm currently unable to do json.Pol1 as it gives me a value "undefined" any idea how that is happening? – Wouterkdc Apr 17 '19 at 13:18

0 Answers0