Home > Software design >  Is it possible return an function with AJAX?
Is it possible return an function with AJAX?

Time:12-04

Let's assume I need to make an ajax call to my server

$.ajax({
    type: 'POST', 
    url: 'url/url', 
    success: function(response){}
});

and as a response from the server I reply with some javascript code

res.send("const myFunc = (b) => { console.log(b) }");

Is there a way to do something like this?:

$.ajax({
    type: 'POST', 
    url: 'url/url', 
    success: function(response){ 
        response('hello'); //I would like 'hello' to appear in the console
    }
});

CodePudding user response:

Example with Function() constructor:

$.ajax({
    type: 'POST', 
    url: 'url/url', 
    success: function(response){
        const fn = new Function('x', `${response}; myFunc(x)`)
        fn('hello')
    }
});

Notice that you have to run the functions inside the string hence ${response}; myFunc(x)

Here is example of how this works:

const code = 'const myFunc = (b) => { console.log(b) }'
const fn = new Function('x', `${code}; myFunc(x)`)
fn('Hello')

It could be easier if you would send array like that:

res.send("b", "console.log(b)");

You could then use it like this:

$.ajax({
    type: 'POST', 
    url: 'url/url', 
    success: function(response){
        const fn = new Function(...response)
        fn('hello')
    }
});
  • Related