Capture the value entered in the input to submit using jQuery

0

I need to lock the shopping cart of a shop made in Prestashop, until the person types the email, or logs in after inserting merchandise into the cart.

Then I made the following implementation in Control:

protected function processChangeProductInCart()
{
    $cart_products = $this->context->cart->getProducts();
    $this->context->cookie->temp_id_product = $this->id_product;

    $mode = (Tools::getIsset('update') && $this->id_product) ? 'update' : 'add';

    if ((!isset($this->context->cookie->email) &&
        !$this->context->customer->isLogged()) &&
        count($cart_products) >= 1) {

        if (isset($this->context->cookie->id_cart)) {
            $this->context->cart->id = $this->context->cookie->id_cart;
            $this->ajaxDie(Tools::jsonEncode(array(
                     'setMail'=>true,
                      'urlPost' => _MODULE_DIR_.'blockcart/blockcart-ajax-save.php',
                      'urlAutentication' => 'index.php?controller=my-account',
                      'textAutentication' => 'Clique e faça o login',
                      'orTextForm' => 'ou preencha seu e-mail abaixo:',
                      'labelEmail' => 'E-mail',
                      'id_cart' => $this->context->cookie->id_cart
                )));

        }
        return;
    }
     //...removi o restante (desnecessário)
}

The file that makes the save (blockcart-ajax-save.php):

<?php
include(dirname(__FILE__).'/../../config/config.inc.php');
include(dirname(__FILE__).'/../../init.php');
$context = Context::getContext();
$blockCart = Module::getInstanceByName('blockcart');
echo $blockCart->postProcess();

The process is this:

 public function validateEmail($params)
    {
        return filter_var($params, FILTER_VALIDATE_EMAIL);
    }

    public function postProcess()
    {
        if (Tools::getValue('email') && Tools::getValue('id_cart')) {
            $email = Tools::getValue('email');
            $this->id_cart = Tools::getValue('id_cart');
            $json = $this->setEmailCustomer($email);
            $json = Tools::jsonEncode($json);
            return $json;
        } else {
            $json = array(
                'errors' => array(
                                  $this->l('O campo e-mail não pode ficar em branco!')
                           ),
                'success' =>'0'
            );
            return Tools::jsonEncode($json);
        }

    }

    private function saveEmail($email) {
        $this->context->cookie->email = $email;
        $data = array(
            'email' => $email,
            'id_cart' => $this->id_cart,
            'created_at' => date('Y-m-d H:i:s')
        );
        $insertEmail = Db::getInstance()->insert('emails_abandoned_cart', $data);
        return $insertEmail;
    }

    public function setEmailCustomer($params)
    {
        $errors = array();

        if (!$params || empty($params)) {
            $errors[] =  $this->l('O campo e-mail não pode ficar em branco!');
        }
        if ($this->validateEmail($params) === FALSE) {
            $errors[] =  $this->l('Preencha um e-mail válido!');
        }

        if (count($errors)) {
            return array(
                'errors' => $errors,
                'success' =>'0'
            );
        }

        $save = $this->saveEmail($params);

        if ($save) {
            return array(
                'errors' => [],
                'success' => '1'
            );
        } else {
            return array(
                'errors' => array(
                     $this->l('Ocorreu um erro ao tentar salvar o e-mail!')
                ),
                'success' =>'0'
            );
        }
    }

