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

Sudipto
  • 390
  • 1
  • 3
  • 18
  • You mean like what [`jquery.getScript`](https://api.jquery.com/jquery.getscript/) does? See [this](http://stackoverflow.com/questions/6642081/jquery-getscript-methods-internal-process) stackoverflow question. – mellamokb Dec 17 '15 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)... – somethinghere Dec 17 '15 at 11:34

2 Answers2

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 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. – somethinghere Dec 17 '15 at 11:40
  • Other forms of `eval` (like `new Function`) are not really safer than `eval` :) – Quentin Dec 17 '15 at 11:41
  • Yeah, I know, I was just saying that that's another route to go down - unrelated to the safety point made before :) – somethinghere Dec 17 '15 at 11:42
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?

Community
  • 1
  • 1
gyosifov
  • 3,193
  • 4
  • 25
  • 41