0

I am trying to create/change a javascript array based on what is return from an ajax call. This is what I am working with so far:

function ajaxCall(code) {
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("POST","ShowBusiness",false);
    xmlhttp.send(code);
    document.getElementById("content").innerHTML = xmlhttp.responseText;
}

and then within that response HTML I have (among other elements)

<script type="text/javascript">
    images = [1, 2, 3];
</script>

However, when I then try to use console.log(images); within a function that was in the original page, it tells me that "images is not defined". I then tried to go back and insert a var images = []; into the head of the original page, but then the console log returns [], not what I hope to change as a result of the ajax call.

Any ideas how I can get around this? I assume that the page is not recognizing the javascript that I am inserting into the page with ajax.

wakey
  • 2,283
  • 4
  • 31
  • 58
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Mouser Aug 10 '15 at 14:42
  • Use json to handle values sent via Ajax. – cre8 Aug 10 '15 at 14:57

2 Answers2

0

Use appendChild() instead :

function ajaxCall(code) {
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("POST","ShowBusiness",false);
    xmlhttp.send(code);
    document.getElementById("content").appendChild(xmlhttp.responseText);
}
Ajay Narain Mathur
  • 5,326
  • 2
  • 20
  • 32
0

Don't think script tags get executed on insertion. Check the answers in this question (or the edit of the original question) for a couple of solutions:

Executing <script> elements inserted with .innerHTML

Community
  • 1
  • 1
cviejo
  • 4,388
  • 19
  • 30