Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send js function through AJAX

I would like to pass "a javascript function" to my backend and I'm using ajax. This is a short example:

var data = { 
    prop: function (e) { alert(e) }
};
ajax.(..., data: data, dataType: "json")...

This automatically removes the prop from the data because it's a function.

How can I pass this function to my backend with json? Without converting it to a string.

like image 291
Mr.Orange Avatar asked Nov 28 '25 20:11

Mr.Orange


1 Answers

You really don't want to send a function from the client to the server and execute that function on the server, not without a lot of security checks. Think about it for a moment, remembering that you can't trust anything you receive from the client. Separately, the server should already know how to do the things it needs to do; usually what you'd do instead is send a command (a string) telling it to use that function (which it would already have, and thus you could trust).

But, if you want to go ahead and do that anyway:

Without converting to string.

You can't. The only way is to send the function as source code or some other form that can be sent via HTTP, which is ultimately a text-based protocol. So you'd send source code, or you'd compile it to some kind of bytecode of your own devising and then send that (converted to a string, probably Base64 or similar), etc.

As of ES2015, normal functions are required to have a toString that takes the form of a valid function declaration or expression, so you could send that string:

var dataToSend = {prop: data.prop.toString()};
ajax(..., data: JSON.stringify(dataToSend), dataType: "json")

The server would then have to compile that string and execute the result. JavaScript provides a way to do that (eval), but again: It's very dangerous to execute code received from the client. Doing very dangerous things requires doing a lot of safety checks first.

like image 139
T.J. Crowder Avatar answered Dec 02 '25 05:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!