Related
I know that with the new Fetch API (used here with ES2017's async/await) you can make a GET request like this:
async getData() {
try {
let response = await fetch('https://example.com/api');
let responseJson = await response.json();
console.log(responseJson);
} catch(error) {
console.error(error);
}
}
But how do you make a POST request?
Long story short, Fetch also allows you to pass an object for a more personalized request:
fetch("http://example.com/api/endpoint/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
name: myName,
password: myPassword
})
})
.then( (response) => {
//do something awesome that makes the world a better place
});
Check out the fetch documentation for even more goodies and gotchas:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Please note that since you're doing an async try/catch pattern, you'll just omit the then() function in my example ;)
if you want to make a simple post request without sending data as JSON.
fetch("/url-to-post",
{
method: "POST",
// whatever data you want to post with a key-value pair
body: "name=manas&age=20",
headers:
{
"Content-Type": "application/x-www-form-urlencoded"
}
}).then((response) =>
{
// do something awesome that makes the world a better place
});
The best way to POST form data to a PHP-script is the Fetch API. Here is an example:
function postData() {
const form = document.getElementById('form')
let data = new FormData()
data.append('name', form.name.value)
fetch('../php/contact.php', {
method: 'POST',
body: data,
}).then(response => {
if (!response.ok) {
throw new Error('Network response was not ok.')
}
}).catch(console.error)
}
<form id="form" action="javascript:postData()">
<input id="name" name="name" placeholder="Name" type="text" required>
<input type="submit" value="Submit">
</form>
Here is a very basic example of a PHP-script that takes the data and sends an email:
<?php
header('Content-type: text/html; charset=utf-8');
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
$to = "test#example.com";
$subject = "New name submitted";
$body = "You received the following name: $name";
mail($to, $subject, $body);
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)
})
GET request using Axios:
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()
POST request using Axios:
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()
Here is a solution for a POST request using node-fetch, with async/await.
async function post(data) {
try {
// Create request to api service
const req = await fetch('http://127.0.0.1/api', {
method: 'POST',
headers: { 'Content-Type':'application/json' },
// format the data
body: JSON.stringify({
id: data.id,
foo: data.foo,
bar: data.bar
}),
});
const res = await req.json();
// Log success message
console.log(res);
} catch(err) {
console.error(`ERROR: ${err}`);
}
}
// Call your function
post() // with your parameter of Course
Here is a complete example: After spending hours tinkering with incomplete code snippets I finally managed to post some json from javascript, pick it up using php on a server, added a data field and finally updated the original web page. Here is the HTML, the PHP and the JS. My thanks to everyone who posted the original code fragments collected here. Similar code is on-line here: https://www.nbest.co.uk/Fetch/index.php
<!DOCTYPE HTML>
<!-- Save this to index.php and view this page in your browser -->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Fetch Example</title>
</head>
<body>
<h1>Javascript Fetch Example</h1>
<p>Save this to index.php and view this page in your browser.</p>
<button type="button" onclick="myButtonClick()">Press Me</button>
<p id="before">This is the JSON before the fetch.</p>
<p id="after">This is the JSON after the fetch.</p>
<script src="fetch.js"></script>
</body>
</html>
<!-- --------------------------------------------------------- -->
// Save this as fetch.js --------------------------------------------------------------------------
function success(json) {
document.getElementById('after').innerHTML = "AFTER: " + JSON.stringify(json);
console.log("AFTER: " + JSON.stringify(json));
} // ----------------------------------------------------------------------------------------------
function failure(error) {
document.getElementById('after').innerHTML = "ERROR: " + error;
console.log("ERROR: " + error);
} // ----------------------------------------------------------------------------------------------
function myButtonClick() {
var url = 'json.php';
var before = {foo: 'Hello World!'};
document.getElementById('before').innerHTML = "BEFORE: " + JSON.stringify(before);
console.log("BEFORE: " + JSON.stringify(before));
fetch(url, {
method: 'POST',
body: JSON.stringify(before),
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(response => success(response))
.catch(error => failure(error));
} // ----------------------------------------------------------------------------------------------
<?php
// Save this to json.php ---------------------------------------
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
$decoded['bar'] = "Hello World AGAIN!"; // Add some data to be returned.
$reply = json_encode($decoded);
}
header("Content-Type: application/json; charset=UTF-8");
echo $reply;
// -------------------------------------------------------------
?>
In this article, I described about the Second Parameter of fetch().
For submit JSON data
const user = { name: 'Sabesan', surname: 'Sathananthan' };
const response = await fetch('/article/fetch/post/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(user)
});
For submit form
const form = document.querySelector('form');
const response = await fetch('/users', {
method: 'POST',
body: new FormData(form)
})
For file upload
const input = document.querySelector('input[type="file"]');
const data = new FormData();
data.append('file', input.files[0]);
data.append('user', 'foo');
fetch('/avatars', {
method: 'POST',
body: data
});
I learn MVC and make some AJAX interaction. So I've routes file with
'cart/addProductAjax' => 'cart/addProductAjax',
CartController with actionAddProductAjax:
<?php
class CartController
{
public function actionIndex() {
}
public function actionAdd($productId) {
Cart::addProduct($productId);
$referer = '/';
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
}
header("Location: $referer");
}
public function actionAddProductAjax() {
$productId = $_POST['productId'];
print_r($_POST);
exit;
Cart::addProduct($productId);
$itemsAmount = Cart::countItems();
exit(json_encode($itemsAmount));
}
}
And JS piece of code that send request and receive response from the server:
document.body.addEventListener('click', event => {
if(event.target.classList.contains('add-to-cart')) {
event.preventDefault();
let productId = event.target.dataset.id;
let response = fetch("/cart/addProductAjax/", {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(productId),
})
.then(response => response.json())
.then(response => console.log(response));
}
});
And nothing works. I think there is an error somewhere in PHP method. What shoul I do to make it work?
I'm try to implement the paypal express checkout.
So I implement the button and write the result in my database. Nothing exceptional, it's the script they gave.
<script>
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01'
}
}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Call your server to save the transaction
return fetch('recordDatabase.php', {
method: 'post',
mode: "same-origin",
credentials: "same-origin",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
orderID: data.orderID,
time: details.create_time,
status: details.status,
nom: details.payer.name.given_name,
prenom: details.payer.name.surname,
pays: details.payer.address.country_code,
valeur:details.purchase_units[0].amount.value
})
})
});
}
}).render('#paypal-button-container');
</script>
The php to record in the database:
<?php
$link = connect();
$date = date('Y-m-d H:i:s');
//Receive the RAW post data.
$contentType = isset($_SERVER["CONTENT_TYPE"]) ?trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if(! is_array($decoded)) {
//echo "error";
} else {
$name = $decoded['nom'];
$time = $decoded['time'];
$id = $decoded['orderID'];
$stat = $decoded['status'];
$pays = $decoded['pays'];
$val = $decoded['valeur'];
$secQuery = "INSERT INTO myDatabase(PSEUDO,PASSWORD,CONNECTION,INSCRIPTION,ANNIVERSAIRE,MAIL,IDPAYPAL,STATPAYPAL,NOMPAYER,PAYS,VALEUR) VALUES ('essai','123456',0,'$date','$time','email#mail','$id','$stat','$name','$pays','$val') ";
if (mysqli_query($link,$secQuery)) {
//echo "ok";
} else {
//echo "error";
}
}
} else {
//echo "error";
}
So, the record in my database works fine, but my question is:
How can I retrieve the echo error or ok in the javascript to confirm the user that everything is fine, or if an error happen.
I tried another solution, to redirect the user from the php and add to the php:
header("Location: confirmation web page"); or
echo "<script>window.location = 'confirmation web page'</script>";
but both solution doesn't work. No redirection happen
Correct if i'm wrong, recordDatabase.php is your php file that is storing the transactions.
So, the return fetch('recordDatabase.php', { is returning the response from this file, your echo 'ok';,echo 'error';, the fetch is asyncronous, so it'will return a promise.
Add header('Content-Type: application/json'); to your php file so it returns a json response.
Also change your echo to echo '{"status":"ok"}'; and echo '{"status":"error"}';
Now modify your fetch function,
return fetch('recordDatabase.php', {
//same info here
})
.then((response) => response.json())
.then((responseData) => {
if(responseData.status == "ok"){
alert("it worked");
}else{
alert("it didn't work");
}
})
return fetch('codes/paypalapi.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID
})
});
it will work perfectly
i had the same situation
I have just solved your case , just try this code and see how it works
Paypal Script API
<script>
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01'
}
}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
alert('Transaction completed by ' + details.payer.name.given_name+' ApplicationId <?php echo $id; ?> :payerID'+data.payerID);
// Call your server to save the transaction
return fetch('payments.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID,
time: details.create_time,
status: details.status,
nom: details.payer.name.given_name,
prenom: details.payer.name.surname,
pays: details.payer.address.country_code,
valeur:details.purchase_units[0].amount.value
})
}).then(data => data.ok && data.json()).then(response => {
alert(response.status);
});
});
}
}).render('#paypal-button-container');
</script>
PHP script (payments.php)
<?php
header('Content-Type: application/json');
$date = date('Y-m-d H:i:s');
//Receive the RAW post data.
$contentType = isset($_SERVER["CONTENT_TYPE"]) ?trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if(! is_array($decoded)) {
//echo "error";
} else {
$name = $decoded['nom'];
$time = $decoded['time'];
$id = $decoded['orderID'];
$stat = $decoded['status'];
$pays = $decoded['pays'];
$val = $decoded['valeur'];
echo '{"status":"ok"}';
}
} else {
echo '{"status":"error"}';
}
?>
I want to update my multiple records. But only first record is updating, other ones aren't..
I'm using fetch api for ajax call, but I thins problem is not here, cause I'm able to send array data, I can see in browser dev section. (I mean, I can send multiple id data, it's ok)
Then I'm trying to save them in foreach loop, but only first record is updating in this loop.
in controller
public function approveComment(Request $request)
{
if ($request->ajax()) {
$ids = $request->json()->all();
foreach ($ids as $id) {
$comment = Comments::find($id);
$comment->comment_status = 1;
$comment->save();
}
return response()->json("successful");
} else {
$comment = Comments::find($request->input('comment_id'));
$comment->comment_status = 1;
$comment->save();
return back();
}
}
ajax call;
ajax.put('comments/approve',token,ids)
.then(data => data.json())
.then(log => console.log(log))
.catch(err => console.log(err))
put method in ajax class
async put(url, token, data) {
const response = await fetch(url, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": token
},
method: "put",
credentials: "same-origin",
body: JSON.stringify(data)
});
return response;
}
I find the problem;
public function approveComment(Request $request)
{
if ($request->ajax()) {
$ids = $request->json()->all();
foreach ($ids as $id) {
$comment = Comments::find($id);
$comment->comment_status = 1;
$comment->save();
// return response()->json("successful"); (it was here)
}
return response()->json("successful"); (it should be in here, not in loop)
} else {
$comment = Comments::find($request->input('comment_id'));
$comment->comment_status = 1;
$comment->save();
return back();
}
}
I know that with the new Fetch API (used here with ES2017's async/await) you can make a GET request like this:
async getData() {
try {
let response = await fetch('https://example.com/api');
let responseJson = await response.json();
console.log(responseJson);
} catch(error) {
console.error(error);
}
}
But how do you make a POST request?
Long story short, Fetch also allows you to pass an object for a more personalized request:
fetch("http://example.com/api/endpoint/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
name: myName,
password: myPassword
})
})
.then( (response) => {
//do something awesome that makes the world a better place
});
Check out the fetch documentation for even more goodies and gotchas:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Please note that since you're doing an async try/catch pattern, you'll just omit the then() function in my example ;)
if you want to make a simple post request without sending data as JSON.
fetch("/url-to-post",
{
method: "POST",
// whatever data you want to post with a key-value pair
body: "name=manas&age=20",
headers:
{
"Content-Type": "application/x-www-form-urlencoded"
}
}).then((response) =>
{
// do something awesome that makes the world a better place
});
The best way to POST form data to a PHP-script is the Fetch API. Here is an example:
function postData() {
const form = document.getElementById('form')
let data = new FormData()
data.append('name', form.name.value)
fetch('../php/contact.php', {
method: 'POST',
body: data,
}).then(response => {
if (!response.ok) {
throw new Error('Network response was not ok.')
}
}).catch(console.error)
}
<form id="form" action="javascript:postData()">
<input id="name" name="name" placeholder="Name" type="text" required>
<input type="submit" value="Submit">
</form>
Here is a very basic example of a PHP-script that takes the data and sends an email:
<?php
header('Content-type: text/html; charset=utf-8');
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
$to = "test#example.com";
$subject = "New name submitted";
$body = "You received the following name: $name";
mail($to, $subject, $body);
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)
})
GET request using Axios:
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()
POST request using Axios:
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()
Here is a solution for a POST request using node-fetch, with async/await.
async function post(data) {
try {
// Create request to api service
const req = await fetch('http://127.0.0.1/api', {
method: 'POST',
headers: { 'Content-Type':'application/json' },
// format the data
body: JSON.stringify({
id: data.id,
foo: data.foo,
bar: data.bar
}),
});
const res = await req.json();
// Log success message
console.log(res);
} catch(err) {
console.error(`ERROR: ${err}`);
}
}
// Call your function
post() // with your parameter of Course
Here is a complete example: After spending hours tinkering with incomplete code snippets I finally managed to post some json from javascript, pick it up using php on a server, added a data field and finally updated the original web page. Here is the HTML, the PHP and the JS. My thanks to everyone who posted the original code fragments collected here. Similar code is on-line here: https://www.nbest.co.uk/Fetch/index.php
<!DOCTYPE HTML>
<!-- Save this to index.php and view this page in your browser -->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Fetch Example</title>
</head>
<body>
<h1>Javascript Fetch Example</h1>
<p>Save this to index.php and view this page in your browser.</p>
<button type="button" onclick="myButtonClick()">Press Me</button>
<p id="before">This is the JSON before the fetch.</p>
<p id="after">This is the JSON after the fetch.</p>
<script src="fetch.js"></script>
</body>
</html>
<!-- --------------------------------------------------------- -->
// Save this as fetch.js --------------------------------------------------------------------------
function success(json) {
document.getElementById('after').innerHTML = "AFTER: " + JSON.stringify(json);
console.log("AFTER: " + JSON.stringify(json));
} // ----------------------------------------------------------------------------------------------
function failure(error) {
document.getElementById('after').innerHTML = "ERROR: " + error;
console.log("ERROR: " + error);
} // ----------------------------------------------------------------------------------------------
function myButtonClick() {
var url = 'json.php';
var before = {foo: 'Hello World!'};
document.getElementById('before').innerHTML = "BEFORE: " + JSON.stringify(before);
console.log("BEFORE: " + JSON.stringify(before));
fetch(url, {
method: 'POST',
body: JSON.stringify(before),
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(response => success(response))
.catch(error => failure(error));
} // ----------------------------------------------------------------------------------------------
<?php
// Save this to json.php ---------------------------------------
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
$decoded['bar'] = "Hello World AGAIN!"; // Add some data to be returned.
$reply = json_encode($decoded);
}
header("Content-Type: application/json; charset=UTF-8");
echo $reply;
// -------------------------------------------------------------
?>
In this article, I described about the Second Parameter of fetch().
For submit JSON data
const user = { name: 'Sabesan', surname: 'Sathananthan' };
const response = await fetch('/article/fetch/post/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(user)
});
For submit form
const form = document.querySelector('form');
const response = await fetch('/users', {
method: 'POST',
body: new FormData(form)
})
For file upload
const input = document.querySelector('input[type="file"]');
const data = new FormData();
data.append('file', input.files[0]);
data.append('user', 'foo');
fetch('/avatars', {
method: 'POST',
body: data
});