Create object and send by ajax - Codeigniter

Asked

Viewed 190 times

1

Hello,

Can help me create an object with this code and send by 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 so: 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, ZIP CODE, TELEPHONE, etc...

In its current form, it is sending without my having the possibility to remove the masks from the field. Or if there’s a possibility I don’t know.

  • I do not know if it is the best form and also I have not tested, more and if Voce does $('#txt_cnpj').trigger('change');after you do $('#txt_cnpj').val(_obj_assessoria.cnpj);. See if this doesn’t make your mask appear

  • Because Trigger ?

  • I believe you only show the masks after the ajax returns your information. Using Trigger (translation: trigger) with the 'change' option makes the object act as someone changed its value. I think it might also make your mask show

  • No, the mask is OK; what I want is to remove the mask in the ajax request

  • I understood my Portuguese is not the best

  • Voce has already written the remove_mascara() function; What functions or Libraries are using to apply the masks.

  • https://github.com/igorescobar/jQuery-Mask-Plugin

  • I see that it has the function jMask.remove = function() {&#xA; var caret = p.getCaret();&#xA; p.destroyEvents();&#xA; p.val(jMask.getCleanVal());&#xA; p.setCaret(caret);&#xA; return el;&#xA; };. Ever tried to use.

  • I don’t know how I’d do it ?

  • @Wagnerfilho How are you sending the data there in PHP? You are using the function json_encode()?

  • @Godfreytheking, yes. My problem is not sending the data to the server. Until then, I send the serialized data to the server. But I would like to create an object before sending, and instead of using data: $('#form').serialize() I wanted to send as data: { 'objeto': JSON.stringify(objeto) },; but for this I would have to create the object before. So I could handle the fields individually.

  • @Wagnerson, according to your code you are not sending data to PHP, but searching for it - GET method.

  • @Wagnerfilho According to your feedback, I will adjust my answer.

  • @Wagnerson I just saw, you’re referring to function salvar_assessoria()?

  • Exactly, I’m referring to the post method.

  • @Wagnerfilho Check my answer.

  • @Godfreytheking, my friend, I don’t think you understand. I request this way, what I’m not getting is to create an object to manipulate the fields individually. Example: objeto.elemento.valor_do_elemento or objeto.cpf = $('#txt_cpf').val();

  • All I want is to handle each field manually before making the ajax request. Because for the CPF field, for example, I’m using a Mask plugin, and all the dots and dashboard is going to the server, so I have to do a str_replace on the server. So I wanted to do this, before sending by ajax. Got it ?

  • @Wagnerson You’ve come to see my answer? JSON.parse(JSON.stringify($('#form').serializeArray())) does exactly what you want, creates an Object with the fields of your form for you to handle individually.

Show 14 more comments

2 answers

1

To turn your entire form into JSON Object format, do:

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

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

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 doubts, access this jsfiddle and open your browser console (Chrome is F12) and see the solution working.

0

If Voce wants to remove the Mask before sending the results via ajax, the github.com/igorescobar/jQuery-Mask-Plugin library has available the function unmask(). Then its function remove_mascara(); must be something like that

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 never used this library so, more than I see it I believe that this should work.

  • 1

    Your answer doesn’t match the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.