sending JSON data along with functions through AJAX

I am looking to rejuvenate functions that are passed through AJAX, like below:

//AJAX response:
{"foo":"bar","baz":"function(){console.log('I am back working as a function!');}"}

It's important that baz is treated as a function and not a string. How can I accomplish this?

Answer №1

To achieve what you need, Jozef's suggestion of using the eval() function is an option.

However, it's important to note that many sources advise against using eval():

  1. This post discusses why eval() can be considered risky
  2. When is JavaScript's eval() not evil?
  3. More insights on the dangers of eval()
  4. Exploring why using eval() in JavaScript is discouraged

A more secure alternative recommended by this blog () involves utilizing Function instead:

let json = {"foo":"bar","baz":"function(){console.log('I am back working as a function!');}"};

let func = new Function("console.log('I am back working as a function!');");
func();

If modifying the JSON data isn't possible, the str.replace() method could serve as an alternative.


Cautiously considering the potential risks associated with executing arbitrary code is crucial. It is highly advised to implement whitelisting measures to ensure only predetermined functions are executed. Instead of directly responding with a function, consider following this approach for enhanced security:

function func1() {
  console.log('I am back working as a function!');
}

function func2() {
  console.log('another code block');
}

let json = {"foo":"bar","baz":"1"};

switch(json.baz) {
  case "1": func1();break;
  case "2": func2();break;
  default: console.error("Invalid response");
}

This guidance aims to provide a safer implementation.

Answer №2

It is indeed possible to achieve the desired outcome, however, caution must be exercised when utilizing the potentially risky eval function.

var ajaxResponse = {"foo":"bar","baz":"function(){console.log('I am back working as a function!')}", "lambda": "() => console.log('Hello i\\'m a lambda')"};

function isAFunction(v) {
    try {
        eval("var f = " + v);
        return typeof f === "function";
    } catch (e) {
        return false;
    }
}

var result = Object.entries(ajaxResponse).reduce((obj, [key,value]) => {
      if (isAFunction(value)) {
          eval("obj[key] = " + value);
      } else {
            obj[key] = value;
      }
      return obj;
      
}, {});

result.baz();
result.lambda();

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

Using a button click to toggle the vue-ctk-date-time-picker in VueJS

Currently, I am utilizing the Vue component - https://github.com/chronotruck/vue-ctk-date-time-picker within my own component. However, I am encountering an issue where I would like to maintain the component's original functionality while having a but ...

submitting URL from dropdown menu without using the 'submit' button

My situation involves a dropdown list: @Html.DropDownList("InnerId", Model.GroupDropDownList, new { @class = "select_change" }) I am looking to achieve submitting the value when a user clicks on the selection without needing to select and then use a subm ...

Struggling to uncheck all selected boxes using jQuery

I've attempted various methods, but I'm unable to create code that will uncheck or clear all checkboxes once they have all been selected. Here is the latest version of my code... $(".select_all").click(function(){ var state = ($(this).html( ...

What steps can be taken to avoid activating CORS while performing a POST request?

I am submitting form data and I do not want CORS to be triggered when I make the HTTP request. Currently, I am using jQuery's $.ajax method as follows: $.ajax({ method: "POST", url: url, data: e.serialize(), cache: false, dataTyp ...

When you print document.getElementById('idname').value, it only displays [object HTMLInputElement]

Currently, I have a Tamper-monkey script in place that is designed to scrape specific text from a single page. The script's job is to extract the values of three buttons named pick_0, pick_1, and pick_2 from the page and display them in a designated b ...

Ruby: issue with CSV formatting causing errors when trying to convert to JSON

I am attempting to transform a csv file containing incident codes along with their descriptions into a json file using the code provided below. require 'csv' require 'json' csv = File.open('incidentCodes.json').read CSV.pars ...

Tips for using variable arguments in Meteor's find method

Why is the find query not returning any data when using the "qnum" variable argument as a value? Could it be due to the scope limitation of variables inside an object? Quiz.js file Questions = new Mongo.Collection("questions"); if (Meteor.isClient) { ...

repeated firing of keydown event in ReactJS

Having an issue with adding an event listener and checking if it's level 1. When I press the space key once, it seems to fire more than 50 times. Any assistance would be greatly appreciated. document.addEventListener("keyup", function(e) { if(l ...

Upload files via Ajax request is required

I am in the process of trying to upload a binary file to a server while avoiding a full page refresh when the server responds. I must admit, I am not well-versed in this area and I understand if my approach needs some adjustments. This is how I have appro ...

Using VueJS for Dynamic Class Binding

Using Vue version 3.0.5. I have a component named Cube.vue where I am attempting to dynamically assign a blue or green class to a child element. The component has been created and imported into a specific page, however, I am facing issues getting the con ...

Guide to emitting a value using the composition API

I'm currently working with a datepicker component that is part of a form in my Vue3 app using the composition API. My challenge is how to pass a value from the datepicker component back up to the form component. Unfortunately, I've encountered ...

Structuring React Router: Implementing function passing

I am relatively new to reactjs and I am curious if there is a simple way to display information from the same component on different routes. In the code snippet below, I have two functions that return divs containing text. However, rendering them directly ...

The video playback encountered an issue. Unable to access properties of undefined while attempting to play the video

I am facing an issue with my video gallery where I can't seem to play one video at a time. Instead, I keep getting this error message: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'play'). I suspect it may be ...

An easy way to create an input field after clicking a button

When I try to add a field on Button Click, the default field is not showing and does not get added upon button click I have put in my best effort but I cannot figure out what the problem is. I have added functions and used Math to generate a unique id. Th ...

The second pop-up modal fails to appear

I have successfully implemented 2 modal windows with the help of bootstrap. The first modal is used for adding a user to the database, and the second one is meant for editing an existing user. While the first modal works perfectly fine, the editing modal d ...

The class functions perfectly under regular circumstances but ceases to operate once it is initialized

I'm currently developing a bluetooth remote in React Native. The issue I am facing is that my BLE class works perfectly on its own, but certain sections of code seem to malfunction when implemented within another class. import BLE from './Core/BL ...

Encountering a 404 (Not Found) error when attempting to make an API call in React JS with Azure MVC

When trying to make a POST API call from my React app to an Azure MVC controller, I encountered an error in the console: POST http://localhost:3000/api/SampleData/AcknowledgeRole 404 (Not Found) This error is puzzling because I have clearly defined the ...

Guide on Incorporating Coffeescript into the Node.js Blueprint Framework

Have you checked out Skeleton (https://github.com/dstroot/skeleton) yet? It appears to be a robust framework for node.js, offering all the middleware you need. However, it seems to lack support for coffee script. How can we incorporate it into our project? ...

What is the answer to this issue where the entity name is required to directly come after the "&" in the entity reference?

Whenever I insert the code into my Blogger platform, an error pops up stating: The entity name must directly follow the '&' in the entity reference Here is the code: <script> if (typeof bc_blocks == "undefined" && wind ...

The method for retrieving a generic type property within a dynamic interface

Is there a way to access a dynamic T property within an interface in order to enhance its typing for generic functions like this: type AnotherType<T extends {}> = T & { prop: boolean; prop2: string; }; interface SpecialInterface<T> ...