-3

I want to run javascript codes from ajax response. For example, I want to show the result via a modal. If I use eval() function, will there be any security issue?

1 Answers1

2

DO NOT USE EVAL

  • Malicious code: invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username.
  • Terribly slow: the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings! Using eval is orders of magnitude slower than normal JavaScript code.

Info source: https://www.digitalocean.com/community/tutorials/js-eval

Proper solution

Assuming you're using jQuery, you should use ajax callback functions to perform operations after you get the response, like so:

function callback(data) {
   /* Here goes the code you want to run after the request is done.
      The 'data' parameter represents your response data */
}

$.ajax({
   url: "your-endpoint-url"
}).done(callback);

For further documentation check official docs: https://api.jquery.com/jquery.ajax/

Vanilla JS

If you're using vanilla JS here you have an example:

var req = new XMLHttpRequest();
req.open('GET', 'your-endpoint-url', true);

function callback(data) {
  if (req.readyState == 4) {
     if(req.status == 200){
         // Here goes your code if the request returns a 200 status code
     }
  }
};

req.onreadystatechange = callback;
req.send(null); 

For further documentation check: https://developer.mozilla.org/es/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Marc Hernández
  • 318
  • 1
  • 7