D
D
ddeel2020-10-20 09:54:07
PHP
ddeel, 2020-10-20 09:54:07

How to send json post request to javascript?

How to send post request json to javascript and get it to php?
Sending data not through a form, but by a condition, for example, if(){}
It is necessary on pure js, without jquery
Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eternalfire, 2020-10-20
@eternalfire

const url = 'https://example.com/profile';
const data = { username: 'example' };

try {
  const response = await fetch(url, {
    method: 'POST', // или 'PUT'
    body: JSON.stringify(data), // данные могут быть 'строкой' или {объектом}!
    headers: {
      'Content-Type': 'application/json'
    }
  });
  const json = await response.json();
  console.log('Успех:', JSON.stringify(json));
} catch (error) {
  console.error('Ошибка:', error);
}

https://developer.mozilla.org/ru/docs/Web/API/Fetc...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question