How to grab data using fetch() API POST method in PHP?
the parsed text/json, whatever, is then passed to another function as data and here processed ** JS CODE ** so if I’m fetching a php url wich returns a json, when I console.log the data in I should see the html code echoed by the php and the json inside it, instead all I see is a string of numbers like 1137168 (I typedof it and it’s a string. ) You need to write:Demo (watch the network tab when running the fiddle to see the data included in the body): http://jsfiddle.net/2vx0rp3q/ Solution 2: Change data in body as defined here https://developer.mozilla.org/it/docs/Web/API/Fetch_API/Using_Fetch Question: I am trying to fetch values from php file api.php my javascript page has code like this.(this code is not on page api.php) can you please guide me how to fetch value of variable from php file by using fetch.
How to grab data using fetch() API POST method in PHP?
I am trying to use fetch() API POST method in order to grab the post data in PHP.
Here is what I have tried:
var x = "hello"; fetch(url,).then(function(response)< return response.json(); >);
If you want to $_GET[‘x’] , you need to send the data in the querystring:
var url = '/your/url?x=hello'; fetch(url) .then(function (response) < return response.text(); >) .then(function (body) < console.log(body); >);
If you want to $_POST[‘x’] , you need to send the data as FormData :
var url = '/your/url'; var formData = new FormData(); formData.append('x', 'hello'); fetch(url, < method: 'POST', body: formData >) .then(function (response) < return response.text(); >) .then(function (body) < console.log(body); >);
Apparently, when using the Fetch API to send data to a PHP server, you’ll have to handle the request a little different from what you’re used to.
The data you’re «POSTing» or «GETting» is not going to be available in the super global variables since this input is not coming from a multipart-data form or an application/x-www-form-urlencoded
You can get your data by reading the special file : php://input , for example using file_get_contents(‘php://input’) and then try to decode that input with json_decode() .
You can read more about it here:
I use the postData function from MDN:
/** * send_body___receive_response.js * * Can of-course be in tags in HTML or PHP */ async function postData( url='', data= < >) < // *starred options in comments are default values const response = await fetch( url, < method: "POST", // *GET, POST, PUT, DELETE, etc. mode: "same-origin", // no-cors, *cors, same-origin cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: "same-origin", // include, *same-origin, omit headers: < "Content-Type": "application/json", // sent request "Accept": "application/json" // expected data sent back >, redirect: 'follow', // manual, *follow, error referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url body: JSON.stringify( data ), // body data type must match "Content-Type" header >, ); return response.json( ); // parses JSON response into native JavaScript objects > const data = < 'key1': 'value1', 'key2': 2 >; postData( 'receive_body___send_response.php', JSON.stringify( data ) ) .then( response => < // Manipulate response here console.log( "response: ", response ); // JSON data parsed by `data.json()` call // In this case where I send entire $decoded from PHP you could arbitrarily use this console.log( "response.data: ", JSON.parse( response.data ) ); >);
You could just POST data but I like to receive a response that it was successful.
/** * receive_body___send_response.php */ /* Get content type */ $contentType = trim($_SERVER["CONTENT_TYPE"] ?? ''); // PHP 8+ // Otherwise: // $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : ''; /* Send error to Fetch API, if unexpected content type */ if ($contentType !== "application/json") die(json_encode([ 'value' => 0, 'error' => 'Content-Type is not set as "application/json"', 'data' => null, ])); /* Receive the RAW post data. */ $content = trim(file_get_contents("php://input")); /* $decoded can be used the same as you would use $_POST in $.ajax */ $decoded = json_decode($content, true); /* Send error to Fetch API, if JSON is broken */ if(! is_array($decoded)) die(json_encode([ 'value' => 0, 'error' => 'Received JSON is improperly formatted', 'data' => null, ])); /* NOTE: For some reason I had to add the next line as well at times, but it hadn't happen for a while now. Not sure what went on */ // $decoded = json_decode($decoded, true); /* Do something with received data and include it in response */ // dumb e.g. $response = $decoded['key2'] + 1; // 3 /* Perhaps database manipulation here? */ // query, etc. /* Send success to fetch API */ die(json_encode([ 'value' => 1, 'error' => null, 'data' => null, // or ?array of data ($response) you wish to send back to JS ]));
Working example that show how to add two numbers with fetch api using FormData .
For each operation you better have different FormData with its own fields.
const frmAddNumbers = new FormData(); // create single instance frmAddNumbers.set('cmd', "add_numbers"); // this cmd will not change frmAddNumbers.set('first_number', ""); frmAddNumbers.set('second_number', ""); function opAddNumbers(num1, num2) < frmAddNumbers.set('first_number', num1); frmAddNumbers.set('second_number', num2); fetch('./cmd.inc.php', ) .then(res => res.json()) // res.text() .then(res => displayResult(res)) .catch(e => console.error('Error, opAddNumbers(), ' + e)) > function displayResult(response) < console.log(response); document.getElementById("result").innerHTML = `Result = $`; >
$num1 + $num2); $output = json_encode($result); break; > echo $output;
How to fetch data from the database in PHP, There are two ways to connect to a database using PHP. They are as follows. MySQLi (“i” stands for improved) PDO (PHP Data Objects) MySQLi vs …
Fetch() json from php
I’ve got a I’ve got a simple fetch request. I’m not much of an expert in promises and asynch code but from what I understand fetch url sends a request to open/get/post an url and returns a promise (response) of delivering that content. Qhen that content is fetched THEN I can parse it in a text ( Response.text() ) the parsed text/json, whatever, is then passed to another function as data and here processed
fetch(url).then(function(response) < console.log(typeof(response)); return response.text(); >).then(function(data) < console.log('data ', data); >).catch(function(err) < console.log ('ERRORE ', err); >) >
so if I’m fetching a php url wich returns a json, when I console.log the data in I should see the html code echoed by the php and the json inside it, instead all I see is a string of numbers like 1137168 (I typedof it and it’s a string. )
$selectNum = "SELECT num FROM table"; $quer = mysqli_query($conn, $selectNum); while($row = mysqli_fetch_array($quer, MYSQLI_ASSOC)) < $arrayJSON = $row; >header('Content-Type: application/json'); echo json_encode($arrayJSON, JSON_PRETTY_PRINT); mysqli_close($conn);
the php and the js are saparated files
You need to set headers to json on server side and use json_encode to the array you want to return on your request like :
and parse it on client side using jquery like so
var data = /*data retuned from your request*/; $.parseJSON($data);
On your while block you are not using concatination, so your $arrayJSON contains the last row’s num you selected in the query.
How can I use PDO to fetch a results array in PHP?, \PDO::FETCH_ASSOC and \PDO::FETCH_NUM allow you to define fetching mode. \PDO::FETCH_ASSOC will return only field => value array, whilst …
PHP POST using JS Fetch API
I don’t know why it’s not working. It returns empty $_POST .
const updateRequest = new FormData(); updateRequest.append('updateRequest', 'next-period'); fetch('file.php', < method: 'POST', data: updateRequest >) .then((response) => response.text()) .then((text) => < console.log(text); >)
In the PHP file , the server request is POST but var_dump logs true.
According to the documentation, if you want to send data to the server in the request body (as you would for a POST) then you put it in the body option. There is no data option available. If you provide that to the Fetch method it is not expecting it and will simply ignore it. Perhaps you’ve confused it with the syntax for jQuery $.ajax() (which does have a data option) or something?
Demo (watch the network tab when running the fiddle to see the data included in the body): http://jsfiddle.net/2vx0rp3q/
var form = new FormData(document.getElementById('login-form')); fetch("/login", < method: "POST", body: form >);
as defined here https://developer.mozilla.org/it/docs/Web/API/Fetch_API/Using_Fetch
Javascript — fetch api (GET DATA) from php file, Basically i am working with 2 servers right now,, apache and node .js. my apache server(php file) contain public key.. and i want to fetch that …
Fetch api (GET DATA) from php file
I am trying to fetch values from php file
my javascript page has code like this.(this code is not on page api.php)
fetch('http://localhost/react_task/react-webpack-boilerplate/php/api.php', < method: 'get', // may be some code of fetching comes here >).then(function(response) < if (response.status >= 200 && response.status < 300) < return response.text() >throw new Error(response.statusText) >) .then(function(response) < console.log(response); >)
can you please guide me how to fetch value of variable from php file by using fetch.
You are not echoing the value, so it won’t be send.
Your php needs to output the value you want. A simple way to do this is to use echo . For example:
echo 'come!! fetch this value';
You should use echo to display it in php then it will be available in you JavaScript reponse.
How to grab data using fetch() API POST method in PHP?, Add a comment. 1. Remember $_POST in PHP only grabs either formData () or urlSearchParams () data and for other all types of data … Code samplevar formData = new FormData();formData.append(‘x’, ‘hello’);fetch(url, < method: 'POST', body: formData >).then(function (response)
fetch API +PHP БЕЗ jQuery
Как использовать JS fetch без jQuery, но с сервером на PHP – ответ сервера + отсылка данных на сервер.
/*проверим, поддерживает ли browser – fetch?*/ if (window.fetch)*если да*/ function formEncode(obj) *эта функция позволит преобразовать JS Object в валидные данные для POST-запроса*/ var str = []; for(let p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); return str.join("&"); > ; fetch("/", < method: "POST", headers: < "Content-type": "application/x-www-form-urlencoded">, mode: "same-origin", credentials: "same-origin", body: formEncode()/*мне необходимо было передавать содержимок HTML-документа на сервер, чтобы сохранить страницу HTML полностью, после формирования DOM*/ >); >;
// Если файл не обновлялся 3600 секунд (1 час) или файл пуст, // то обновляем его //3600*24 (сутки) if (filemtime($file) <(microtime(true)-(3600*24))) < file_put_contents($file,$_POST['html']); >exit;
Затем можно сформировать ответ сервера:
fetch("/", < method: "POST", headers: < "Content-type": "application/x-www-form-urlencoded">, mode: "same-origin", credentials: "same-origin", body: formEncode()/*мне необходимо было передавать содержимок HTML-документа на сервер, чтобы сохранить страницу HTML полностью, после формирования DOM*/ >).then(resp=>*здесь мы получаем ответ и взаимодействуем с ним*/ resp.json();/*преобразовываем ответ из JSON*/ >).then(data=>< console.log(data)/*выводим данные*/ >);
А также ответ сервера (PHP):
echo json_encode(['data'=>'string','data2'=>'string2']);
. и если это распарсить, как указано в комментариях к JS выше, то получится объект. К нему можно будет обращаться:
. >).then(resp=>*здесь мы получаем ответ и взаимодействуем с ним*/ resp.json();/*преобразовываем ответ из JSON*/ >).then(data=>< console.log(data)/*выводим данные – */ console.log(data.data);/*string*/ console.log(data.data2);/*string2*/ >);
Еще пример распарсивания результата, как объекта:
fetch("/", < method: "POST", headers: < "Content-type": "application/x-www-form-urlencoded">, mode: "same-origin", credentials: "same-origin", body: formEncode()/*мне необходимо было передавать содержимок HTML-документа на сервер, чтобы сохранить страницу HTML полностью, после формирования DOM*/ >) .then(r => r.json().then(data => ())) .then( obj => > ); >;