The table I created was this:

  $success = Db::getInstance()->execute('
            CREATE TABLE '._DB_PREFIX_.'emails_abandoned_cart(
            'id_eml_bnd_cart' int(11) NOT NULL AUTO_INCREMENT,
            'email' varchar(255) NOT NULL,
            'id_cart' int(11) NOT NULL,
            'created_at' DATETIME NOT NULL,
            PRIMARY KEY('id_eml_bnd_cart'))
            ENGINE='._MYSQL_ENGINE_.' default CHARSET=utf8');

However, my question is a lot simpler than that, when I run the processChangeProductInCart() method via ajax, it executes a javascript file (ajax-cart.js), using the fancybox and my method that captures this JSON output in jQuery is as follows:

$.ajax({
            type: 'POST',
            headers: { "cache-control": "no-cache" },
            url: baseUri + '?rand=' + new Date().getTime(),
            async: true,
            cache: false,
            dataType : "json",
            data: 'controller=cart&add=1&ajax=true&qty=' + ((quantity && quantity != null) ? quantity : '1') + '&id_product=' + idProduct + '&token=' + static_token + ( (parseInt(idCombination) && idCombination != null) ? '&ipa=' + parseInt(idCombination): ''),
            success: function(jsonData,textStatus,jqXHR)
            {
                if(jsonData.setMail) {
                    var content = '<div class="col-xs-12 col-md-12 clearfix container" style="padding:30px;">\
                                    <form action="'+jsonData.urlPost+'" method="post" class="std save-mail">\
                                      <fieldset>\
                                        <h4 class="product-name"><a href="'+jsonData.urlAutentication+'" class="iframe">'+jsonData.textAutentication+'</a> '+jsonData.orTextForm+'</h4>\
                                        <p class="errors-msg"></p>\
                                        <p class="required text">\
                                        <label for="email">'+jsonData.labelEmail+':</label>\
                                        <input type="text" class="text key-val-mail" id="email_save" name="email_save" data-idcart="'+jsonData.id_cart+'" data-validate="isEmail">\
                                        <button type="button" id="save_mail" class="btn btn-default button button-small save-mail-submit">\
                                        <span>Enviar</span>\
                                        </button>\
                                        </p>\
                                      </fieldset>\
                                    </form>\
                                  </div>';

                    if (!!$.prototype.fancybox) {
                        $.fancybox.open([
                            {
                                type: 'inline',
                                autoScale: true,
                                minHeight: 30,
                                content: content
                            }
                        ], {
                            padding:0
                        });
                    } else {
                        $.getScript('/js/jquery/plugins/fancybox/jquery.fancybox.js', function() {
                            $('<link/>', {
                                rel: 'stylesheet',
                                type: 'text/css',
                                href: '/js/jquery/plugins/fancybox/jquery.fancybox.css'
                            }).appendTo('head');

                            $.fancybox.open([
                                {
                                    type: 'inline',
                                    autoScale: true,
                                    minHeight: 30,
                                    content: content
                                }
                            ], {
                                padding:0
                            });
                        });
                    }

                }

So far so good, the problem occurs when I type the email in the input that opens, it is not publishing the email ... when I execute the function below, it is only receiving the id_cart, it should capture the email here $('.key-val-mail').val() , but it's not rolling, what could it be?

 $(document).on('click', '.save-mail-submit', function(){
        var el = $('.save-mail');
        var data = {
                   'email': $('.key-val-mail').val(),
                   'id_cart': $('.key-val-mail').data('idcart')
                   };
          console.log(data);
        $('.errors-msg').html('');

        $.ajax({
            type: 'POST',
            headers: { "cache-control": "no-cache" },
            async: true,
            cache: false,
            data:data,
            url:el.attr('action') + '?rand=' + new Date().getTime(),
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("TECHNICAL ERROR: \n\nDetails:\nError thrown: " + errorThrown + "\n" + 'Text status: ' + textStatus);
            },
            success:function(XMLHttpRequest, textStatus, errorThrown) {
                var result = JSON.parse(XMLHttpRequest);
                $('[data-idcart]').attr('data-idcart', data.id_cart);
                if (result.success == 1) {
                    $('.save_mail').remove();
                } else {
                    var msgErrors = result.errors;
                    var errorsMsgHTML = '<div class="alert alert-warning" style="margin-top:10px">';
                    if (msgErrors.length) {
                        for (var i in msgErrors) {
                            errorsMsgHTML += '<b>' + msgErrors[i] + '</b>';
                        }
                        errorsMsgHTML +='</div>';
                        $('.errors-msg').html(errorsMsgHTML).animate({ opacity: 100 }, 1000);
                    }

                    setTimeout(function(){
                            $('.errors-msg').animate({ opacity: 0 }, 1000, function() {
                                $('.errors-msg').html('');
                            });
                    }, 4000)
                }
            }
        });
    });
    
asked by anonymous 01.03.2016 / 15:11

1 answer

0

I found the solution, instead of using the click event directly on the button, I passed the event to the form (submit), and using < strong> delegate , I was able to work with the parameters and attributes of the children of the dynamic form:

$(document).delegate('form.save-mail', 'submit', function(e) {
        e.preventDefault();
        var _self = $(this);
        var email = _self.children().find('.key-val-mail').val();
        var data = {
                   'email': email,
                   'id_cart': _self.children().find("#email_save").data('idcart'),
                   'fancybox':_self.children().find(".fancybox-active").val()
                   };
       console.log(data);
        $('.errors-msg').html('');

        $.ajax({
            type: 'POST',
            headers: { "cache-control": "no-cache" },
            async: true,
            cache: false,
            data:data,
            url:_self.attr('action') + '?rand=' + new Date().getTime(),
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("TECHNICAL ERROR: \n\nDetails:\nError thrown: " + errorThrown + "\n" + 'Text status: ' + textStatus);
            },
            success:function(XMLHttpRequest, textStatus, errorThrown) {
                var result = JSON.parse(XMLHttpRequest);
                console.log(result);
                if (data.id_cart != "") {
                    _self.children().find('[data-idcart]').data('idcart', data.id_cart);
                }
                if (result.success == 1) {
                    if (data.fancybox == "true") {
                        $('.fancybox-close').trigger('click');
                        location.reload();
                    } else {
                        e.preventDefault();
                        $('.layer_cart_overlay').hide();
                        $('#layer_cart').fadeOut('fast');
                    }
                    _self.children().find('.save_mail').remove();
                } else {
                    var msgErrors = result.errors;
                    var errorsMsgHTML = '<div class="alert alert-warning" style="margin-top:10px">';
                    if (msgErrors.length) {
                        for (var i in msgErrors) {
                            errorsMsgHTML += '<b>' + msgErrors[i] + '</b>';
                        }
                        errorsMsgHTML +='</div>';
                        _self.children().find('.errors-msg').html(errorsMsgHTML).animate({ opacity: 100 }, 1000);
                    }

                    setTimeout(function(){
                        _self.children().find('.errors-msg').animate({ opacity: 0 }, 1000, function() {
                            _self.children().find('.errors-msg').html('');
                            });
                    }, 4000)
                }
            }
        });
    });
    
01.03.2016 / 19:47