Create object and send by ajax - Codeigniter

1

Hello,

Can you help me create an object with this code and send it via ajax.

console.log("cadastro-assessoria trabalhando");
//Variáveis

$(document).ready(function() {
	$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
		e.target // activated tab
        var target_tab = e.target.href.split('#')[1];
		set_tabindex(target_tab);
		console.log(target_tab);
	});	
	obter_assessoria_ajax();
	/*** Eventos ***/
    $('#btn_salvar').click(function () {
	    salvar_assessoria();
    });

});

function obter_assessoria_ajax() {
    var ret;
    $.ajax({
        type: 'GET',
		dataType: "JSON",
	    url : "assessoria/obter_assessoria",
        success: (function (tbl_assessoria) {
            _obj_assessoria = tbl_assessoria;
			console.log(tbl_assessoria);
            obj_form();
            ret = true;
        }),
        error: (function (erro) {
            //TrataErroAjax(erro);
            ret = false;
        })
    });
    return ret;
}

function obj_form()
{
	$('#txt_id').val(_obj_assessoria.id);
	$('#txt_cnpj').val(_obj_assessoria.cnpj);
	$('#txt_inscricao_estadual').val(_obj_assessoria.inscricao_estadual);
  $('#txt_razao_social').val(_obj_assessoria.razao_social);
  $('#txt_nome_fantasia').val(_obj_assessoria.nome_fantasia);
	$('#txt_logradouro').val(_obj_assessoria.logradouro);
	$('#txt_numero').val(_obj_assessoria.numero);
	$('#txt_complemento').val(_obj_assessoria.complemento);
	$('#txt_bairro').val(_obj_assessoria.bairro);
	$('#txt_cidade').val(_obj_assessoria.cidade);
	$('#txt_cep').val(_obj_assessoria.cep);
	$('#txt_uf').val(_obj_assessoria.uf);
	$('#txt_observacao').val(_obj_assessoria.observacao);
	$('#txt_nome').val(_obj_assessoria.nome);
	$('#txt_telefone').val(_obj_assessoria.telefone);
	$('#txt_celular').val(_obj_assessoria.celular);
	$('#txt_email').val(_obj_assessoria.email);
	$('#txt_qtde_licenca').val(_obj_assessoria.qtde_licenca);
	//Formato Data pt-br		
    var dt_expiracao = _obj_assessoria.dt_expiracao.split('-').reverse().join("/");    
	$('#txt_dt_expiracao').val(dt_expiracao);
	$('#txt_chave').val(_obj_assessoria.chave);
	set_mascara();
}

function salvar_assessoria() {
	$('#btn_salvar').html('<i class="fa fa-spinner fa-spin"></i> Salvando');
	$('#btn_salvar').attr('disabled', true);
	remove_mascara();
    var ret;
    $.ajax({
        type: 'POST',
        datatype: 'JSON',
		url : "assessoria/salvar_assessoria",
		data: $('#form').serialize(),
		success: function(data){
		    console.log(data);
		    $('#btn_salvar').html('<i class="fa fa-save"></i> Salvar');
            $('#btn_salvar').attr('disabled', false);
		    toastr.success('Cadastro atualizado com sucesso');
		    ret = true;		   
       },		
        error: function (erro) {		    
            //TrataErroAjax(erro);
			toastr.danger('Erro ao salvar');
			alert(erro);
            ret = false;
		}
	});
	event.preventDefault();
    return false;
}

/*** Operações da tela ***/
//Função para adicionar index aos tabs
function set_tabindex(tab) {
    var lb_desbloquear = '';
    if (tab == "tab_licenca_uso") {
        _index_tab = 2;
        lb_desbloquear = 'Desbloquear';
	} else {
        _index_tab = 1;
	}
	
    $('#btn_desbloquear_item span').text(lb_desbloquear);
	
    if (_index_tab > 1)
	$('#btn_desbloquear_item').show();
    else
	$('#btn_desbloquear_item').hide();
}

$("#btn_desbloquear_item").click(function() {
  //$("#qtde_licenca").attr('disabled', !$("#qtde_licenca").attr('disabled'));
  //$("#dt_expiracao").attr('disabled', !$("#dt_expiracao").attr('disabled'));
  //$("#chave").attr('disabled', !$("#chave").attr('disabled'));  
});

I know that at the time of sending I would send it like this: data: { 'objeto': JSON.stringify(objeto_criado) },

My intention is to send as an object to be able to treat the fields that contain masks, for example CNPJ, CEP, TELEPHONE, etc ...

In the current way, you are sending without being able to remove the masks from the field. Or if there is a possibility I do not know.

    
asked by anonymous 23.08.2017 / 18:41

2 answers

1

For you to transform your entire form into JSON Object format, do:

var formulario = JSON.parse(JSON.stringify($('#form').serializeArray()))

Now you can access each item of this object and treat it the way you want it.

  

Where JSON.parse() converts a string to JSON.

     

Where JSON.stringify() converts javascript values to a string   JSON.

     

Where serializeArray() creates an array of objects.

If you still have questions, go to this jsfiddle and open your browser console (Chrome is F12) and see the solution working.

    
24.08.2017 / 21:46
0

If you want to remove the mask before sending the results via ajax, the library github.com/igorescobar/jQuery-Mask-Plugin has the unmask() function available. So your remove_mascara(); function should be something like this

function remove_mascara(){
    $('#txt_cnpj').unmask();
    $('#txt_cep').unmask();
    ......

    //Talvez para que o objeto atualiza voce precisa fazer isto.
    //Tenta fazer sem primeiro
    $('#txt_cnpj').trigger('change');
    ....
}

I've never used this library so more than seeing it, I think this should work.

    
23.08.2017 / 23:13