2

Through a Javascript request, XMLHttpRequest responds with some additional Javascript that needs to be added to the page the requesting page.

Using eval(), if the response is something like:

alert('This is the js response');

... then this works just fine.

However, the text returned could look something like this:

<script language="javascript">var checkVar='checkVar: value 1';</script>

but most likely:

<script src="http://www.somesite.com/setCheckVarValue.js"></script> 

... where additional JS needs to be loaded on the page.

I have ensured that the XMLHttpRequest is synchronous, as I want to reference checkVar right after this.

So:

<script type="text/javascript" src="http://www.mysite.com/addJSToPage.js" />
// at this point, since this is a synchronous call, page processing waits
// until the response is received that needs to include the additional JS
// to load; this, for testing sets the value of checkVar

<script type="text/javascript" >
    alert(checkVar);
</script>

The alert message should read "checkVar: value 1".

For other reasons, this is not just as simple as setting var checkVar in addJSToPaged.js, so I'm not looking for that kind of recommendation.

I'm using alert(checkVar) simply as a test to ensure that a value has been set through JS in the response.

I suppose that I could strip out the beginning and ending script tags and keep the eval() way of doing it. However, I would like to know if there are any solutions that support what I'm looking for?

Thanks.

UPDATE

Following Prashanth's suggestion, in addJSToPage.js I added:

var dynamicElement = document.createElement('div');

Then in the response from the XMLHttpRequest, I did:

dynamicElement.appendChild = xmlhttp.responseText;

Still not seeing the value of checkVar.

4
  • you might need to inject that into the DOM, eval is evil. In this case you might need to respond with the message and do a alert on the response text. Commented Feb 2, 2012 at 6:11
  • @Prashanth - It's not as simple as just as an alert; updated the description, as the response will be a JS reference to load more JS. Commented Feb 2, 2012 at 6:33
  • right, inject it into the dom and you can call the function. I couldn't think of a valid use case where you would need to respond with just javascript. Commented Feb 2, 2012 at 7:23
  • 1
    Updated above, however still no go. Can you please provide an example? Commented Feb 2, 2012 at 7:44

3 Answers 3

4

Ignoring the fact that whatever you are doing is probably a bad idea, Prashanth has the right idea of inserting it into the DOM. you could also strip out the tags and just eval as "normal".

Not ignoring the fact that 1) eval is evil, 2) dynamically loading remote code is bad and 3) synchronous AJAX is extra bad, I have this to say:

Unless you know what you are doing, evaling anything is a bad idea, its hard to debug, can expose massive security flaws and all sorts of other nasties. You then compound this by loading remote code, which is apparently generated in a way outside of your control because you aren't able to get just the script. Synchronous Ajax is bad because there is only one thread in javascript, blocking on Ajax will literally lock up the entire page until it is loaded because even things like scrolling generate javascript events, which the currently busy engine has to check for handlers. While the request goes fast on your local machine, someone with a slow or poor quality connection could be waiting a while, up to the timeout time for the connection. The 'A' in AJAX is asynchronous, and for a good reason, use the callbacks, they are there for a reason.

If you are just doing data passing, use JSON, which is JavaScript Object Notation, a simple data format that happens to also be valid JavaScript. You can use eval on it, but I suggest a JSON parser, i think most modern browsers have them built in (could be wrong here). JSON is good because it can express complex data structures, is simple to generate and parse and is widely supported.

Sign up to request clarification or add additional context in comments.

3 Comments

I understand what you're saying. I initially was using the asynch method, but as I mentioned, I want to ensure that the response text (which is a JS ref) is executed.
In addition to this, I see an issue with eval() as it will only let you execute script from your own domain. I think that integrating jQuery's getScript() may be a better solution and avoid many of the pitfalls discussed.
Come to think of it, it's not just a Javascript include that could be added. Essentially, I need to be able to inject whatever additional HTML (could be full javascript with tags) onto a page from Javascript. Prashanth's option may be the way to go.
2

Recapping - the need is present to be able to dynamically load some content onto a page after/during load, and have it execute. By execute, I don't just mean change the text on some div - that's easy. But if we want to load some new JS dynamically, say an alert that comes from some outside source, and inject it, along with it's script tags, and maybe some other HTML code, then the solution is to use the following jQuery call:

jQuery(dynamicResponse).appendTo('body');

dynamicResponse comes from an asynchronous $.ajax({}) or XmlHttpRequest response. Once present, it is appended onto whatever DOM element, specified in appendTo() and executed.

Comments

1

Here is the example

var script = document.createElement("script");
//innerHTML can be the response from your server. But send the text with script tag.
script.innerHTML = "var foo = function(){console.log('injected into the DOM')}" 
document.body.appendChild(script) // insert into the DOM
foo() // call the function 

1 Comment

In further clarification, I posted this: stackoverflow.com/questions/9125163/… . It may not just be a JS function, but loading a JS library, or image, etc. Any advice?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.