Js fetch post json php

How to use fetch in JavaScript to GET or POST data

The fetch command is an asynchronous function which allows you to send and receive data in JavaScript — commonly used for getting data from an API or similar.

GET data

The default method for fetch is GET . This allows you to pass in a URL and get the data from the other end. In the example below we are retrieving a JSON API. Using promises, the data is parsed and then made available for use.

The thing to note with asynchronous functions (in laymen’s terms) is, although they fire when executed, they do not stop the rendering of the page. If part of your code requires the fetch to be complete before firing, ensure it is triggered in the promise (the then function).

fetch(URL) .then(data => data.json()) .then(data =>  // data is your API data >); ``` ## POST data There may be instances when your JavaScript code or app may wish to POST data to your backend code. This can be achieved using `fetch` also. Consider this example which includes the `JSON.stringify()` function - this [converts a json object into a JSON string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). ```js let data =  key: "value" >; fetch(URL,  method: 'post', body: JSON.stringify(data) >).then(data =>  // data is anything returned by your API/backend code >);

Bonus: PHP example

This one took me a while to figure out, but capturing the POST variables from your fetch function in a PHP script is not as obvious as it initially seems!

The key is using php://input — which is a readable stream which contains the data as a JSON string (as sent with the fetch function). This can be decoded using the native PHP function.

 $input = json_decode(file_get_contents('php://input'), true); // $input['key'] would equal "value" 

If you were to remove the true from the end of the json_decode , your data would be available as a PHP object instead, meaning you would access «value» using $input->key .

Источник

Как сделать обмен данными между js и php используя fetch?

Если указываем вернуть JSON в fetch то возникает ошибка:
Error SyntaxError: «JSON.parse: unexpected character at line 1 column 1 of the JSON data»
Если укажем просто объект result, то вернет:
body: ReadableStream
locked: false
: object < … >
bodyUsed: false
headers: Headers < >
ok: true
redirected: false
status: 200
statusText: «OK»
type: «basic»
url: «server/api.php»
: ResponsePrototype

То есть файл ответа он видит и возвращает код 200, но php код не возвращает данные, пробовал без условий, и возвращать var_dump($_POST) и т.д. Как я понял в глобальную переменную $_POST не прилетают данные.
Но если я вернуть к примеру var_dump([1,2,3]), и в js укажу result.text(), то этот массив прилетит мне в консоль.

fetch это promise, попробуй async/await:

document.addEventListener('DOMContentLoaded', function () < async function UseFetch(requestData = <>) < console.log('Получили объект', requestData); console.log("Отправляемый JSON: ", JSON.stringify(requestData)); await fetch('api.php', < method: 'POST', // or 'PUT' headers: < 'Content-Type': 'application/json' >, body: JSON.stringify(requestData) >) .then((result) => result.ok === true ? result.json() : false) .then((data) => console.log("Success", data)) .catch(error => console.error("Error", error)); > UseFetch(< 'path': 123, 'abc': 234 >); >);

А еще, зачем ты декодируешь и потом кодируешь одни и те же данные? Там скорее всего и ошибка, попробуй так:

Источник

Sending data to PHP server with Fetch API (POST method and JSON preferred)

Now I’m trying to understand Fetch API and, even if it’s simple and intuitive, I’ve stumbled on a weird and unexpected problem: I CAN’T send JSON post to PHP server I CAN send form-data post to LOCAL PHP I CAN’T send form-data post to WEB URL PHP I can (obviously) retrieve data from all the above, but strangely nothing arrives. I’m trying Fetch API for the first time and I have problems sending data to a PHP server.

Sending data to PHP server with Fetch API (POST method and JSON preferred)

I’m trying Fetch API for the first time and I have problems sending POST data to a PHP server .

I’m moving away from $.ajax and trying pure javascript solutions to communicate with different servers (sometimes local, sometimes not). Now I’m trying to understand fetch API and, even if it’s simple and intuitive, I’ve stumbled on a weird and unexpected problem:

I can (obviously) retrieve data from all the above, but strangely nothing arrives. Through $_SERVER[‘REQUEST_METHOD’] I can see that when using the LOCAL path I get «POST» as I asked, but when using the WEB URL it changes in GET for some reason I don’t understand.

url="/"; url="www.something.com"; fetch(url, < method: 'POST', body: JSON.stringify(< test: "toast", >) >) .then(function(response) < return response.text(); >) .then(function(data) < console.log(data); >); 

I expect just to send and receive data in a solid and clear way. No jquery, no libraries, etc. I just want to send a JSON and find it on the PHP file when checking the $_POST var.

UPDATE

It seems that the problem with local and web urls were on this difference: www.something.com/test => www.something.com/test/ index.php . Without index.php for some reason it refused the POST data (but read the echoed info anyway). But the problem about JSON remain.

UPDATE

I found that $_POST and $_GET don’t work well with Fetch API. You have to use php://input to get all the data sent to the server.

Don’t know why. There’s a better solution? Why ajax and XMLHttpRequest don’t have this kind of problems?

Note: If you want the data to be recognized as json, you have to specify it with a header, even this was never requested so why now? Is Fetch API missing something?

header('Content-Type: application/json'); $test=json_decode(file_get_contents("php://input")); //some code echo json_encode($test); 

There is two ways to use Fetch API: one>

let response = await fetch(url,[Options]); if (response.ok) < // if HTTP-status is 200-299 // get the response body (the method explained below) let json = await response.json(); >else

and the second way is to use pure promise syntax:

fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits') .then(response => response.json()) .then(commits => alert(commits[0].author.login)); 

now lets talk about options and data: your data must be a JavaScript object like this:

then you can config your headers like this:

finally use fetch like this:

let response = await fetch(url, < method: "POST", headers:headers, body: JSON.stringify(data) >); 

I think your problem is using FormData instead of stringified JavaScript object

I hope someone will find this answer. I am using Codeigniter 3.1.11 and I’ve found the answers after getting help from a friend.

class YourController extends CI_Controller < public function yourMethod() < // THIS CODE IS A MUST! $input = json_decode(file_get_contents('php://input'), true); // You get the data you sent via FETCH var_dump($this->input->post('testdata')); > > 
let postData = new FormData(); postData.append('testdata', 123); fetch('http://localhost/your-app-name/yourcontroller/yourMethod', < method: 'POST', mode: 'no-cors', headers: < "Content-Type": "application/json" >, body: postData >).then((res) => < console.log(res); >).catch(console.log); 

To view the preview of the data you send or get using Fetch you can inspect, go to tab Network, in the table «Name», click yourMethod then go to tab «Preview». In the preview you can see 123.

Php — How to handle POST requests, I am coming from an MVC world and this is quite hard for me to grasp yet. I am trying to figure out what is the wordpress way of handling post requests. I looked it up on the web and I found that I should use add_action with a function defined in my theme’s functions.php but I can not figure out how to …

How to send request to php file via Fetch API post method

Hello guys I just started learning php. So I was trying to make a post request from my javascript file to my php file by Fetch API when I make the request in my console I’m getting this error Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 I don’t understand why this error is happening. Please help me fix this problem.

JavaScript

// payload object const data = < first_name: "first name", last_name: "last name" >// make the request fetch("ajax-insert.php", < method: "POST", body: JSON.stringify(data), headers: < "Content-Type": "application/json; charset=UTF-8" >>) .then((response) => response.json()) .then((data) => console.log(data)) 

PHP

In PHP, use file_get_contents(«php://input») to get the string json and json_decode to get a php object as shown below. Note that what your javascript fetch call is expecting as returned data is only the json string

PHP

first_name; // $last_name = $object->last_name; // echo $first_name; // echo "
"; // echo $last_name; ?>

First your js file is missing one curly brace

 method: "POST", body: JSON.stringify(data), headers: < "Content-Type": "application/json; charset=UTF-8" >>) .then((response) => response.json()) .then((data) => console.log(data)) 

Also, in your php, you need send back a json something like

 //if want to access values $_arr = json_decode($content, true); $first_name = $_arr["first_name"]; $last_name = $_arr["last_name"]; //do what ever you want to do with first_name and last_name //after you are done, be sure to send back a json echo json_encode(['success'=>true]); exit() 

Php — Want to use both GET and POST methods, It is doable, no problem. There is the $_REQUEST array that merges GET, POST, and COOKIE values but the better way would be to handle GET and POST manually in your script. Just have your engine check both $_GET [«variable»] and $_POST [«variable»] and use whichever is set. If a variable is set in …

Adding a user using fetch with POST method

Using the following code, I’m trying to add a new user and console log all users including the new added one:

const url = "https://jsonplaceholder.typicode.com/users"; // Creating a user fetch(url, < method: "POST", body: JSON.stringify(< name: "Robert Miller", username: "robby", email: "roby@outlook.com" >), headers: < Accept: "application/json, text/plain, */*", "Content-Type": "application/json" >>) .then(response => response.json()) .then(response => console.log(response)); 

However, the console.log shows only the added user but not all users. My assumption was that because the method of the fetch is POST, I need to send another request via GET to get all users and came up with this:

const url = "https://jsonplaceholder.typicode.com/users"; // Creating a user fetch(url, < method: "POST", body: JSON.stringify(< name: "Robert Miller", username: "robby", email: "roby@outlook.com" >), headers: < Accept: "application/json, text/plain, */*", "Content-Type": "application/json" >>) .then(response => response.json()) .then(response => console.log(response)); fetchAllUsers(); function fetchAllUsers() < fetch(url) .then(response => < if (!response.ok) < throw Error(response.statusText); >// Read the response as json. return response.json(); >) .then(data => < // Do stuff with the JSON console.log(data); >) .catch(error => < console.log("Looks like there was a problem: \n", error); >); > 

But I still cannot see the added user in the list. Any help?

I think this link is answer your question: Unable to post a new user

Since JSONPlaceholder is a shared API used by many, modifications are faked (POST, PUT, PATCH) and resources are read-only. This is to avoid user «A» creating new resources and having user «B» impacted by them.

If you need to make changes and persist them between calls, you can run JSON Server locally.

Javascript — POST Request with Fetch API?, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

Simple POST request using the fetch API

The fetch() method , like the XMLHttpRequest and Axios request, is used to send the requests to the server. The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API. You will get the whole Get and Post method using fetch API

fetch(url, < config >) .then(res => < // Handle response >) .catch(err => < // Handle errors >)

Create a POST request using fetch(): The POST request is widely used to submit forms to the server.

Источник

How to use fetch in JavaScript to GET or POST data

The fetch command is an asynchronous function which allows you to send and receive data in JavaScript — commonly used for getting data from an API or similar.

GET data

The default method for fetch is GET . This allows you to pass in a URL and get the data from the other end. In the example below we are retrieving a JSON API. Using promises, the data is parsed and then made available for use.

The thing to note with asynchronous functions (in laymen’s terms) is, although they fire when executed, they do not stop the rendering of the page. If part of your code requires the fetch to be complete before firing, ensure it is triggered in the promise (the then function).

fetch(URL) .then(data => data.json()) .then(data =>  // data is your API data >); ``` ## POST data There may be instances when your JavaScript code or app may wish to POST data to your backend code. This can be achieved using `fetch` also. Consider this example which includes the `JSON.stringify()` function - this [converts a json object into a JSON string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). ```js let data =  key: "value" >; fetch(URL,  method: 'post', body: JSON.stringify(data) >).then(data =>  // data is anything returned by your API/backend code >);

Bonus: PHP example

This one took me a while to figure out, but capturing the POST variables from your fetch function in a PHP script is not as obvious as it initially seems!

The key is using php://input — which is a readable stream which contains the data as a JSON string (as sent with the fetch function). This can be decoded using the native PHP function.

 $input = json_decode(file_get_contents('php://input'), true); // $input['key'] would equal "value" 

If you were to remove the true from the end of the json_decode , your data would be available as a PHP object instead, meaning you would access «value» using $input->key .

Источник

Читайте также:  Python online compiler idle
Оцените статью