Transmit a JavaScript object using the $.ajax method

My goal is to pass a complex JavaScript object like the one below through a $.ajax request :

 var o = {
   a: 1, 
   b: 'dummy string', 
   c: ['a', 1, {}], 
   d: {dd: 1}, 
   e: new Date(), 
   f: function() {
        console.log('here');
   }
}

I am aware that I usually need to use JSON.stringify before sending it to my php script. However, JSON.stringify tends to remove properties it can't stringify :

JSON.stringify(o);

returns this ->

"{
  "a":1,
  "b":"dummy string",
  "c":["a",1,{}],
  "d":{"dd":1},
  "e":"2015-11-13T21:34:36.667Z"
}"

But what if I want to store the JavaScript object "o" as plain text in a MySQL column like this :

o = {
   a: 1, 
   b: 'dummy string', 
   c: ['a', 1, {}], 
   d: {dd: 1}, 
   e: new Date(), 
   f: function() {
        console.log('here');
   }
}

Answer №1

Here is a suggestion you can test out:

const obj = {
   property1: 'value1', 
   property2: 123, 
   property3: ['a', true, {}], 
   property4: {prop: 'example'}, 
   property5: new Date(), 
   property6: function() {
        console.log('testing');
   }
};

obj.property6 = obj.property6.toString();
const stringifiedObj = JSON.stringify(obj);
document.getElementById('output').innerHTML = stringifiedObj;

Fiddle: http://jsfiddle.net/abcdefg/

You may need to adjust the code to prevent overwriting functions when executing it. This quick example shows how properties are included in the resulting string.

As mentioned by a user named coder123 in the comments above, here's an illustration of using the replacer argument with JSON.stringify:

const obj = {
   property1: 'value1', 
   property2: 123, 
   property3: ['a', true, {}], 
   property4: {prop: 'example'}, 
   property5: new Date(), 
   property6: function() {
        console.log('testing');
   }
};

function customReplacer (key, value) {
  if (typeof value === "function") {
    return value.toString();
  }
  return value;
}

const modifiedStringifiedObj = JSON.stringify(obj, customReplacer);
document.getElementById('output').innerHTML = modifiedStringifiedObj;

Fiddle: http://jsfiddle.net/abcdefg/1/

Answer №2

Two general options for handling JSON formatting:

You have the option of creating a custom toJSON method for any object:

Function.prototype.toJSON=function(){return String(this);}; 

JSON.stringify({a:1, b:function(){alert(123)}});

This approach results in the function being converted to a string, as shown here:

{"a":1,"b":"function (){alert(123)}"}

An important consideration is that the function literal is treated as a string rather than a function. To address this issue, you can utilize a reviver parameter with JSON.parse() if necessary.

Alternatively, a more effective solution involves using a replace argument with JSON.stringify():

JSON.stringify({a:1, b:function(){alert(123)}}, function(k,v){
  if(typeof v==="function") return String(v);
  return v;
});

As depicted above, this method yields the following output:

{"a":1,"b":"function (){alert(123)}"}

This technique stands out because it does not require modifications to built-in or instance objects.

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

I want to search through an array of tuples to find a specific value in the first index, and if there is a match, I need to return the value in the second index of the matching tuple

I am dealing with an array of tuples: var tuparray: [string, number][]; tuparray = [["0x123", 11], ["0x456", 7], ["0x789", 6]]; const addressmatch = tuparray.includes(manualAddress); In my function, I aim to verify if the t ...

Enhancing quiz results with intricate input forms using JavaScript

I am currently working on an online quiz and the code is functioning properly. However, I would like to display the scores of each user. As a beginner in Javascript, I have been developing this quiz for a friend, and it has been a learning experience for m ...

Clicking buttons in AngularJS

I've developed a button that, when clicked, triggers an AJAX call and binds the server response obtained through AJAX to a table using AngularJS. The issue I'm facing is that the data should appear on the webpage on the first click of the button, ...

Setting a pre-selected value in a Vue.js dropdown list involves a few simple steps. This

Currently, I am developing two Vue components. I am sending array data from the parent component to the child component using props. Now, I have a requirement to pre-select a value in the dropdown list of the child component. Below is a snippet of my code ...

