Ajax parameters are coming as Undefined

Asked

Viewed 109 times

2

I would like to say that I searched the forum and found some similar questions, but no answer solved my problem. Follow my own doubt:

Doubt:

I am trying to delete a notification by ajax, but the error is occurring. The variables id_project and n_notification are as Undefined. How to solve this problem?

Error:

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui Projectocontroller.php: (method removeNotification)

//Este método remove a Notificação
        public function removeNotificacao(Request $request)
        {
            $notificacao = HistoricoNotificacao::find($request->id)->where('n_notificacao', '=',  $request->nnotificacao);

            $nnotificacao = $request->nnotificacao;
            if (!$notificacao)
            return response()
                        ->json(['error' => 'not_found'], 404);

            $response =  $notificacao->deletarNotificacao($notificacao);  

            if($response['success'])
            {
            return response()
                    ->json(['success' => $response['message']], 200);  

            }else
            {
                // Caso não delete, informa um erro inesperado
            return redirect()
            ->json(['error' => 'Erro ao remover a notificação nnotificacao ' + $nnotificacao ], 500);        
                        //->json(['error' => $response['message']], 500);        
            } 
        }



Project.php: (method deletarNotificacao)

   //Este método remove os dados da Notificação
    public function deletarNotificacao(HistoricoNotificacao $notificacao) : Array
    {
        $notificacao = $this->delete();
        if($notificacao){
            return[
                'success' => true,
                'message' => 'Sucesso ao excluir a notificação'
            ];   
        }
        else{
            return[
                'success' => false,
                'message' => 'Falha ao excluir a notificação'
            ]; 
        }
    }


Ajax page (draft notification.js)

Is responsible for passing the variables id_project and n_notification for the method removeNotification.

$(document).on('click', '#btnExcluirNotificacao', function () {
    $('#idProjNotificacao').val($(this).data('id'));
    $('#numNotificacao').text($(this).data('nnotificacao'));
});

//Ajax para remover uma notificação, e atualizar a página após a ação
$('.removeNotificacao').click(function () {

    var data_id = $('#idProjNotificacao').val();
    var n_notificacao = $('#numNotificacao').val();

    $.ajaxSetup({
        headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    }); 

    $.ajax({
        url:  "/projetos/removeNotificacao",
        type: "POST",
        data: {id: data_id, nnotificacao: n_notificacao}
    }).done(function (response) {
        console.log(response);

        if (response.success) {  

        /*  $('.message').text("Sucesso ao excluir");
         $('.message').show();  */
        alert ('Sucesso ao excluir a notificação');

        setTimeout(function(){
                location.reload();
            }, 4000); 
        }
        else {
        //    alert(response.error);
        alert("Erro ao excluir a notificação");

        }   
    }).fail(function (response) {
      //  $('.message').text("Erro ao excluir");
      alert("Falha ao excluir a notificação , nnotificacao = " + response.nnotificacao + "  Id = "+response.id);
    });

    return false;
});




//Evento que preencherá o modal View de histórico de Notificações
$(document).on('click', '.btnViewNotificacao',function () {
    $('#modalViewIdNotificacao').val(($(this).data('id')));
    $('#modalViewNnotificacao').val(($(this).data('nnotificacao')));
    $('#modalViewDtRecebimento').val(($(this).data('dtrecebimento')));
    $('#modalViewDtResposta').val(($(this).data('dtresposta')));
    $('#modalViewConteudo').val(($(this).data('conteudo')));
    $('#modalViewOrigem').val(($(this).data('origem')));
    $('#modalViewDtConclusao').val(($(this).data('dtconclusao')));
});

//Evento que preencherá o modal Edit de histórico de Notificações
  $(document).on('click', '.btnEditNotificacao',function () {
    $('#modalEditIdNotificacao').val(($(this).data('id')));
    $('#modalEditNnotificacao').val(($(this).data('nnotificacao')));
    $('#modalEditDtRecebimento').val(($(this).data('dtrecebimento')));
    $('#modalEditDtResposta').val(($(this).data('dtresposta')));
    $('#modalEditConteudo').val(($(this).data('conteudo')));
    $('#modalEditOrigem').val(($(this).data('origem')));
    $('#modalEditDtConclusao').val(($(this).data('dtconclusao')));
});


Modal Delete Notification

