php receive post code example

Example 1: php post

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Name: <input type="text" name="fname">
  <input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  // do logic
  $name = $_POST['fname'];
}
?>

Example 2: php get

<form method="GET">
  <input type="text" name="someName">
  //The Name Attribute will be put into the _GET inside of php 
  <input type="submit" value="Submit">
 </form>
  
<?php
$var = $_GET("someName");
echo ($var);
?>

Example 3: php receive post

// Send data trough e.g. AJAX in JavaScript

$.ajax({
    type: "POST",
    url: 'example.php',
    data: { "num1": 1, "num2": 2},
    contentType: "application/json; charset=utf-8",
    dataType: "JSON",
    async: false
})

// You would receive it like this:
  
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];

$sum = $num1 + $num2;
echo $sum;

// Would output: 3

Tags:

Php Example