Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 1.79 KB  |  hits: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. In a .js file can I update a variable after ajax responsetext is processed?
  2. function getPHPVariable(){
  3. var ajaxRequest;  // The variable that makes Ajax possible!
  4.  
  5. try{
  6.     // Opera 8.0+, Firefox, Safari
  7.     ajaxRequest = new XMLHttpRequest();
  8. } catch (e){
  9.     // Internet Explorer Browsers
  10.     try{
  11.         ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
  12.     } catch (e) {
  13.         try{
  14.             ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
  15.         } catch (e){
  16.             // Something went wrong
  17.             alert("Your browser broke!");
  18.             return false;
  19.         }
  20.     }
  21. }
  22. // Create a function that will receive data sent from the server
  23. ajaxRequest.onreadystatechange = function(){
  24.     if(ajaxRequest.readyState == 4){
  25.          variableIWant = ajaxRequest.responseText;
  26.     }
  27. }
  28. ajaxRequest.open("GET", "phpfile.php", true);
  29. ajaxRequest.send(null);
  30.  
  31. }
  32.        
  33. window.variableIWant = ajaxRequest.responseText;
  34.        
  35. ajaxRequest.onreadystatechange = function() {
  36.     if (ajaxRequest.readyState == 4) {
  37.         variableIWant = ajaxRequest.responseText;
  38.         longString = "The variable I retrieved is: "+variableIWant+". Isn't this nice?";
  39.         document.getElementById('theDivPart').innerHTML = longString;
  40.     }
  41. }
  42.        
  43. ajaxRequest.onreadystatechange = function() {
  44.     if (ajaxRequest.readyState == 4) {
  45.         update(ajaxRequest.responseText);
  46.     }
  47. }
  48.  
  49. function update(value) {
  50.     longString = "The variable I retrieved is: " + value + ". Isn't this nice?";
  51.     document.getElementById('theDivPart').innerHTML = longString;
  52. }
  53.        
  54. <script type="text/javascript">
  55. $.get('http://sumary.org/phpfile.php').done(function(data){
  56.     $(function() {
  57.        $('#theDivPart').html('The variable I retrieved is: ' + data + '. Isn't this nice?');
  58.     });
  59. });
  60. </script>
  61.  
  62. <body>
  63. <div id="theDivPart"></div>
  64. </body>