Nadav Y.
Nadav Y.

Reputation: 11

Injecting javascript and HTML using AJAX

First of all I would like to say that while this is the first time i post here these boards have helped me much. With that said, I have got a strange issue regarding AJAX and scripts.

You see, in my web application i used custome JS context menus. Now each of them menus is implemented with specific features depending on the object and if the object exists.

E.x : if we got an upper menu place holder but no upper menu the context menu will have one option which is "add menu". But say we already have the upper menu the context menu will have different options such as "edit menu" etc...

so far so good, however, say we have an upper menu place holder and no menu and then we added the menu (still no refresh on the page) i need to generate a new context menu and inject it right? so i do just that along with the new menu i just built.

all that code goes into the SAME div where the old context menu script and upper menu place holder were so basicaly they are overwriten. Now the menu itself is in HTML so it overrides the current code the JS however acts wierd and will show now 2 context menus the old one and the new one even though i overwrite it's code.

I need to some how get rid of the old context menu script without refreshing the page. Any ideas?

P.S all the JS are dynamicaly generated if that makes any difference (i dont think it does.)

Upvotes: 1

Views: 4394

Answers (4)

GreenTurtle
GreenTurtle

Reputation: 890

Following on from Dutchie432's solution, I think it might be easier to do something like:

  1. create an element that links to your new js as a static file
  2. Delete the old js element

e.g.:

var jsElement = document.createElement('script');
jsElement.setAttribute("type","text/javascript");
jsElement.setAttribute("src", "/static/scripts/script.js");
jsElement.setAttribute("charset", "utf-8");
document.head.appendChild(jsElement);

var oldjs = document.getElementById('my-old-js');
oldjs.remove();

You can also do this with your css.

Upvotes: 0

Nadav Y.
Nadav Y.

Reputation: 1

Thanks for the replies.

Dutchie - that's exactly what I did. now the thing is the HTML is properly overwritten (I didn't use append I overwrote the entire div) and yes the javascript just keeps on caching...

I tried to disable browser cache and still the problem persists i get multiple context menu per item the more I ran the ajax function...

Jan, My AJAX function builds a div tag and script tags and places them into another container div tag in the page.

What's suppose to happen is that every time the AJAX runs the code inside the container div is overwritten and you get an updated version. the div inside the container div is overwritten yet the script tags somehow are cached into the memory and now each time the out jQuery function calls the context menu i get multiple menus...

I don't think code is needed but I will post it tomorrow.

Any ideas?

Upvotes: 0

Dutchie432
Dutchie432

Reputation: 29170

No matter what anyone says, do not use EVAL. It's evil and will give you memory issues if used more than a few times on a page.

See my soluition here: trying to call js code that is passed back from ajax call

Basically, create a div with the ID of "codeHolder" and voila. You'll basically want to pass your HTML and JS back to the AJAX receiver (separated by a separator), parse it on the JS side, display the HTML and put the JS Code in your javascriptCode variable.

//Somehow, get your HTML Code and JS Code into strings
var javascriptCode="function test(){.....}";
var htmlCode="<html>....</html>";

//HTML /////////////////////////////////////////
  //Locate our HTML holder Div
  var wndw=document.getElementById("display");

  //Update visible HTML
  wndw.innerHTML = htmlCode;

//Javascript ///////////////////////////////////
  //Create a JSON Object to hold the new JS Code
  var JSONCode=document.createElement("script");
  JSONCode.setAttribute("type","text/javascript");

  //Feed the JS Code string to the JSON Object
  JSONCode.text=javascriptCode;

  //Locate our code holder Div
  var cell=document.getElementById("codeHolder");

  //Remove all previous JS Code
  if ( cell.hasChildNodes() )
      while ( cell.childNodes.length >= 1 )
          cell.removeChild( cell.firstChild );

  //Add our new JS Code
  cell.appendChild(JSONCode);

//Test Call///////////////////////////////////////
test();

This code will replace all previous JS code you might have put there with the new JS Code String.

Upvotes: 2

Nadav Y.
Nadav Y.

Reputation: 11

Well after some head breaking i figured it out.. (the problem not the solution yet) this is the ajax function right?

$.ajax({
            type: "GET",
            url: "../../../Tier1/EditZone/Generate.aspx?Item=contentholder&Script=true",
            dataType: "html",
            success: function (data) {
                $('#CPH_Body_1_content_holder').html(data);
            }
        });

now they function uses a page with an event handler, that event handler reutnrs the data as followed response.write(answer) it just hit me that when you use response.write it sends the code after it's been compiled and ran in our case at page Generate.aspx.

so the script will run but not in the page i intended it to run and because of that i cannot overwrite it... how silly of me.

what i think ill do it return the data as an actualy string and then and only then inject the code into the container div.

ill let you folks know if that works out. cheers and thanks for the advice these forums rock.

Upvotes: 1

Related Questions