Can a function be returned using AJAX?

Suppose I am in need of initiating an ajax call to my server

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

and upon receiving a response from the server, I send some JavaScript code

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

Is there a way to achieve something similar to this?:

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

Answer №1

Example showcasing the Function() constructor:

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

It is important to note that the functions need to be run inside a string like ${response}; myFunc(x)

Here is an example to demonstrate how this operates:

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

It might be more convenient if you were to send an array in this manner:

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

Then, you could use it like so:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue with displaying data fetched from omdbapi, receiving [object Object] instead

Everything is working perfectly in my code except for the mysterious appearance of [object Object] whenever I perform a search. I've combed through my code multiple times, but I just can't seem to locate the source of this issue. It would be grea ...

The model's function received the error message "Not a valid function."

My project involves NodeJS, Express, and Sequelize(mysql2)... I am encountering an issue where I keep receiving the error message "is not a function". I have created a model and defined a function in the model as shown below: module.exports = (sequelize, D ...

Modify a data value when another one is updated

Within my Vue.js data, I have a component that generates form inputs. You can view a live version of this component here. The data structure is as follows: data: { providerData: { archive_cost: { legend: 'Warehouse cost&apos ...

Inactive users will be automatically logged out after a certain period of inactivity when using

I have an application that utilizes WIF and ADFS for authentication. This application is built in Javascript/jQuery, making use of $.ajax calls to interface with an MVC Web Api. The issue arises when the application remains idle for an extended period (ar ...

Understanding the mechanisms of Promise functionality within Typescript can be challenging, particularly when encountering error messages such as "type void is not

Recently, I've delved into the world of Typescript. Despite my efforts to stay true to the typing system, I've encountered a challenge that forces me to resort to using the any type: The issue arises with a function that returns a promise: sav ...

Challenges of aligning a modal overlay in the middle of mobile screens

Currently, I am developing a website and encountering a specific issue with the modal structure. When viewing it on Codepen using Chrome devtools and toggling the device toolbar to simulate mobile screens, everything appears fine. However, when opening the ...

When utilizing the yo angular-fullstack:endpoint, the message endpoint fails to produce the message.socket.js

Hey there, I've encountered an issue where the yo angular-fullstack endpoint shopPacket is not generating the shopPacket.socket.js file. I attempted to update the yo angular full stack generator, but unfortunately, the problem persists. yo angular-f ...

Incomplete data was retrieved from the localStorage

I am currently in the process of developing a mobile application using Phonegap version 1.4.1. I have encountered an issue on iOS (running on version 5.1) where the app fails to load all data from localStorage. Upon first use of the app, I set a flag in l ...

Retrieve GPS data source details using Angular 2

In my Angular 2 application, I am looking to access the GPS location of the device. While I am aware that I can utilize window.geolocation.watchposition() to receive updates on the GPS position, I need a way to distinguish the source of this information. ...

Display animated GIFs in the popular 9Gag format

Is there a way to display a GIF file after clicking on a JPG file, similar to the functionality on 9Gag.com? I am currently using timthumb.php for displaying JPG images. https://code.google.com/p/timthumb/ Below is the code snippet: <div class="imag ...

Attempting to wipe out a request using ajax to access relationship entities in a ruby on rails framework

I'm currently working on implementing an ajax request to delete a "budget" (known as "orçamento" in Portuguese). These budgets are associated with a "cadastre", where each cadastre can have multiple budgets. Below, you can find the components involve ...

What could be the reason behind the login button not triggering the console message display?

I've decided to delve into web server development on my own and have been tweaking a GitHub repository for ExpressJS with Typescript that I stumbled upon. My initial goal is simple - just to have something displayed on the console when I click the log ...

Leveraging webpack2 for code splitting with the CommonsChunkPlugin

I encountered an issue while using code splitting and the CommonsChunkPlugin. My previous experience with require.js involved files being automatically cached. Additionally, I have configured my webpack with libraryTarget: 'amd'. When looking at ...

Utilizing Node.js: How to access another function within the same controller?

I am facing an issue with accessing one function from another in my code. How can I achieve this? class firstController { firstFunction(req, res) { var stamp = request.query("Select 'ALB'+left(newid(),5)+right(newid(),5)+ left(n ...

Tutorials on separating each element of a JSON array into its individual div

Here is an example of how to display subtopic_id and subtopic_name in separate divs: <div class="myThing"></div> <div class="myThing2"></div> Using jQuery, the following code will retrieve data from getsubtopics.php and populate t ...

Issues encountered when retrieving uploaded files and form data from a form through AJAX and sending it to a Laravel backend

Currently, I am developing a form that contains multiple input fields, including an area for file uploads. Once the user clicks the submit button, my goal is to send the form data via an AJAX POST request to the backend system, which happens to be PHP Lara ...

The initial $.ajax request experiences a failure when the page is first loaded

I'm encountering an issue with my code snippet that pulls configurations from a backend Node server using $.ajax. Strangely, when I visit my page for the first time, I don't receive the response. However, upon checking the server log, I can see t ...

Combining items in JavaScript using a shared key

Is there a way to combine 4 separate arrays of objects into one big object based on the keys inside an object? For example: OUTPUT: What I want to achieve. [ { "bugId": "", "testerId": "", "firstName": "", "lastName": "", "country": " ...

Having difficulty in converting JSON objects into key/value pairs in Angular 7

I have a task to convert my JSON data from its current format as shown below: cacheMapDataDto = [{ "cacheName": "cache_nchl_individual_type", "count": 2, "mapObj": { "NCHL_BI_BATCH_VERIFICATION": false, "NCHL_STL_BATCH_VERIFICATIO ...

Removing a specific item from a Kendo UI dropdown list

Recently, I encountered a predicament with a dropdownlist populated from a datasource. Following a certain event, my goal is to eliminate a single item from the dropdownlist identified by id = 22. Although I recognize this may not be the best practice du ...