Python Eve encountering WSGI issue [Errno 32] causing a broken pipe during an Ajax call

As I operate a simplistic wsgi server, from run import app if __name__ == "__main__": app.run(threaded=True, debug=True) When I send a get request to the server, it responds with a 200 message but no data. An error message is displayed: Error on r ...

Develop a regular expression tailored for jQuery validation purposes

I'm working with jQuery validation in my web form and I need to validate a text field with specific criteria: 1. Must contain a number. 2. The letters 'a' or 'A', 'b' or 'B' are allowed after the number. 3. Th ...

When you press multiple buttons, the correct button will reveal an image while the incorrect buttons will display an X

Could you lend a hand with the code below? Your assistance is truly appreciated :). Thank you in advance. I need help setting up a functionality where clicking on the correct button (e.g. H) will display a checkmark and a forward link image. If the user c ...

What are the steps to integrating a repository into the clean architecture design pattern?

I have been following Uncle Bob's clean architecture principles in developing my medical application's API. However, I am facing some challenges in determining where certain components should be implemented. Within my application layer, I have a ...

What is the best way to sort items in an array in React based on their length being below a specific number?

I am attempting to utilize the filter() method in order to filter out items from an array if the length of the array is below a certain amount, within the context of ReactJS. Unfortunately, I have not yet succeeded in achieving this. Sample Code: class T ...

Express.JS failing to save data to file when using NeDB

Currently, I am developing a bulk import feature for my personal password manager and I have encountered a problem. The issue arises when trying to import an array of passwords using the forEach() method to iterate through each one. After calling the inse ...

Learn how to effortlessly move a file into a drag-and-drop area on a web page with Playwright

I am currently working with a drag-zone input element to upload files, and I am seeking a way to replicate this action using Playwright and TypeScript. I have the requirement to upload a variety of file types including txt, json, png. https://i.stack.img ...

Displaying JavaScript values one by one using a for loop and alert

Having an issue with looping through a JSON array in JavaScript. I am trying to extract only SG_J1001 and SG_LS01, but it's not working as expected. The result is coming out like this [{"regis ....... var item = JSON.stringify(data['code'] ...

Sending back Uploadifive Ajax 'Error/Success' information from a Codeigniter Controller

I am currently working with the Uploadifive upload plug-in. It is functioning properly, but I am facing difficulties in passing error and success messages from my controller back to my view through the plug-in. Despite logging console and log errors, I can ...

Why does trying to package a Windows app on OSX prompt a request for Wine installation?

For several months, I have been successfully utilizing Electron on macOS (10.11.6) to create and package both OSX and Windows applications. My current setup includes electron v1.7.3 and "electron-packager" "^8.5.2", all of which have not been updated in a ...

The PDF structure in vue3-pdf is not valid and may cause errors

This error is occurring on almost every file, except for one that works fine. The console also displays the following warning: Warning: Indexing all PDF objects. Object { message: "Invalid PDF structure.", name: "InvalidPDFException", ...

Use Javascript to toggle the display to none for a specific table row (tr)

Is there a way to implement JavaScript code that will hide a specific table row using display:none;, and then reveal it again when a button is clicked? ...

Sending a multitude of variables using strings, evaluating them through various functions, and incorporating a variety of methods

To put it simply, my goal is to utilize an object literal that allows me to pass an unknown quantity of variables in any order to a function. While this may seem straightforward in principle, within my code, this object literal is passed to a second functi ...

Tips for concealing labels until the submit button is activated

I am currently handling a project involving a Spring Controller and JSP. Within a JSP page, I have included a button labeled Process. Upon clicking this button, two radio buttons are displayed below it along with a Submit button. After tapping the Submit ...

JavaScript - Toggling checkboxes to either be checked or unchecked with a "check all" option

To create a toggle checkboxes functionality, I am attempting the following: HTML Code: <!-- "Check all" box --> <input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox( this.getAttribute( 'id' ));" /> <!-- the other ...

Introduce a pause using the raycaster function

When my raycaster intersects an object for 2 seconds, I want to update the object's texture. I attempted to use the clock function, but I am unsure of how to properly implement it. var clock = new THREE.Clock(); clock.autoStart = true; var inters ...