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

  • 0
    Hello everyone!

    Can you please tell me how you can transfer all the data from localstorage to php to send them by mail? And is it possible?
    JavaScript Anonymous, Mar 4, 2019

  • 2 Answers
  • 0
    Simple enough. Let's say we have written something in localStorage using the test key:

    localStorage.setItem ('test', 'Something');



    To send this data to the server, simply do:

    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, pass the key for localStorage as the first parameter, and the link to your handler as the second parameter, this handler on the server side should already receive data.
    Anonymous

  • 0
    Use Ajax requests to the server

    https://learn.javascript.com/fetch
    Mia Ramirez

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!