E
E
Evgeniy2020-10-25 21:38:21
PHP
Evgeniy, 2020-10-25 21:38:21

How to send cart data from localstorage in form via ajax php?

Hi all!

Please tell me how can I transfer all the data from localstorage to php in order to send them as an application to the mail? And is it possible?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nadim Zakirov, 2020-10-25
@Zheleznov

Simple enough. Suppose we have something written in localStorage by the key test : To send this data to the server, simply run:
localStorage.setItem('test', 'Что-то');

sendInfo('test', 'https://ваш_сайт/handler.php');

function sendInfo(key, url) {

  // Создаем форму в конструкторе:
  var formData = new FormData();

  // Добавляем поле с данными в форму:
  formData.append(key, localStorage.getItem(key));

  // Создаем запрос:

  var xhr = new XMLHttpRequest();
  xhr.open('POST', url);
  
  // Обработка ответа:
  
  xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE) {
      if (xhr.status === 200) {
        alert('Запрос выполнен успешно, ответ сервера: ' + xhr.responseText);
      }
      else {
        alert('При выполнении запроса произошла неизвестная ошибка!');
      }
    }
  }
  
  // Отправка:
  
  xhr.send(formData);

}

In the sendInfo function, as the first parameter, pass the key for localStorage , and as the second parameter, a link to your handler, this handler on the server side will already have to receive the data.

A
Alexander Cheremkhin, 2020-10-25
@Che603000

Use Ajax requests to the server
https://learn.javascript.ru/fetch

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question