user1007817
user1007817

Reputation:

Create/access Javascript global variable created on AJAX call

How do I create a Javascript global variable from an AJAX call? I'm currently getting a undefined error. I've cut the code to just relevant sections. I'll add more if requested.

#index.php
#(Calls form.php)
  if(ajaxRequest.status == 200){
    document.getElementById("response").innerHTML = "<script">; #new
    document.getElementById("response").innerHTML += ajaxRequest.responseText;
    document.getElementById("response").innerHTML += "</script">; #new
  }



#form.php
  print("<script>var message = 'Hello World';</script>");
  print("<input type=\"button\" onClick=\"printMessage()\" />");

#index.js
#(Sent to the browser before AJAX. Executed after AJAX call.)
  function printMessage(){
    alert(message);
  }

Upvotes: 0

Views: 633

Answers (2)

stewe
stewe

Reputation: 42632

The problem is that <script> tags added via innerHTML don't get executed.

Have a look at: Can scripts be inserted with innerHTML?

If you can use JQuery, this would work:

$('#response').html(ajaxRequest.responseText);

You could also create the <script> tag using JavaScript like this:

var ajax_response='var message="Hello World!";';

var sc=document.createElement('script');
sc.text=ajax_response;

document.body.appendChild(sc);

alert(message);

Demo: http://jsfiddle.net/6ChZG/


Something like this should work:

#index.php
#(Calls form.php)
  if(ajaxRequest.status == 200){
    var res=document.getElementById("response");
    res.innerHTML = "<input type=\"button\" onclick=\"printMessage()\" value=\"test\" />";
    var sc=document.createElement('script');
    sc.text=ajaxRequest.responseText;
    res.appendChild(sc);    
  }



#form.php
  print("var message = 'Hello World';");


#index.js
#(Sent to the browser before AJAX. Executed after AJAX call.)
  function printMessage(){
    alert(message);
  }

Demo: http://jsfiddle.net/XbM7v/

Upvotes: 1

web-nomad
web-nomad

Reputation: 6003

Try this:

Replace var message with message. Variables not declared as var .. are added to global scope.

And, call printMessage() after the ajax call completes.

  if( (ajaxRequest.status == 200 ) && ( ajaxRequest.readyState==4 ) ){
    document.getElementById("response").innerHTML = ajaxRequest.responseText;
    //printMessage() call here...
  }

Hope this helps.

Upvotes: 0

Related Questions