<!-- Modal de Excluir Notificação-->
                <div class="modal fade modal-danger" id="modalExcluirNotificacao" aria-hidden="true" aria-labelledby="examplePositionCenter"
                 role="dialog" tabindex="-1">
                <div class="modal-dialog modal-center">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">×</span>
                            </button>
                            <h4 class="modal-title">Exclusão da Notificação</h4>
                        </div>
                        <div class="modal-body">
                           <input type="hidden" id="idProjNotificacao"> 
                            <p>Deseja excluir a notificação de número "<span id="numNotificacao"></span>"?</p>
                        </div>
                        <div class="modal-footer">
                            <a type="button" class="btn btn-danger removeNotificacao" data-dismiss="modal">Excluir</a>
                            <button type="button" class="btn btn-default btn-pure" data-dismiss="modal">Fechar</button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Fim do Modal de Excluir Notificação -->


Javascript libraries of the page edit.blade.php

@section('adminlte_js')

 <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>  

<!-- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> -->

 <!--Inicio das interações em AJAX-->
     <script src="{{asset('js/pages-js/projeto/projeto-validaData.js')}}"></script>
     <script src="{{asset('js/pages-js/projeto/projeto-cadNovasLocalidades.js')}}"></script>
     <script src="{{asset('js/pages-js/projeto/projeto-autorizaProjeto.js')}}"></script>
     <script src="{{asset('js/pages-js/projeto/projeto-autorizaDocs.js')}}"></script>
     <script src="{{asset('js/pages-js/projeto/projeto-localidades.js')}}"></script>
     <script src="{{asset('js/pages-js/projeto/projeto-create.js')}}"></script>
     <script src="{{asset('js/pages-js/projeto/projeto-notificacao.js')}}"></script>
     <script src="{{asset('js/pages-js/projeto/projeto-errata.js')}}"></script> 
    <!--Fim das interações em AJAX-->


     <script  src="{{asset('js/app-js.js')}}"></script>

    <!-- <script  src="{{asset('js/datatables/jquery-1.12.4.js')}}"></script>  -->
    <!--Inicio da biblioteca DataTables-->
    <!--  <script src="{{asset('js/datatables/dataTables.buttons.min.js')}}"></script>
     <script src="{{asset('js/datatables/buttons.flash.min.js')}}"></script>
     <script src="{{asset('js/datatables/jszip.min.js')}}"></script>
     <script src="{{asset('js/datatables/pdfmake.min.js')}}"></script>
     <script src="{{asset('js/datatables/vfs_fonts.js')}}"></script>
     <script src="{{asset('js/datatables/buttons.html5.min.js')}}"></script>
     <script src="{{asset('js/datatables/buttons.print.min.js')}}"></script>
     <script src="{{asset('js/datatables/buttons.colVis.min.js')}}"></script>  -->
     <!--Fim da biblioteca DataTables -->  



    @yield('js')

2 answers

1

Try to use:

var n_notificacao = $('#numNotificacao').html();
  • Thank you, I’ll test.

  • 1

    I made the modification, but the error persists.

  • If the document is xhtml, it should be used $('#numNotificacao'). text();

  • 1

    First of all, thank you for the return. I did the tests in the ajax file and the same is receiving the values of the variables idProjNotificacao' and numNotificacao. The problem occurs in the Projectocontroller.php controller when deleting the data. When debugging the network tab the following error appeared when I used the $Response = $notification->delete() command: message: A non-numeric value encountered Exception: Errorexception file: c: xampp htdocs Union app Http Controllers Admin Projectntroller.php

1

I didn’t see in the code how you’re setting the attribute data button #btnExcluirNotificacao.

But you can try it like this and see if it works:

//Ajax para remover uma notificação, e atualizar a página após a ação
$('.removeNotificacao').click(function () {

    var data_id = $('#btnExcluirNotificacao').data('id');
    var n_notificacao = $('#btnExcluirNotificacao').data('nnotificacao');

If it doesn’t work, try:

var data_id = $('#btnExcluirNotificacao').attr('data-id');
var n_notificacao = $('#btnExcluirNotificacao').attr('data-nnotificacao');
  • Leo Klaj, thank you for your reply. I did the tests as recommended in addition I tested the following codes: var data_id = $('#idProjNotificacao'). val(); var n_notification = $('#numNotification'). val(); and the following form var data_id = $('#idProjNotification'). html(); var n_notification = $('#numNotification'). html(); But the error persists. The error is occurring when the id and nnotification variables are passed to the controller (Projectocontroller.php).

  • Then it seems that the btnExcluirNotification button does not have the date attributes set. Try giving console.log to see if the attributes are there anyway.

  • First of all, thank you for the return. I did the tests in the ajax file and the same is receiving the values of the variables idProjNotificacao' and numNotificacao. The problem occurs in the Projectocontroller.php controller when deleting the data. When debugging the network tab the following error appeared when I used the $Response = $notification->delete() command: message: A non-numeric value encountered Exception: Errorexception file: c: xampp htdocs Union app Http Controllers Admin Projectntroller.php

Browser other questions tagged

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