Search code examples
javascriptjqueryajaxevalserializearray

Does serializeArray sanitize input before being passed to eval?


Out of curiosity since eval is "evil". Would serializing an array protect against xxs attacks? From my understanding the serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. If so, what would be a better way to evaluate the data.

var formdata = $('#form').serializeArray();
$.post('https://www.example.com', formdata, function(data) {
    if(data) {
     var buffer = eval('(' + data + ')');
     // do some logic to check for errors
    } else {
      // sumbit the form
    }
});

Solution

  • The variable formdata would contain the "#form" data as an array and will be posted to the server (example.com).

    The server will respond with some data now it's your turn to "do some logic" on the data. Depending on the Server the response will be an string, json or other data formats. At this point I am confused to see the eval call with.

    eval('(' + data + ')');
    

    This is not the way you would usually handle the data of the server and the question would be if you trust the data of the server to plainly eval it.

    Said that it's a better idea to only pass data from the server and receive it as as e.g. JSON and go over the data.

    Often the libraries would handle the JSON parsing and you could access the data and iterate it like you would iterate an object/array in javascript. Since you are using JQuery I would read the documentation of $.post and inspect the servers response in the Browsers Dev Tools.