Transmitting an array within the POST request payload

My goal is to send an array to my Node/MongoDB server using an AJAX POST request, along with other variables in the body. Check out the client side JS code below:

function setupForm(){
    $("#add").submit(function(event) {
        event.preventDefault();
        var name = $("#name").val();
        var logo = $("#logo").val();
        var phone = $("#phone").val();
        var email = $("#email").val();
        var address = $("#address").val();
        var postcode = $("#postcode").val();
        var openingHours = $("#openingHours").val();
        var loc = [44, 44];

        $.ajax({
            type: "POST",
            url: "http://localhost:3000/services",
            data: "name=" + name + "&logo=" + logo + "&phone=" + phone + "&email=" + email + "&address=" + address + "&postcode="+ postcode +"&openingHours=" + openingHours + "&loc=" + loc,
            success: function(){alert('success');}
        });
    });
}

Here is the corresponding server side code:

exports.addWine = function(req, res) {
    var wine = req.body;
    console.log('Adding wine: ' + JSON.stringify(wine));
    db.collection('services', function(err, collection) {
        collection.insert(wine, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred'});
            } else {
                console.log('Success: ' + JSON.stringify(result[0]));
                res.send(result[0]);
            }
        });
    });
}

The current format of adding to the database is not what I desire. Can you help me achieve it in an array like this?

"postcode" : "ugh",
"openingHours" : "fhgfh",
"loc" : "44,44"

Answer №1

To incorporate an additional parameter, simply utilize the serializeArray() function as stated. Append the extra parameter to the array following the example below:

function setupForm(){
    $("#add").submit(function(event) {
        event.preventDefault();

        var data = $(this).serializeArray();
            // add extra parameters (don't forget brackets)
            data.push({ name: 'loc[]', value: 44 });
            data.push({ name: 'loc[]', value: 44 });

        $.ajax({
            type: "POST",
            url: "http://localhost:3000/services",
            data: data,
            success: function() {
               alert('success');
            }
        });
    });
}

If you prefer to continue using your current method of constructing the query string, you would need to include &loc[]=44&loc[]=44. However, it is recommended in the long term to opt for one of the serialize functions for better efficiency.

Answer №2

If you want to ensure the integrity of your data, I recommend including it in the body of your POST requests. By sending the data this way using JSON, you can preserve its datatypes such as arrays and booleans.

$.post("http://localhost:3000/services", {
        name: $("#name").val(),
        loc: [44, 44]
        ...and so on
    }, function(){alert('success');}
);

Your backend should function correctly without any changes necessary. However, you may need to incorporate body-parser into your middleware stack. This middleware will convert the body into a JavaScript object that can be directly inserted into your database.

Answer №3

If you're in need of a solution, consider exploring the functionalities of jQuery's .serialize() and .serializeArray(). These methods might just be what you need.

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

saving numeric values and text to a document using node.js

