1

I'm having a problem with a JavaScript function and a variable.

I'm use AJAX to get values from the server and I've a JavaScript external file that use a variable that is returned by AJAX. The problem is that variable is appears undefined when I try to use this variable inside the external file. The result of the AJAX call is a HTML page that includes this variable used by the external JavaScript file, but when the answer arrives the variable appears in the DOM and if I try to used this variable inside the external JavaScript file I'm getting an error "is not defined".

Example: AJAX CALL

function fillModal(url) {
    var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
        if ((this.readyState === 4) && (this.status === 200)) {
            document.getElementById("dataModal").innerHTML = this.responseText;
        }
    };

    xhttp.open("GET", url, true);
    xhttp.send();
}

Variable used in the external JavaScript file returned by the AJAX reponse

function isOneRowTable(table_name) {
    OneRowTable // This is the name of the variable returned by the AJAX call.
}
Reynier Téllez
  • 531
  • 2
  • 7
  • 19
  • Not sure where OneRowTable is returned from the AJax call.... If there is javascipt in the Ajax call, it does not get evaluated by innerHTML – epascarello Nov 30 '17 at 16:02
  • 1
    Where is this variable defined, where are you setting the variable value? I recommend using `window.OneRowTable` if you are going to spread out your variables like that. – Monstrum Nov 30 '17 at 16:03
  • What is the actual variable? Where do you try to use it? Where do you ever define it? – David Nov 30 '17 at 16:03
  • Most likely a dupe of https://stackoverflow.com/questions/2592092/executing-script-elements-inserted-with-innerhtml – epascarello Nov 30 '17 at 16:04
  • Yes there is JavaScript JavaScript in the Ajax call – Reynier Téllez Nov 30 '17 at 16:06
  • If I define the variable this way window.OneRowTable I'm getting the same error when I try to use the varible. To use the variable I have to put in my code again window.OneRowTable? – Reynier Téllez Nov 30 '17 at 16:19
  • @ReynierTéllez: Instead of vaguely describing your code, perhaps you could provide a demonstrable example of the problem in your question? "I define my variable, but it tells me it's undefined" is unanswerable. If JavaScript is telling you that it's undefined then it's undefined. The system is usually right about these things. We can't tell you what mistake *you've* made unless you can demonstrate the problem. Simply insisting that your code *must* be right and not actually showing it won't get you anywhere. – David Nov 30 '17 at 16:34

0 Answers0