Search code examples
javascriptajaxobjectsweetalert

Problem adding a key-value item to an object using sweet alert 2


I have a problem catching a input value through Sweet Alert. I'm sending an Object called data, and then i need to push in that object a key-value item, but there's no way to include it.

$("#Enviar").click(function (e) {
e.preventDefault();
var venta_id = $('#venta_id').val();
var total = $('#total').val().replace(".", "");
var descuento = $('#descuento').val();
var abono = $('#abono').val();
var saldo = $('#saldo').val();
var comentarios = $('#comentarios').val();
var fechaEntrega = $('#fechaEntrega').val();
var vendedor = $('#vendedor').val();
var formaPago = $('#formaPago').val();
var tipoDoc = $('#tipoDoc').val();
var token = '{{csrf_token()}}';
var data={_token:token,venta_id:venta_id,totalAPagar:total,descuento:descuento,abono:abono,saldo:saldo,comentarios:comentarios,fechaEntrega:fechaEntrega,vendedor:vendedor,formaPago:formaPago,tipoDoc:tipoDoc};
Swal.fire({
  title: 'Multiple inputs',
  html:'<input id="swal-input1" class="swal2-input">',
  focusConfirm: false,
  type: 'info',
  preConfirm: () => {
    return [
      document.getElementById('swal-input1').value
    ]
  }
}).then((result) => {
    if (result.value) {
       //const numeroDoc = result.value;
       console.log(result.value);
      data.push({numeroDoc:numeroDoc});            //THIS IS WHERE I CANT INCLUDE THE VALUE
    }
}).then(function(){
$.ajax({
    type: "post",
    url: "{{route('ventaCorrecta')}}",
    data: data,
    success: function (msg) {
      swal({
          title: '¡Venta realizada!',
          text: 'La venta ha sido registrada en el sistema',
          type: 'success',
          allowOutsideClick: "false"
        }).then(function() {
            window.location.href = "{{route('home')}}";
        })
      }
  });
});

});


Solution

  • It looks like you're trying to use push on an object (data) which is not a valid function.

    Instead, you'll have to have to add the numeroDoc property to the object using dot notation.

    if (result.value) {
      data.numeroDoc = result.value;
    }
    

    For more information about working with objects, visit the MDN page.