2

Is it Possible to execute a Javascript using AJAX call or calling a specific function in the Javascript.

I am able to display the contents of the Javascript file like "http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first " but not able to execute the javascript.

Is there any way. Actually I am a newbie AJAX

2
  • You mean like what jquery.getScript does? See this stackoverflow question. Commented Dec 17, 2015 at 11:33
  • 1
    You could create and append a script element and set its textContent property to the script you just receive, or use the reviled eval (not advised but it does work)... Commented Dec 17, 2015 at 11:34

2 Answers 2

5

Ajax lets you do two things:

  1. Make a request to the server
  2. Read the response you get back

Anything else happens around that.

If you are, for instance, running NodeJS on the server, then the HTTP request will trigger some server side JavaScript.

If you get JavaScript back from the server, then you'll have that available in a string and you can do whatever you like to it (including passing it through eval()).

Generally speaking, fetching new JS from the server like that is a bad idea. Better to have your JavaScript loaded into your webpage up front and then just trigger it based on data you get back from the server.

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

3 Comments

Please note that it might be unsafe to simply evaluate code, and if you are unsure what your server might send back (or its somewhat user input controlled) then eval is a dangerous option. Just noting it. As a sidenote, you might be able to use a Function constructor to read your code as well.
Other forms of eval (like new Function) are not really safer than eval :)
Yeah, I know, I was just saying that that's another route to go down - unrelated to the safety point made before :)
4

If I am understanding correctly the case here is that the server is returning some javascript code and you like to evaluate it.

You can use the eval() function as described here.

In the example you provided it would be something like:

var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      eval(xhttp.responseText);
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();

But you should be careful, because using eval is not always a good idea. See this SO question: Why is eval a bad idea?

Comments

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.