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
Adding my comment as an answer, Since you have mentioned you want to submit a
form-data
. You have construct FormData , Instead of JsonStringIf you are not interested in sending the data as JSON string/object there could be other options. Here I have three examples. Sending as:
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.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.
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.