Having issues with Json stringification and serializing arrays

Having an issue with Json when using serializeArray.

An example of my HTML form:

<form action="" method="post" name="myForm">
ID: <input type="text" name="id" /><br/>
State (XX): <input type="text" name="state" /><br/>
<p><input type="submit" onClick='submitform()' /></p>
</form>

This is the javascript I'm using:

function submitform() {
var formData = JSON.stringify($("form[name*='myForm']").serializeArray());
alert(formData);

The alert displays data in name value pairs like:

[{"name":"id","value":"1234"},{"name":"state","value":"CA"}]

I want the output to be: {"id":"1234","state":"CA"}

Any suggestions on how to achieve this?

Answer №1

There are plenty of existing posts on this topic at stackoverflow

Converting form data to JSON


    $.fn.serializeData = function() {
        var obj = {};
        var arr = this.serializeArray();
        $.each(arr, function() {
            if (obj[this.name]) {
                if (!obj[this.name].push) {
                    obj[this.name] = [obj[this.name]];
                }
                obj[this.name].push(this.value || '');
            } else {
                obj[this.name] = this.value || '';
            }
        });
        return obj;
    };

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 Angular JS version 1.2.26 to implement promises within a forEach iteration

I am working on a JavaScript project where I have implemented an angular.forEach loop to iterate over image configuration objects and create Image() objects using the URLs from the config. My goal is to ensure that none of the resulting images are returne ...

Guide to smoothly scroll to a specific Label using GSAP's scrollTrigger and scrubbing within a Timeline

Currently facing an issue with a scrollTrigger Timeline where I need a button to scroll to a specific position. I attempted using seek but it did not work, and even the ScrollTo plugin lacks support for this functionality. The Timeline created using gsap ...

What is the best way to create a header similar to the one in the image using only CSS

Wondering if it's possible to create a header like the one in the image using just pure CSS and without Photoshop. How can I design it in a professional manner? You can view an example of the image here. ...

Error: Encountered an unexpected token while trying to parse multiple form functions

I recently added the following submission function to my .js file: $( "form" ).on( "submit", function( event ) { event.preventDefault(); var data = $( this ).serialize(); $.ajax({ type: "POST", url: "content/rev/a_sub ...

Using Java to extract data from a JSON file containing dynamic fields

Looking to extract data from a JSON file that contains objects with dynamic fields. Take, for example, the "items" section which includes objects with unique identifiers like “1c68b853-2a07-4409-ad61-8650212f3260” along with additional attributes. Ther ...

Tips for efficiently serving a static file without triggering a disk read

res.sendFile is the preferred method for serving a static file in express. However, it appears that res.sendFile reads the file from disk with each request, as shown below: router.get('/', (req, res) => { res.sendFile('./guest.js&apo ...

incorporating video content onto a webpage

Let me provide more details for better understanding. Currently, the website is not operational yet. Once it's live, I'll be hosting it on a platform like YouTube. The issue I encountered was when trying to embed a video using the code below: & ...

What is the best way to locate the nearest marker using the Google Maps Direction Service?

Currently, I am engaged in the development of a Google Maps project where I am integrating markers retrieved from a database onto the map using the drawMarkers function. In addition to this, the Google Maps feature tracks your current location and refreshe ...

Bower consistently installs the most up-to-date version instead of the version that was explicitly specified

Despite the version specified in the "bower.json" file, bower (v1.8.0) doesn't adhere to it and instead downloads the most recent version of the library available. It seems like it's not taking the version into account at all. Even downgrading to ...

When a table cell is hovered over, a left border will be added

I've been working on adding a left border to the text in a way that highlights the first cell's border when hovering over a row, providing a clear indication of the current row for users. Feel free to check out my progress so far on this fiddle: ...

What is the best way to obtain the SearchIDs for various searchNames using JavaScript?

Who can assist me in resolving this issue? I am trying to retrieve the id of a searchName whenever a user selects the checkbox. Ideally, I would like to assign the value of the PHP line $search_row->searchid to the id attribute in the input field. Apolog ...

Is there a way to invoke a class method from the HTML that is specified within its constructor function?

class Welcome { constructor() { this.handlePress = this.handlePress.bind(this); this.htmlContent = `<a onclick="this.handlePress">Link</a>`; } handlePress(e) { console.log('planet'); } } The HTML structure appears ...

Tips on arranging jQuery deferred objects in order?

I am facing an issue where I need to delay every Ajax call until the previous function (hashcode.Sign()) has completed. Unfortunately, my current code does not wait for hashcode.Sign() to finish, causing problems as this function creates a new session that ...

Invalid file format for product images in Magento version 1.9.0.1

Every time I try to upload an image in the product option, Magento 1.9.0.1 gives me an error saying "Disallowed file format." ...

In Google Chrome, the input types for email, URL, and search feature a thin 1px padding on the left and right sides

If you are a user of Google Chrome (the only browser I am familiar with that exhibits this behavior), please visit this example, uncheck the "Normalized CSS" box, and observe the input elements. In Google Chrome, the email, URL, and search input fields ha ...

Eliminating empty elements in json documents within a MongoDB database

Working with php and MongoDB, the library I am using automatically generates code for mongodb calls, acting as an ODM layer. However, when dealing with embedded documents in the parent document, the library utilizes the $unset function. According to the D ...

Creating dynamic flags with specific parameters using Pentaho and JavaScript

I am looking to optimize my code by finding a better way to achieve this. I have a variable called "hour" and I need to create flags for each hour of the day like so: if (hour == 0) {flag12AM = 'yes'} else {flag12AM == 'no'} if (hour ...

Changing the format of JSON output in Laravel

Help me clean up my JSON output by removing unnecessary elements. This is my current Output: [ { "current_page": 1, "data": [ { "_id": "6580f69587f0f77a14091c22", ...

The digest string for the crypto.pbkdf2Sync function is malfunctioning

I've been working on revamping the authentication system for an old application that previously ran on node 4.5, but I keep encountering an error whenever I attempt to log in. TypeError [ERR_INVALID_ARG_TYPE]: The "digest" argument must be one of type ...

The error message reads: `json.decoder.JSONDecodeError: Unexpected additional data present at line 2, starting from column 1 (character

I encountered an error: (json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 5357)) when trying to parse a JSON file. Can someone explain the reason behind this error? Additionally, could you provide guidance on how to properly extract va ...