@tokyodead

Как получить данные с формы обратной связи, и обработать их в своём скрипте PHP?

Есть форма обратной связи, обработчик этой формы вроде этот код.
import axios from "axios";
import Modal from "@js/components/modal";
import Cookies from 'js-cookie'

export default {
    form: document.querySelector('#modal-callback .js-callback-form'),
    msg: document.querySelector('#modal-callback .js-callback-msg'),
    inner: document.querySelector('#modal-callback .js-callback-inner'),
    phoneInput: document.querySelector('#callback-phone'),
    nameInput: document.querySelector('#callback-name'),
    title: document.querySelector('#modal-callback .js-title'),
    submitBtn: document.querySelector('#modal-callback .js-submit-btn'),
    defaultTitle: 'Давайте мы вам позвоним',
    errorClass: 'modal__input--error',

    sendMail(e) {
        this.phoneInput.setAttribute('disabled', 'true');
        this.submitBtn.setAttribute('disabled', 'true');
        this.nameInput.setAttribute('disabled', 'true');

        let phone = e.target[1].value;
        let name = e.target[0].value;

        const headers = {
            'X-OCTOBER-REQUEST-HANDLER': 'onCallbackMailSend',
            'X-OCTOBER-REQUEST-PARTIALS': '',
            'X-Requested-With': 'XMLHttpRequest'
        };

        return axios({
            method: "POST",
            url: window.location.href,
            headers: headers,
            data: {name: name, phone: phone}
        }).then(response => {
            $(this.inner).stop(0).slideToggle();
            this.msg.style.display = 'block';
            setTimeout(() => {
                this.modalInstance.close();
            }, 2000);
        });
    },

    init() {
        this.modalInstance = new Modal({
            trigger: '.js-callback-trigger',
            modal: document.getElementById('modal-callback'),
            callbackOpen: (target) => {
                if(target == null) {
                    this.title.innerHTML = this.defaultTitle;
                    return false;
                }

                let title = target.getAttribute('data-title');

                if(title != null) {
                    this.title.innerHTML = title;
                } else {
                    this.title.innerHTML = this.defaultTitle;
                }
            },
            callbackClose: () => {
                this.phoneInput.removeAttribute('disabled');
                this.phoneInput.value = '';
                this.nameInput.removeAttribute('disabled');
                this.nameInput.value = '';
                this.submitBtn.removeAttribute('disabled');
                this.msg.style.display = 'none';
                this.inner
                    .style
                    .cssText = `display:block;height:initial;`;
            }
        });

        this.modalInstance.init();

        setInterval(() => {
            if(Cookies.get('modalViewed') == null) {
                this.modalInstance.open();
                Cookies.set('modalViewed', 'true', { expires: 1 })
            }
        }, 30000);

        this.phoneInput.addEventListener('input', () => {
            if (this.phoneInput.classList.contains(this.errorClass)) {
                this.phoneInput.classList.remove(this.errorClass);
            }
        });

        this.form.addEventListener('submit', (e) => {
            e.preventDefault();
            let isValid = this.phoneInput.value.replace(/[^0-9]/g, '').length === 11;
            isValid ? this.sendMail(e) : this.phoneInput.classList.add(this.errorClass);
        })
    }
}


Делаю интеграцию формы сайта с CRM Bitrix, подскажите пожалуйста, как получить с такой формы данные которые ввел пользователь.
  • Вопрос задан
  • 126 просмотров
Пригласить эксперта
Ответы на вопрос 2
ThunderCat
@ThunderCat Куратор тега JavaScript
{PHP, MySql, HTML, JS, CSS} developer
0) Проверить консоль браузера на ошибки
1) Включить вывод ошибок в пхп
2) проверить что ваш скрипт вообще что-то отправляет во вкладке нетворк (и что отправляет то что надо)
3) так же в нетворк смотреть что пришло из ответа на запрос аяксом, если ошибка - исправлять
вроде все
Ответ написан
Комментировать
artloveyou
@artloveyou
url: window.location.href <- ваша форма шлёт данные по адресу, который у вас в гет-строке,
методом пост method: "POST"
Соответственно по этому же адресу у вас должен быть бэк экшен который принимает пост запрос. А в нем уже забираете (в общем случае через $_POST) эти данные data: {name: name, phone: phone}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы