skip to Main Content

How do I POST parameters for content type text/html without sending it as an object?

In my case I need to send extra data outside of a form read from cookie.

Posting using body : {} or body: JSON.Stringify({}) posts data an object. I want 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)
    }
});

Got an object instead of individual values –

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

Expecting individual values –

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

2

Answers


  1. Adding my comment as an answer, Since you have mentioned you want to submit a form-data. You have construct FormData , Instead of JsonString

    $(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)
        }
    });
    
    Login or Signup to reply.
  2. If you are not interested in sending the data as JSON string/object there could be other options. Here I have three examples. Sending as:

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

    Sending the data with the content type text/html does not make sense, now that the data has nothing to do with HTML code.

    Personally, I would prefer use either the second or third option.

    Send as text/plain (URI encoded)

    This is what I interpret out of your question. You would like to send the data as a plain string. Now, that is a bit messy with line breaks and characters like ", so you need to encode the data as URI. In this case the server has no chance of interpriting the data/string, therefore this option is not a good idea.

    $(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 you POST data using an ordinary HTML form. If there are no files that need to be send, this is would be the preferred option. The server will be able to interpret the data as if it was a HTML form sending the data.

    $(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 is content type used when you POST data including files in a HTML form. The server will be able to interpret the data as if it was a HTML form sending the data.

    $(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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search