简体   繁体   中英

Api rest link and javascript popup

Could someone tell me what I might be doing wrong in this link from the wordpress api with the sweetalert2 popup?

I'm making sure that when I click on the popup button, I cancel the subscription, but I'm not getting a return on the popup.

Below my javascript code with sweetalert2, I believe the error is in the DATA part, but I can't solve it.

             <script type="text/javascript">
    jQuery(document).ready(function($) {
        $('.submit-acoes-pausar-<?php echo $today_conferir = date('Y-m-d', strtotime($date_calc)); ?>')
                                .click(
                                    function() {
            var id = $(this).data("id");
            (async () => {
                const { value: cancelamento } = await Swal.fire({
                    title: 'IMPORTANTE',
                    text: 'Deseja realmente CANCELAR TODOS os pedidos desta assinatura a partir da data selecionada?',
                    input: 'textarea',
                    inputPlaceholder: 'Coloque sua mensagem aqui...',
                    showConfirmButton: true,
                    showCancelButton: true,
                    confirmButtonText: 'Cancelar',
                    confirmButtonColor: '#ff0000',
                    cancelButtonText: 'Voltar',
                    cancelButtonColor: '#d3d3d3',
                })

                if (cancelamento) {
                     //alert(id);
                     //Swal.fire(`Preço: ${price}`)
                    $.ajax({
                        url: "' . get_site_url() . '/wp-json/oinb/v1/add/cancelamento",
                        type: "POST",
                        dataType: "json",
                        headers: {
                            "Access-Control-Allow-Origin": "*"
                        },
                        data: {
                          "id_lista": id,
                          "dt_ppa": dt,
                          "acao_ppa": acao,
                          "id-cliente": cliente,
                        },
                        success: function (data) {
                            if (data["success"]==true) {
                                Swal.fire({
                                    icon: "success",
                                    title: "Sucesso",
                                    title: data["message"]
                                })
                            } else {
                                Swal.fire({
                                    icon: "error",
                                    title: "Oops...",
                                    text: data["message"]
                                })
                            }
                        },
                        error: function (data) {

                            Swal.fire(
                                "Ocorreu um erro",
                                `valor: ${cancelamento} | data-id: ${message}`,
                                "error"
                            )

                        }
                    });
                }
            })()
        });
    });
</script>';

API

API is already working, I just need to implement it in the popup

  <?php

$dir = plugin_dir_path(_DIR_);
include_once($dir . 'emails/custom-mail.php');
require_once($dir . "utils/functions.php");

add_action(
    'rest_api_init',
    function () {
        register_rest_route(
            'oinb/v1',
            '/add/cancelamento',
            array(
                'methods' => 'POST',
                'callback' => 'add_cancelamento',
            )
        );
    }
);

function add_cancelamento(WP_REST_Request $request)
{
    $id_lista = $request['id_lista'];
    $dt_ppa = $request['dt_ppa'];
    $acao_ppa = $request['acao_ppa'];
    $date_now = date('d/m/Y');
    $user_id = get_post_meta($id_lista, 'id-cliente', true);
    $user_info = get_userdata($user_id);
    $user_email = $user_info->user_email;

        $new_assinatura = array(
            'post_status' => 'publish',
            'post_type'      => 'acaoprogramada',
            'post_title' => 'AçãoProgUser:' . $user_id . 'ListaDeCompras:' . $id_lista . '-Date:' . $dt_ppa,
            'meta_input' => array(
                'id_lista' => $id_lista,
                'dt_programada' => $dt_ppa,
                'frequencia' => '',
                'status_ass' => $acao_ppa,
                'dt_add' => $date_now,
                'dt_edit' => $date_now,
            )
        );
        $create_cancelamento = wp_insert_post($new_assinatura);

        if ($create_cancelamento > 0){

            $to = $user_email;
            $subject = 'Sua Assinatura de Orgânicos será CANCELADA!';
            $titulo_email = 'Sua assinatura foi cancelada';
            $texto_email = 'Sua assinatura foi cancelada com sucesso. Caso deseje reativá-la, <a href="https://www.organicosinbox.com.br/minha-conta/">clique aqui</a> e volte a receber sua cesta a qualquer momento.<br/>Gratidão e até breve!';
            //$texto_email = 'De acordo com os ajustes que você realizou no nosso site, a sua lista de compras será desativada no dia '.$dt_ppa_oriiginal.'. Caso deseje reativar basta acessar sua conta  e cancelar o cancelamento.';
            $body = customFormatMailOinb($titulo_email, $texto_email);
            $headers = array('Content-Type: text/html; charset=UTF-8');
            wp_mail($to, $subject, $body, $headers);

            print json_encode(array('success' => true, 'message' => 'Cancelamento efetuado'));
        } else {
            print json_encode(array('error' => false, 'message' => 'Cancelamento NÃO efetuado'));
        }
        
}

Are you sure Swal.fire promise returns its result in an "value" object key?

I would try a

Swal.fire({
  title: 'TEST',
  text: "blabla",
  icon: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Unsubscribe'
}).then(result => { console.log(result)})
.catch(error => { console.log(error) })

Then inspect the result object returned.

Also I wouldn't use await blocking statements, JS is asynchronous by nature. furthermore you don't really need to keep showing the modal to your user, as you will fire another alert feedback to tell if the action succeeded or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM