Passing data from JavaScript to PHP using fetch API

Hey everyone! I’m a newbie when it comes to using the fetch API. I’m trying to send some data from my JavaScript file (running on a Node.js server) to a PHP file (on an Apache server). I’ve got two JSON values, ‘a’ and ‘b’, that I want to send.

Here’s what my code looks like right now:

fetch('http://localhost/myapp/api.php', {
  method: 'POST',
  body: JSON.stringify({
    x: 10,
    y: 20
  })
}).then(response => {
  if (response.ok) {
    return response.text();
  }
  throw new Error('Network response was not ok');
}).then(data => {
  console.log(data);
}).catch(error => {
  console.error('There was a problem with the fetch operation:', error);
});

I’m using React for my frontend. Can anyone help me figure out how to get the values of ‘x’ and ‘y’ in my PHP file? Thanks in advance!

To retrieve the values of ‘x’ and ‘y’ in your PHP file, you’ll need to parse the incoming JSON data. Here’s how you can modify your PHP script to handle this:

<?php
$json = file_get_contents('php://input');
$data = json_decode($json, true);

$x = $data['x'] ?? null;
$y = $data['y'] ?? null;

if ($x !== null && $y !== null) {
    // Process the data
    $result = $x + $y; // Example operation
    echo json_encode(['result' => $result]);
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid input']);
}

This script reads the raw POST data, decodes the JSON, and extracts the ‘x’ and ‘y’ values. It then performs a simple operation and sends back a JSON response. Make sure to set the appropriate headers in your PHP file for JSON responses. Also, consider implementing proper error handling and input validation for production use.

hey ameliat, u might wanna add some headers to ur fetch request. try this:

headers: {
‘Content-Type’: ‘application/json’
}

also, make sure ur php file is set up to handle json input. u can use file_get_contents(‘php://input’) to grab the raw data and then json_decode() it. hope that helps!

Hey there! I’ve been in your shoes before, and I can tell you it can be a bit tricky at first. One thing that really helped me was setting the correct headers on both ends. In your JavaScript, try adding:

headers: {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}

This tells the server you’re sending JSON and expecting JSON back. On the PHP side, make sure you’re setting the correct headers too:

header('Content-Type: application/json');

Also, don’t forget to handle CORS if your frontend and backend are on different domains. It saved me a lot of headaches later on. Good luck with your project!