Last active
May 13, 2025 08:39
-
-
Save Shakil-Shahadat/b8c910b897117cb367b203c928ff3cc2 to your computer and use it in GitHub Desktop.
✓ POST Request by Fetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
header( 'Access-Control-Allow-Origin: *' ); | |
$received = file_get_contents( 'php://input' ); | |
echo $received; | |
// Ref: https://www.php.net/manual/en/reserved.variables.post.php#125651 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Method 1 ( Better ) : Send data as JSON | |
let info = { | |
name: 'John Doe', | |
age: 30, | |
salary: 20000 | |
}; | |
fetch( 'post.php', | |
{ | |
method: 'POST', | |
headers: { 'Content-Type' : 'application/json' }, | |
body: JSON.stringify( info ) | |
}) | |
.then( response => response.text() ) | |
.then( data => console.log( data ) ) | |
.catch( error => console.error( 'Error:', error ) ); | |
// Method 2 ( Worse ) : Send data as URL encoded | |
fetch( 'post.php', | |
{ | |
method: 'POST', | |
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' }, | |
body: 'data1=Hello World!&data2=Hello Universe!' | |
}) | |
.then( response => response.text() ) | |
.then( data => console.log( data ) ) | |
.catch( error => console.error( 'Error:', error ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment