如何将输入数据从AMP-FORM发送到外部API,以及如何在wordpress数据库中记录相同的数据?

时间:2019-10-24 11:41:46

标签: php ajax wordpress forms amp-html

网站和表单都是AMP-HTML,我尝试使用admin-post和admin-ajax发送到API并将所有输入数据存储到Wordpress数据库,我成功发送了电子邮件,并且存储到数据库,但是,要发送到外部API,我不知道发生了什么,它不会在控制台中显示任何错误消息,因为APM-FORM使用ajax,我不知道是否在内部调用另一个ajax给出错误与否,不知道如何解决。

想法是,在填写表格并提交之后,第一步是将所有数据发送到外部API,此后,无论成功与否,都将该表格存储在数据库中并将电子邮件发送给收件人电子邮件。

我成功使用CFDB(联系表单数据库)存储了数据,并使用phpmailer发送了电子邮件。我同时使用了admin-ajax和admin-post调用,但是没有成功发送到外部API。

在Linux,PHP 7.3,MariaDB,Apache 2.4和Nginx中工作。

使用admin-post的AMP-FORM示例

<form id="orcamento-form" class="orcamento-form custom-forms"
    method="post"
    on="submit:header-before.hide;submit-success:header-after.show,page.scrollTo(duration=200)"
    custom-validation-reporting="show-all-on-submit"
    action-xhr="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
    target="_top">

    <?php wp_nonce_field( 'test_form_action', 'test_form_nonce' ); ?>
    <input type="hidden" name="action" value="form_orcamento">
    <input type="hidden" name="form_type" value="Orçamento">

    <label for="nome">Nome</label>
    <input id="nome" type="text" name="nome" required tabindex="1">
    <span class="warning" visible-when-invalid="valueMissing" validation-for="nome">Campo obrigatório.</span>

    <input type="submit" value="Solicitar Orçamento" tabindex="1">

    <div submitting class="submitting">
        <template type="amp-mustache">
            Olá {{nome}}, estamos processando sua solicitação.
        </template>
    </div>

    <div submit-success class="submit-success">
        <template type="amp-mustache">
            Formulário enviado com sucesso.
        </template>
    </div>
</form>

functions.php示例

/**
 * Form Up Study Orçamento
 *
 * @return void
 */
function amp_form_orcamento() {

    if ( ! isset( $_POST['test_form_nonce'] ) || ! wp_verify_nonce( $_POST['test_form_nonce'], 'test_form_action' ) ) {
        wp_send_json_error( 'Falha na verificação de nonce.' );
    }

    // Define headers for AMP cross origin.
    header( 'access-control-allow-credentials:true' );
    header( 'access-control-allow-headers:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token' );
    header( 'access-control-allow-methods:POST, GET, OPTIONS' );
    header( 'access-control-allow-origin:' . $_SERVER['HTTP_ORIGIN'] );
    header( 'access-control-expose-headers:AMP-Access-Control-Allow-Source-Origin' );
    header( 'amp-access-control-allow-source-origin:https://' . $_SERVER['HTTP_HOST'] );
    header( 'Content-Type: application/json' );

    // Initialize phpmailer class.
    global $mailer;

    /* carrega todas variáveis */

    /**
     * Send the Email throught PHPMailer, if success send to the Edvisor API.
     */
    if ( ! $mailer->Send() ) {

        // Deu erro no envio da mensagem pelo PHPMailer.
        wp_send_json(
            array(
                'error'   => $mailer->ErrorInfo, // phpcs:ignore
                'message' => 'Falha ao enviar o email.',
            ),
            400
        );
    } else {

        // Email enviado através do PHPMailer com sucesso, enviar para API Edvisor.
        ?>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
    <script type="text/javascript">
    jQuery( document ).ready(function($) {
        var formData = {
            "agencyId"  : 1234,
            "firstname" : "<?php echo esc_html( $firstname ); ?>",
            "lastname"  : "<?php echo esc_html( $lastname ); ?>",
            "email"     : "<?php echo esc_html( $email ); ?>",
        }
        $.ajax({
            url: 'https://app.edvisor.io/api/v1/student?public_key=PUBLIC_KEY',
            data: JSON.stringify(formData),
            type: 'PUT',
            dataType: 'json',
            contentType: 'application/json; charset=UTF-8',
            processData: false
        })
            .done(function(response, textStatus, jqXHR) {
                console.log( 'OK' );
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                console.log( 'ERROR' );
            });
    });
    </script>
        <?php
    }

    $mailer->ClearAllRecipients();
}
add_action( 'admin_post_nopriv_form_orcamento', 'amp_form_orcamento' );
add_action( 'admin_post_form_orcamento', 'amp_form_orcamento' );

我无法确定发送到API的内容或返回的错误,因为控制台未显示任何消息,因此为空白...

我很高兴看到API返回了成功的响应。

0 个答案:

没有答案