Using async/await with Fetch to send POST parameters for text/html content

Is there a way to POST parameters for content type text/html without sending it as an object?

In my specific scenario, I need to include extra data that is not part of a form and is read from a cookie.

When posting with body : {} or body: JSON.Stringify({}), the data is posted as an object. However, I want the data to be posted as individual values.

$(document).on('click', '#update', async () => {
    try {
        const response = await fetch("/getupdate",{
            method:'POST',
            headers:{
                'Content-Type':'text/html; charset=utf-8'
            },
            body: JSON.stringify({
                "country": getCookie("country"),
                "city": getCookie("city").replace(/"/g, ""),
                "action": 1,
                "csrfmiddlewaretoken": $('input[name=csrfmiddlewaretoken]').val()
            }),
        });
    } catch (error){
        console.log(error)
    }
});

Instead of receiving individual values, I got an object -

{
    "country": "US",
    "city": "Miami",
    "action": 1,
    "csrfmiddlewaretoken": "iLoS4Bsgdyc6EhOtQKiiXrIqr9S1eojdhdyEeClA8qI5ei2WpfQQu1JrduLrbndndR"
}

I am expecting individual values to be sent like this -

    "country": "US",
    "city": "Miami",
    "action": 1,
    "csrfmiddlewaretoken": "iLoS4Bsgdyc6EhOtQKiiXrIqr9S1eojdhdyEeClA8qI5ei2WpfQQu1JrduLrbndndR"

Answer №1

If you're not keen on transmitting the data as a JSON string/object, there are alternative options available. Here are three examples of how you can send the data:

  • text/plain
  • application/x-www-form-urlencoded
  • multipart/form-data

Sending the data with the content type text/html doesn't make sense because the data is unrelated to HTML code.

Personally, I would recommend using either the second or third option.

Send as text/plain (URI encoded)

This seems to be what you're asking for. You want to send the data as a plain string. However, this can get messy with line breaks and characters like ", requiring you to encode the data as URI. But keep in mind that if you do this, the server won't be able to interpret the data/string correctly, so this may not be the best choice.

$(document).on('click', '#update', async() => {
  let data = `"country": ${getCookie("country")},
              "city": ${getCookie("city").replace(/"/g, "")},
              "action": 1,
              "csrfmiddlewaretoken": ${$('input[name=csrfmiddlewaretoken]').val()}`;

  try {
    const response = await fetch("/getupdate", {
      method: 'POST',
      body: encodeURIComponent(data)
    });
  } catch (error) {
    console.log(error)
  }
});

function getCookie(str) {
  return "some string";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="csrfmiddlewaretoken" value="csrfmiddlewaretoken">
<button id="update">Update</button>

Send as application/x-www-form-urlencoded

This is the default content type when submitting data through a standard HTML form. If you don't have any files to send, this would be the recommended option. The server will be able to understand the data as if it were coming from an HTML form submission.

$(document).on('click', '#update', async() => {
  let data = new URLSearchParams();
  data.append('country', getCookie("country"));
  data.append('city', getCookie("city").replace(/"/g, ""));
  data.append('action', 1);
  data.append('csrfmiddlewaretoken', $('input[name=csrfmiddlewaretoken]').val());

  try {
    const response = await fetch("/getupdate", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: data
    });
  } catch (error) {
    console.log(error)
  }
});

function getCookie(str) {
  return "some string";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="csrfmiddlewaretoken" value="csrfmiddlewaretoken">
<button id="update">Update</button>

Send as multipart/form-data

This content type is used when sending data along with files in an HTML form. The server will be able to interpret the data similar to an HTML form submission.

$(document).on('click', '#update', async() => {
  try {
    let data = new FormData();
    data.append("country", getCookie("country"));
    data.append("city", getCookie("city").replace(/"/g, ""));
    data.append("action", 1);
    data.append("csrfmiddlewaretoken", $('input[name=csrfmiddlewaretoken]').val());

    const response = await fetch("/getupdate", {
      method: 'POST',
      body: data
    });
  } catch (error) {
    console.log(error)
  }
});

function getCookie(str) {
  return "some string";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="csrfmiddlewaretoken">
<button id="update">Update</button>

Answer №2

In my opinion, it would be best to submit the form data by constructing a FormData object instead of using JsonString. You can do this by referring to the FormData documentation for more information.

$(document).on('click', '#update', async () => {
    try {
        // Construct form data
        const data = new FormData();
        data.append("country", getCookie("country"));
        data.append("city", getCookie("city").replace(/"/g, ""));
        data.append("action", 1);
        data.append("csrfmiddlewaretoken", $('input[name=csrfmiddlewaretoken]').val());

        const response = await fetch("/getupdate",{
            method:'POST',
            body: data,
        });
    } catch (error){
        console.log(error)
    }
});

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 jQuery, learn how to successfully call a selector from dynamic content

I am currently facing a challenge with a table that is generated server-side and then appended to the view page (client-side). Since the table is not directly included in the DOM, I am using the StickyTableHeaders jQuery plugin to create a sticky header fo ...

Access and retrieve pkpass files from a server using React

I've exhausted all options but still can't get it to work. I'm attempting to create an Apple wallet pass using https://github.com/walletpass/pass-js. When I download the pass on the node server where I've implemented it, everything work ...

Unable to find the import "@mui/x-charts/PieChart" in the file "src/components/Pie/Pie.jsx". Could the file be missing or spelled incorrectly?

I utilized the PieChart component in my pie.jsx file pie.jsx import { PieChart } from '@mui/x-charts/PieChart'; const Pie = () => { return ( <div> <PieChart series={[ { data: [ ...

In what scenarios is it more suitable to utilize style over the sx prop in Material-UI?

When it comes to MUI components, the style and sx prop serve similar purposes. While the sx prop provides some shorthand syntaxes and access to the theme object, they essentially function the same way. So, when should you opt for one over the other? ...

Enhancing, not replacing, a Template Block

Currently, I am working on a Django template that involves a block of code for a basic blog engine: {% block mainLeft %} <section class="container" id="main"> <section class="offset1 span8" id="mainLeft> </section> ...

I am not enhancing the array's value; rather, I am substituting it

Hey everyone, I'm currently working on extracting an array of Sizes and Colors from an object. The goal is to trigger a handler, clickHandler(), when the input is clicked. However, each time the handler is invoked, the code ends up replacing the value ...

Encountering a three.js issue while generating a large number of point lights

//////twinkling stars for (let index = 0; index < 1000; index++) { const stargeometry = new THREE.SphereGeometry(1, 24, 24); //create star sphere size const starmaterial = new THREE.MeshStandardMaterial({ color: 0xffffff }); //define star textur ...

Use HTML to showcase an image that dynamically changes based on the outcome of a query function

Hello there, I hope my inquiry is clear enough. I apologize for reaching out as I am unsure where to begin and what exactly I should be focusing on. Currently, I have an image displayed in an HTML page like this: <div id="tag_sunrise_sunset"><p ...

Encountering an issue with Django where updating the database using an Excel file results in an error due to the presence of duplicate

My model assigns contact_email as the primary key for the Contact model. A scenario arises where users can upload an excel file on an html page to add their contacts to the database. When a new contact_email is uploaded, contacts are successfully added to ...

How can Selenium be used to identify an Internet Explorer browser extension?

Can Selenium be used to detect internet explorer browser plugins? For example, if I open a URL on IE and want to check for any installed plugins, is there a way to automate this with selenium? ...

instructions for selecting div id within the same "table td" element using jQuery

Here is the code snippet that I am working with: <td> <div id="div<%# Eval("Id") %>" class="Display"><%# Eval("Display") %></div> <div class="Actions"> </div> <div class="Comment"> <span>Comm ...

How to dynamically insert elements into the HTML page using Angular

When my page first loads, it looks like this <body> <div class="col-md-12" id="dataPanes"> <div class="row dataPane"> Chunk of html elements </div> </div> <div class"col-md-12 text-right"> <input type="butt ...

What is the best way to interpret numerous rows of Form elements simultaneously?

What is the most efficient way to name form elements across rows for easy conversion into JSON format? Considering HTML does not have built-in Array support, what alternative method should be used? In each row, there are 2 text fields and 1 select dropdow ...

Switching from jQuery to vanilla JavaScript, iterating through each HTML tag in a loop

Here is my current jQuery code that I am looking to convert into vanilla JavaScript. var elements = []; document.querySelectorAll('*:not(script, style, iframe)').forEach(function(element) { elements.push(element); }); I have tried using d ...

Is it possible to include ternary in the "homepage" section of the package.json file?

When making API calls in production, they will be on the same domain as where my app is hosted, so it's necessary to include "homepage": "." in the package.json. However, when working locally from localhost, I need to make API calls to the production ...

Redirecting with response headers in Next.js

Objective: The Goal: Clicking a button on a page should send a request to the controller. The controller will then set a cookie, and upon receiving the response, redirect the page to another page, such as the about page. Directly Calling API route from th ...

Expand Menu Options (jQuery)

Currently facing a jQuery problem that I can't seem to figure out. I've set up a menu with submenu elements and want to toggle the content height by clicking on menu items. The issue arises when clicking on another item causes the content to coll ...

Combining Framer Motion with Next.js: Resolving conflicts between layoutId and initial props in page transitions

As I work on creating smooth image page transitions using Framer Motion and Next.js with layoutId, I've come across a challenge. Here is my main objective: The home page displays an overview with 3 images When an image is clicked, the other images f ...

What is the process for specifying a method on a third-party class in TypeScript?

I'm facing a challenge while trying to extend a third-party class in TypeScript. The issue is that I am unable to access any existing methods of the class within my new method. One possible solution could be to redeclare the existing methods in a sep ...

Why is my nested React Router component failing to load upon page refresh?

Lately, I have been delving into learning react and for the past few weeks. However, I've encountered an issue where when I try to reload the page using the browser's reload button, instead of reloading the component, it simply disappears (turnin ...