Change button text in AJAX request

Asked

Viewed 634 times

0

Hello! I know it sounds silly to ask, but I don’t understand why it’s not working.

I want to send the form via ajax, while the request is made, the button is disabled and the name(text) of the button is changed to salvando..., once the request is completed, the button returns to its original state.

But it’s not working and I saw no reason not to work.

* HTML *

<div class="modal fade" id="modal_operador" tabindex="-1" role="dialog" aria-hidden="true" style="display: none;">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div style="background-color: #337ab7" class="modal-header bg-primary no-border">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title"><i class="fa fa-flash"></i> Operador</h4>
            </div>
            <form id="frm_operador">
                <div class="modal-body">
                    <div class="row">
                        <div class="form-group col-md-12">
                            <label for="nome">Nome</label>
                            <input type="text" id="txt_nome" class="nome form-control input-sm" name="nome" autocomplete="off" placeholder="Nome">
                        </div>
                        <div class="form-group col-md-12">
                            <label for="cpf">CPF</label>
                            <input type="text" id="txt_cpf" class="cpf form-control input-sm" name="cpf" autocomplete="off" placeholder="000.000.000-00">
                        </div>
                        <div class="form-group col-md-12">
                            <label for="login">Login</label>
                            <input type="text" id="txt_login" class="login form-control input-sm" name="login" autocomplete="off" placeholder="login.usuario">
                        </div>
                        <div class="form-group col-md-12">
                            <label for="senha">Senha</label>
                            <input type="password" id="txt_senha" class="senha form-control input-sm" name="senha" autocomplete="off" placeholder="******">
                        </div>
                        <div class="form-group col-md-12">
                            <label for="confirma_senha">Confirma Senha</label>
                            <input type="password" id="txt_confirma_senha" class="confirma_senha form-control input-sm" name="confirma_senha" autocomplete="off" placeholder="******">
                        </div>
                        <div class="form-group col-md-12">
                            <label for="situacao">Situação</label>
                            <select id="sel_situacao" name="situacao" class="situacao form-control input-sm">
                                <option value="1">Ativo</option>
                                <option value="2">Inativo</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer clearfix">
                    <button type="button" id="btn_salvar" class="btn btn-primary btn-flat pull-left"><i class="fa fa-save"></i> Salvar</button>
                    <button type="button" id="btn_cancelar" class="btn btn-default btn-flat" data-dismiss="modal"><i class="fa fa-times"></i> Cancelar</button>
                </div>
            </form>
        </div>
    </div>
</div>

$('#btn_salvar').click(function () {
   form.validate();        
   if (form.valid()) {
      salvar();
   }
});

//Função Salvar
function salvar() {
    form_objeto();
    if (salvar_operador()) {        
	atualizar_tabela();
	$('#modal_operador').modal('hide');
	toastr.success('Operador salvo com sucesso');
     }
}

//Método Salvar
function salvar_operador() {
  var url;
  if (_metodo_salvar == 'novo') {
    url = "operador/novo";
  } else {
    url = "operador/atualizar";
  }

  $('#btn_salvar').html('<i class="fa fa-spinner fa-spin"></i> Salvando');
  $('#btn_salvar').attr('disabled', true);

  var ret;
  $.ajax({
    type: 'POST',
    async: false,
    datatype: 'json',
    url: url,
    data: {
      'objeto': JSON.stringify(_obj_operador)
    },
    success: (function(data) {
      _obj_operador = data;
      $('#btn_salvar').html('<i class="fa fa-save"></i> Salvar');
      $('#btn_salvar').attr('disabled', false);
      limpar_modal();
      ret = true;
    }),
    error: (function(erro) {
      //TrataErroAjax(erro);
      alert(erro);
      ret = false;
    })
  });
  return ret;
}

  • Is there a mistake? And why do you use JSON.stringify? jQuery already does that.

  • No mistake and I use JSON.stringify to serialize the object for JSON.

  • The jQuery already makes JSON.stringify, just pass data: _obj_operador. Does the console have an error? you can see the ajax on the console if it is pending or resolves?

  • @Sergio, I’ll even have to change the JSON.stringify 'cause I’m gonna have to file through the form and then use the multipart/form-data and in ajax I’ll have to do something like this var formData = new FormData($('#form')[0]);. Taking advantage, know if it is possible to serialize so that I can upload files ?

  • Formdata accepts files as well.

  • When I withdraw the JSON.stringify, i have the server return. Message: json_decode() expects parameter 1 to be string, array given

  • Formdata accepts files, that’s right. But I can serialize a Formdata ?

  • What language do you have on the server?

  • PHP and I’m doing the following: $objeto = $_POST['objeto'];&#xA;$objeto_decode = json_decode($objeto); .

Show 4 more comments

2 answers

1

just as a complement, I use ajaxStart and ajaxStop to display a loading gif during my request, and when it ends, the gif will disappear:

$(document).ajaxStart(function () {
        $('#loadingImage').show();
    }).ajaxStop(function () {
        $('#loadingImage').hide();
    });

0

Change your function by placing a beforeSend and complete in Ajax.

//Método Salvar
function salvar_operador() {
var url;
if (_metodo_salvar == 'novo') {
  url = "operador/novo";
} else {
  url = "operador/atualizar";
}

var ret;
$.ajax({
type: 'POST',
async: false,
datatype: 'json',
url: url,
data:  _obj_operador,
beforeSend:function() { 
    $('#btn_salvar').html('<i class="fa fa-spinner fa-spin"></i> Salvando');
    $('#btn_salvar').attr('disabled', true);
 },
success: (function(data) {
  _obj_operador = data;
  limpar_modal();
  ret = true;
}),
complete:function() {
    $('#btn_salvar').html('<i class="fa fa-save"></i> Salvar');
    $('#btn_salvar').attr('disabled', false);
 },
error: (function(erro) {
  //TrataErroAjax(erro);
  alert(erro);
  ret = false;
})
});
return ret;
}
  • Lucas, I agree to use beforeSend and complete is good idea. But the AP code had some bug not to work as is?

  • @Lucas was supposed to work this way and the way I put it, but it doesn’t work either way or with beforeSend.

  • @Sergio had no bug, but I think it would be right to let Ajax handle it since you are using it

  • @Wagnerfilho Yes, it was supposed to work both ways.. Do you have an error in the console? And even change the text of the button at least?

  • It does not change anything! Although the request is fast, it is remarkable the text change and the disabled. There is no error, except the message that was saved successfully, something I am using in the save function. I will update the question to Voce see.

  • @Wagnerfilho publishes the part of html that has the button

  • @Lucassouza, done

Show 2 more comments

Browser other questions tagged

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