Send json with javascript

Javascript : Send JSON Object with Ajax?

and then JSON.stringify the JSON object and send it in a parameter, but it would be cool to send it in this way if it’s possible.

4 Answers 4

var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance xmlhttp.open("POST", "/json-handler"); xmlhttp.setRequestHeader("Content-Type", "application/json"); xmlhttp.send(JSON.stringify()); 

but man I can use content-type: application/x-www-form-urlencoded too if I use stringify, then what’s the point to use application/json ? 🙂

@CIRK: What’s it matter? The content-type setting is completely arbitrary unless the server treats the one or the other specially. It’s just data flowing back and forth at the end of the day.

well if your post body is expected to be JSON eg () use content type application/json if your post body is form urlencoded data (name=John&time=2pm) use application/x-www-form-urlencoded

If you`re not using jQuery then please make sure:

var json_upload = "json_name=" + JSON.stringify(); var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance xmlhttp.open("POST", "/file.php"); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlhttp.send(json_upload); 

And for the php receiving end:

I don’t think this answers the question asked. I believe the dev wants to send a blob of JSON to PHP as Content-Type: application/json, not wrapped in a urlencoded wrapper.

This is not really sending JSON over, it is sending formdata over. You can also send JSON directly, in which case you can not read it with $_POST, but instead read it with json_decode(file_get_contents(‘php://input’));

Dear friends can you share this POST ajax with the entire needed code to be used on the page? Or thank you as well if you have a kind link to some full working example of vanilla ajax POST with JSON

I struggled for a couple of days to find anything that would work for me as was passing multiple arrays of ids and returning a blob. Turns out if using .NET CORE I’m using 2.1, you need to use [FromBody] and as can only use once you need to create a viewmodel to hold the data.

Wrap up content like below,

In my case I had already json’d the arrays and passed the result to the function

var IDs = JsonConvert.SerializeObject(Model.Select(s => s.ID).ToArray()); 

Then call the XMLHttpRequest POST and stringify the object

var ajax = new XMLHttpRequest(); ajax.open("POST", '@Url.Action("MyAction", "MyController")', true); ajax.responseType = "blob"; ajax.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); ajax.onreadystatechange = function () < if (this.readyState == 4) < var blob = new Blob([this.response], < type: "application/octet-stream" >); saveAs(blob, "filename.zip"); > >; ajax.send(JSON.stringify(params)); 

Then have a model like this

public class MyModel < public int[] IDs < get; set; >public int[] ID2s < get; set; >public int id < get; set; >> 
public async Task MyAction([FromBody] MyModel model) 

Use this add-on if your returning a file

Источник

Fetch: POST JSON data

I’m trying to POST a JSON object using fetch. From what I can understand, I need to attach a stringified object to the body of the request, e.g.:

fetch("/echo/json/", < headers: < 'Accept': 'application/json', 'Content-Type': 'application/json' >, method: "POST", body: JSON.stringify() >) .then(function(res)< console.log(res) >) .catch(function(res)< console.log(res) >) 

When using jsfiddle’s JSON echo I’d expect to see the object I’ve sent ( ) back, but this does not happen — chrome devtools doesn’t even show the JSON as part of the request, which means that it’s not being sent.

check this fiddle jsfiddle.net/abbpbah4/2 what data you’re expecting ? because get request of fiddle.jshell.net/echo/json is showing empty object. <>

You forgot to include the json property that contains the data you want to send. However, I the body is not being treated correctly anyway. See this fiddle to see that the delay of 5 seconds gets skipped. jsfiddle.net/99arsnkg Also, when you try to add additional headers, they are ignored. This is probably an issue with fetch() itself.

18 Answers 18

With ES2017 async/await support, this is how to POST a JSON payload:

(async () => < const rawResponse = await fetch('https://httpbin.org/post', < method: 'POST', headers: < 'Accept': 'application/json', 'Content-Type': 'application/json' >, body: JSON.stringify() >); const content = await rawResponse.json(); console.log(content); >)();

Can’t use ES2017? See @vp_art’s answer using promises

The question however is asking for an issue caused by a long since fixed chrome bug.
Original answer follows.

chrome devtools doesn’t even show the JSON as part of the request

This is the real issue here, and it’s a bug with chrome devtools, fixed in Chrome 46.

That code works fine — it is POSTing the JSON correctly, it just cannot be seen.

I’d expect to see the object I’ve sent back

that’s not working because that is not the correct format for JSfiddle’s echo.

var payload = < a: 1, b: 2 >; var data = new FormData(); data.append( "json", JSON.stringify( payload ) ); fetch("/echo/json/", < method: "POST", body: data >) .then(function(res)< return res.json(); >) .then(function(data)< alert( JSON.stringify( data ) ) >) 

For endpoints accepting JSON payloads, the original code is correct

To be on the safe side, it would be good to confirm res.ok in case the response code is some kind of error. It’d also be good to have a .catch() clause at the end. I realize this is just a sample snippet, but bear these things in mind for real world usage.

Perhaps I’m being redundant but I’d like to point out that it does work successfully with PUT requests as well.

@Timo: this depends very much on your server; the server is not required to use these fields. But the server might emit different data depending on Accept , and it might require content-type to accept json. Better set both to avoid endless debugging when the server software updates.

I think your issue is jsfiddle can process form-urlencoded request only. But correct way to make json request is pass correct json as a body:

fetch('https://httpbin.org/post', < method: 'POST', headers: < 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' >, body: JSON.stringify() >).then(res => res.json()) .then(res => console.log(res));

For those who aren’t familiar with arrow functions, you have to return res.json() there, to get the data in the next .then() call.

From search engines, I ended up on this topic for non-json posting data with fetch, so thought I would add this.

For non-json you don’t have to use form data. You can simply set the Content-Type header to application/x-www-form-urlencoded and use a string:

fetch('url here', < method: 'POST', headers: , // this line is important, if this content-type is not set it wont work body: 'foo=bar&blah=1' >); 

An alternative way to build that body string, rather then typing it out as I did above, is to use libraries. For instance the stringify function from query-string or qs packages. So using this it would look like:

import queryString from 'query-string'; // import the queryString class fetch('url here', < method: 'POST', headers: , // this line is important, if this content-type is not set it wont work body: queryString.stringify() //use the stringify object of the queryString class >); 

After spending some times, reverse engineering jsFiddle, trying to generate payload — there is an effect.

Please take eye (care) on line return response.json(); where response is not a response — it is promise.

var json = < json: JSON.stringify(< a: 1, b: 2 >), delay: 3 >; fetch('/echo/json/', < method: 'post', headers: < 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' >, body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay >) .then(function (response) < return response.json(); >) .then(function (result) < alert(result); >) .catch (function (error) < console.log('Request failed', error); >); 

yw. Curious detail, it works for me in the old way with fetch (stackoverflow.com/questions/41984893/…) instead the application/json . Perhaps you know why .

The Content-Type is application/json , but your actual body appears to be x-www-form-urlencoded — I don’t think this should work? If it does work, your server must be pretty forgiving. The answer by @vp_arth below appears to be the correct one.

2021 answer: just in case you land here looking for how to make GET and POST Fetch api requests using async/await or promises as compared to axios.

I’m using jsonplaceholder fake API to demonstrate:

Fetch api GET request using async/await:

 const asyncGetCall = async () => < try < const response = await fetch('https://jsonplaceholder.typicode.com/posts'); const data = await response.json(); // enter you logic when the fetch is successful console.log(data); >catch(error) < // enter your logic for when there is an error (ex. error toast) console.log(error) >> asyncGetCall() 

Fetch api POST request using async/await:

 const asyncPostCall = async () => < try < const response = await fetch('https://jsonplaceholder.typicode.com/posts', < method: 'POST', headers: < 'Content-Type': 'application/json' >, body: JSON.stringify(< // your expected POST request payload goes here title: "My post title", body: "My post content." >) >); const data = await response.json(); // enter you logic when the fetch is successful console.log(data); > catch(error) < // enter your logic for when there is an error (ex. error toast) console.log(error) >> asyncPostCall() 

GET request using Promises:

 fetch('https://jsonplaceholder.typicode.com/posts') .then(res => res.json()) .then(data => < // enter you logic when the fetch is successful console.log(data) >) .catch(error => < // enter your logic for when there is an error (ex. error toast) console.log(error) >) 

POST request using Promises:

fetch('https://jsonplaceholder.typicode.com/posts', < method: 'POST', headers: < 'Content-Type': 'application/json', >, body: JSON.stringify(< // your expected POST request payload goes here title: "My post title", body: "My post content." >) >) .then(res => res.json()) .then(data => < // enter you logic when the fetch is successful console.log(data) >) .catch(error => < // enter your logic for when there is an error (ex. error toast) console.log(error) >) 
 const axiosGetCall = async () => < try < const < data >= await axios.get('https://jsonplaceholder.typicode.com/posts') // enter you logic when the fetch is successful console.log(`data: `, data) > catch (error) < // enter your logic for when there is an error (ex. error toast) console.log(`error: `, error) >> axiosGetCall() 
const axiosPostCall = async () => < try < const < data >= await axios.post('https://jsonplaceholder.typicode.com/posts', < // your expected POST request payload goes here title: "My post title", body: "My post content." >) // enter you logic when the fetch is successful console.log(`data: `, data) > catch (error) < // enter your logic for when there is an error (ex. error toast) console.log(`error: `, error) >> axiosPostCall() 

I have created a thin wrapper around fetch() with many improvements if you are using a purely json REST API:

// Small library to improve on fetch() usage const api = function(method, url, data, headers = <>)< return fetch(url, < method: method.toUpperCase(), body: JSON.stringify(data), // send it as stringified json credentials: api.credentials, // to keep the session on the request headers: Object.assign(<>, api.headers, headers) // extend the headers >).then(res => res.ok ? res.json() : Promise.reject(res)); >; // Defaults that can be globally overwritten api.credentials = 'include'; api.headers = < 'csrf-token': window.csrf || '', // only if globally set, otherwise ignored 'Accept': 'application/json', // receive json 'Content-Type': 'application/json' // send json >; // Convenient methods ['get', 'post', 'put', 'delete'].forEach(method => < api[method] = api.bind(null, method); >); 

To use it you have the variable api and 4 methods:

And within an async function:

const all = await api.get('/todo'); // . 
$('.like').on('click', async e => < const // Get it however it is better suited await api.put(`/like/$`, < like: true >); // Whatever: $(e.target).addClass('active dislike').removeClass('like'); >); 

Had the same issue — no body was sent from a client to a server. Adding Content-Type header solved it for me:

var headers = new Headers(); headers.append('Accept', 'application/json'); // This one is enough for GET requests headers.append('Content-Type', 'application/json'); // This one sends body return fetch('/some/endpoint', < method: 'POST', mode: 'same-origin', credentials: 'include', redirect: 'follow', headers: headers, body: JSON.stringify(< name: 'John', surname: 'Doe' >), >).then(resp => < . >).catch(err => < . >) 

This is related to Content-Type . As you might have noticed from other discussions and answers to this question some people were able to solve it by setting Content-Type: ‘application/json’ . Unfortunately in my case it didn’t work, my POST request was still empty on the server side.

However, if you try with jQuery’s $.post() and it’s working, the reason is probably because of jQuery using Content-Type: ‘x-www-form-urlencoded’ instead of application/json .

data = Object.keys(data).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(dataSend json with javascript)).join('&') fetch('/api/', < method: 'post', credentials: "include", body: data, headers: >) 

The top answer doesn’t work for PHP7, because it has wrong encoding, but I could figure the right encoding out with the other answers. This code also sends authentication cookies, which you probably want when dealing with e.g. PHP forums:

julia = function(juliacode) < fetch('julia.php', < method: "POST", credentials: "include", // send cookies headers: < 'Accept': 'application/json, text/plain, */*', //'Content-Type': 'application/json' "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" // otherwise $_POST is empty >, body: "juliacode mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f4.0%2f" data-se-share-sheet-license-name="CC BY-SA 4.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
answered May 24, 2018 at 4:25
1
    1
    For PHP you can also use $data = json_decode(file_get_contents('php://input'), true); to get the array from fetch(requestURI, );
    – xgarb
    Aug 19, 2022 at 13:35
Add a comment|
5
**//POST a request** const createTodo = async (todo) =>< let options = < method: "POST", headers: < "Content-Type":"application/json", >, body: JSON.stringify(todo) > let p = await fetch("https://jsonplaceholder.typicode.com/posts", options); let response = await p.json(); return response; > **//GET request** const getTodo = async (id) =>< let response = await fetch('https://jsonplaceholder.typicode.com/posts/' + id); let r = await response.json(); return r; >const mainFunc = async () =>< let todo = < title: "milan7", body: "dai7", userID: 101 >let todor = await createTodo(todo); console.log(todor); console.log(await getTodo(5)); > mainFunc()

Источник

Читайте также:  Индекс максимального элемента массива питон
Оцените статью