In my node.js application, I am working with files to read and write numbers and strings. Currently, I am using fs.writeFileSync(myPath, value); where the value can be either a number or a string. When I try to read the file using fs.readFileSync(myPa ...

How can I transfer information from Node.js to Vue in an Nuxt.js server-side rendering setup?

I need to find a way to pass Firestore data to Vue files from Node.js (Express) because I have to utilize Firestore's getCollections() method, which cannot be executed on the client side. I have set up nuxt-ssr for deploying Google Cloud Functions an ...

Basic asynchronous JavaScript and XML (AJAX) call

I am currently learning about ajax and experimenting with a script that involves extracting information from a JSON object and displaying it on the document. Below is an example of the JSON file named companyinfo.json: { 'id':1, 'name&apos ...

What is the best starting dataset to use from a large pool of data points when creating a stock line chart in High

I am working on creating a line stock highchart similar to the example shown here: https://www.highcharts.com/demo/stock/lazy-loading In the provided example, the initial load fetches data from https://demo-live-data.highcharts.com/aapl-historical.json, s ...

Combining shared table rows with embedded ruby code in Javascript - is it possible?

I'm a new Javascript learner and I'm attempting to create a function that will merge rows with the same value (year in this case) and add their numbers together. Although my code isn't functioning as expected, it also doesn't seem to be ...

Facing an ESIDIR error in NextJs, despite the fact that the code was sourced from the official documentation

For an upcoming interview, I decided to dive into learning Next.js by following the tutorial provided on Next.js official website. Everything was going smoothly until I reached this particular section that focused on implementing getStaticProps. Followin ...

Why is the value of the select element in AngularJS an object?

Here is a JSON object: { "9000A": { "LOCname":"A Place", "LOCid":"9000A" }, "2700C": { "LOCname":"C Place", "LOCid":"2700C" }, "7600B": { "LOCname":"B Place", "LOCid":"7600B" } } To ...

Time for the browser to evaluate javascript code has arrived

We are looking to enhance the speed at which our Javascript files load in the browser. Although our own Javascript files are simple and small, larger libraries like jQuery and KendoUI take a considerable amount of time to evaluate. We are interested in fin ...

The functionality of my script relies on the presence of an alert function within it

My code seems to only work when I include an alert function in it. I'm trying to make my div scroll to the bottom. I've done some research, but for some reason, the script doesn't run without an alert function. $(document).ready(function ...

Creating a nested JSON structure by fetching data from a remote source

i'm looking to populate the json file located at through a get request. This json contains music from various churches in different cities, with data organized into multiple levels. I want to parse this data using jquery and utilize hidden div elemen ...

Using JavaScript/JQuery, change relative or viewport sizes to fixed sizes when the page loads

Wishing you a delightful day. As I work on my website, I find myself relying heavily on viewport units like vw and vh for all measurements such as font size, padding, margin, width, and height. These units provide the flexibility needed to ensure that the ...

Automated system is responsible for flagging and disabling comments

We are facing a puzzling issue at the moment. Our comments form allows users to submit their thoughts on news articles, and each submission is immediately accepted and displayed on the same page. Within each comment, there is a link that enables users to ...

The system is unable to locate a supporting entity with the identifier '[object Object]', as it is classified as an 'object'

I'm currently working on an Angular 2 application where I am retrieving data from an API and receiving JSON in the following format. { "makes": null, "models": null, "trims": null, "years": null, "assetTypes": { "2": "Auto ...

Converting data from Node.js 6.10 from hexadecimal to base64 and then to UTF-8

I have a code snippet that generates "data" containing a JSON object. My goal is to extract the HEX-value from the Buffer in the data, and then decode it from HEX to BASE64 to UTF8 in order to convert it into a string. Here is the code snippet: console.l ...

The lifespan of my cookie is limited

I am utilizing the jQuery.min.js from https://github.com/carhartl/jquery-cookie and my cookie code looks like this: $(function() { //hide all divs just for the purpose of this example, //you should have the divs hidden with your css //check ...

Uploading files with Express JS 4.x using Multer

I am facing challenges while attempting to upload an image in Express JS using the Multer middleware. The process seems straightforward, yet I encounter multiple issues with what should be the simplest scenario. Upon trying to execute my code, the only er ...

The HTML button with Google's material-icons appears noticeably small when displayed on mobile devices

Looking to design a basic HTML page with a button placed in the lower right corner? Check out the code below: <!DOCTYPE html> <html> <head> <title>Sample Page</title> <style> /* Styles for the container * ...

Attempting to execute the .replace() method but encountering difficulties

Looking for help with some HTML code: <li><a href="#" class="lstItem">Testing jQuery [First Bracket]</a></li> <li><a href="#" class="lstItem">Loving jQuery [Second one]</a></li> I need to remove the text in ...

Tips for crafting interactive Dropdown menus

Visit this link for more information Hello all, I am a beginner in HTML and Javascript and seeking guidance on how to create dynamic dropdown menus similar to the ones on the provided website. I have successfully implemented the source code, but my questi ...

Ensure jQuery waits until the function has completed execution

Here is the script in question: var d; $(".circle").click(function() { var id = $(this).attr('id'); var MyDiv1 = document.getElementById(id); var name = MyDiv1.innerHTML; $.get("url", function(data){ d=data; }); d=d ...