Jump to content

Refreshing javascript source for AJAX


kael.shipman

Recommended Posts

Hey all,

 

I've gotten really into AJAX over the past year, but my knowledge has holes in it. I need a way to overwrite/refresh variable libraries on the fly.

 

I've got a catalog where the page reloads when you select a product. Instead of that, I'd like to just grab the product information from a back-end php script and fill the product display box (standard AJAX stuff). However, each product comes with a hefty array containing prices and availability for each option. Instead of loading an array that's hundreds of items long (containing all availability for ALL products) into the runtime environment for the script, I'd like to have a php backend for the script source and just change the source every time I change a product. However, in my testing, I haven't found a way to get javascript to refresh its variables. Here's my test:

 

<html>
<head>
  <script id="extScrpt" type="text/javascript" src="jsTest.php?script=1&p=1"></script>
  <script type="text/javascript">
   function chngScript(num) {
    if (num == '') { return; }
    var scrpt = document.getElementById('extScrpt');
    var newSrc = 'jsTest.php?script=1&p='+num;
    alert('changing script from '+scrpt.src+' to '+newSrc);
    scrpt.src = newSrc;
    chkErrs();
   }

   function chkErrs() {
    if (errLog) { //errLog is loaded along with each new library to log errors (surprise surprise) during php execution
     alert('Errors: '+errLog);
    }
   }

   function testScrpt() {
    if (!errLog) {
     alert('PgArray ('+pgArray.length+' Elements): '+pgArray);
    } else {
     alert('Errors on the page are preventing processing.'+"\n"+errLog);
    }
   }
  </script>
</head>
<body>
  <input type="text" onchange="chngScript(this.value);" /> <button onclick="testScrpt();">Test</button>
</body>
</html>

 

These are the Script Sources:

 

<?php
//output using appropriate headers, do security checks, run prelims, etc......


if ($_GET['p'] == 1) {
?>
var errLog = false;
var pgArray = new Array(5);
pgArray[0] = 'cha';
pgArray[1] = 'nah';
pgArray[2] = 'dah';
pgArray[3] = 'fah';
pgArray[4] = 'kah';

<?php } elseif ($_GET['p'] == 2) { ?>
var errLog = false;
var pgArray = new Array(4);
pgArray[0] = 'one';
pgArray[1] = 'two';
pgArray[2] = 'three';
pgArray[3] = 'four';

<?php } else { ?>
var errLog = 'Invalid page!';
var pgArray = new Array(0);

<?php } ?>

 

You change the input box to "1" or "2" and it should change the script source. You hit the button, it should show a toString'd version of pgArray according to what script source is being used. However - as you've probably guessed by now - regardless of what source is there, it continues to display the pgArray that was loaded with the environment.

 

I'm starting to think I was far too lengthy with this description. You probably all knew what I was talking about from the beginning. So any suggestions?

 

By the way, I also tried using the DOM to create a new script element (which worked), but when I tried to delete the old script element to make sure there were no conflicting variables registered before creating another new one, the delete just wouldn't happen.

Link to comment
Share on other sites

Alright, for anyone else who might be having this issue, I made a modification to my earlier code and somehow, it works on Firefox, Safari, and Internet Explorer, which is about 95% of the market and by all means good enough for me. It probably works in the rest, too, as it's nothing complicated or hack-like, but I just don't have the means or the time or the reason to test it.

 

For the record, I'm pretty sure nothing I'm doing is new, but I figured I'd document it here because I always hate it when I finally find a forum question that matches the one I've been searching for and then it doesn't have an answer. If you're pretty up on your AJAX, I wouldn't bother continuing.

 

Anyway, to elaborate on my problem, I'm making my entire site AJAX, but I need to load different javascript function sets depending on the page that's being viewed. I can't just load them all because the site is too big for that, and I value cleanliness over a quick fix. What I had tried to do was simply manipulate the <head> section of the HTML file by deleting the script tag with my page functions in it and replacing it with another with a different source. I had also tried just changing the source, but that didn't work either. Replacing the whole tag did allow me to create the necessary functions (as defined in the new script file), but it didn't delete the old set  of functions, and with enough browsing around, eventually a user could potentially load every function on my site, which - again - is messier than I want it to be.

 

SO. I decided to break it down into libraries (as described in the very useful "best practices" bulletin at the top of this forum). I have a docLib where I store variables that are site wide, like pageID, etc., then I have a small collection of site-wide functions that are just registered under document. These stick with the user throughout. I then load the specific page's functions in by first clearing the pageLib object (declaring pageLib = {}), then establishing the new set of functions as contained by the pageLib object (pageLib.func1 = function(arg1,arg2) { blah blah... }). If I know my javascript, simply clearing the pageLib object effectively frees the system memory to deal with the new set of functions.

 

Using this back-end structure (which is really the meat of the idea), I can load the script files just like before, but instead of the functions being additive or just not loading at all, the old functions are deleted and the new ones are loaded every time.

 

//Javascript File: pageLib.php?p=1

document.pageLib = {}
pageLib.pgGlobalOne = 1;
pageLib.pgGlobalTwo = 2;
pageLib.errLog = false;

pageLib.func1 = function(arg1,arg2) {
var chk = this.chkValidity();
if (!chk) { this.errLog = 'Invalid something or other'; }
return chk;
}

 

<!--HTML File-->
<html>
<head>
  <scirpt type="text/javascript" id="pageLibScript" src="pageLib.php?p=1"></script>
  <script type="text/javascript" id="docLibScript" src="docLib.php?p=1"></script>
  <script type="text/javascript">
   function chngScript() {
    if (docLib) { alert('Error'); return; }
    var pageLibScrpt = document.getElementById('pageLibScript');
    var hed = document.getElementsByTagName('head')[0];
    if (pageLibScrpt) {
     hed.removeChild(pageLibScrpt);
     delete pageLibScrpt;
     var pageLibScript;
    }

    pageLibScrpt = document.createElement('script');
    pageLibScrpt.setAttribute('id','pageLibScript');
    pageLibScrpt.setAttribute('type','text/javascript');
    pageLibScrpt.src = 'pageLib.php?p='+docLib.pgID; //docLib.pgID defined in docLib.php?p=1 (above)
    hed.appendChild(pageLibScrpt);
    chkErrs();
   }

   function chkErrs() {
    if (pageLib.errLog) {
     alert('Errors: '+pageLib.errLog);
    }
   }
  </script>
</head>
<body>
  <button onclick="docLib.pgID = 2; chngScript();">Change Page</button>
</body>
</html>

 

This is obviously a very spare example, but the concept is solid, and it appears to be completely cross-browser.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.