Crud Ajax Laravel 5.*

Asked

Viewed 231 times

0

I have a little problem. I’m doing a crud with Ajax + Laravel. "Everything" is working, more than when I update a data, it also registers. Well see how I’m doing. I have a Bhutan that I have an id called dashboard_register category. This id is for me to recover with jQuery and trigger the click event.

 <button id="dashboard_cadastrar_categoria" type="button" class="btn btn-primary butao_categoria">Cadastrar</button>

More when I update I change this id with jQuery to update_ .

 $('.butao_categoria').attr('id', 'update_');

When I update it updates and register right after. What could be?

Ajax method to access the store method in my controller Category.php

$(document).ready(function () {
$('#success').hide();
$(document).ready(function () {
    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
    $("#dashboard_cadastrar_categoria").click(function () {
        $.ajax({
            url: '/administracao/categoria/store',
            type: 'POST',
            data: {_token: CSRF_TOKEN, nome: $("#nome_categoria").val()},
            dataType: 'JSON',
            success: function (data) {

                // console.log(data);

                $("#nome_categoria").val('');
                $('#success').show();
                $('#success').text('Categoria Cadastrada com Sucesso');
                setTimeout(function () {
                    $('#success').fadeOut('slow');
                }, 5000);
            }
        });
    });
});
});

This method works more I suspect that after I update it enters in this method more I do not know why.

Medoto Ajax who accesses the Category.php controller to get the information to edit.

$(document).ready(function () {
$('.categoria_editar').click(function () {
    var id = $(this).attr('value');
    $.ajax({
        url: '/administracao/categoria/edit/' + id,
        type: 'GET',
        dataType: 'JSON',
    }).done(function (e) {
        $('#cadastro_categoria').modal('show');
        $('.butao_categoria').attr('id', 'update_');
        $('.butao_categoria').text('Update');
        $('#dashboard_categoria_id').val(e.id);
        $('#nome_categoria').val(e.nome_categoria);
    });
});

});

And lastly the ajax method that accesses the controller to update

$(document).ready(function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');


$(".butao_categoria").click(function () {
    var nome_catg = $('#nome_categoria').val();
    var id_categ = $('#dashboard_categoria_id').val();

    $.ajax({
        url: '/administracao/categoria/update',
        type: 'POST',
        data: {_token: CSRF_TOKEN, nome_categoria: nome_catg, id_categ: id_categ},
        dataType: 'JSON',

        success: function (e) {
            console.log(e);
        }
    });
});
});

Controller : Store method:

public function store(Request $request){
    if ($request->isMethod('POST')){
        $categoria = new Categoria;
        $categoria->create([
            'nome_categoria'    => $request->get('nome_categoria'),

        ]);

        if($categoria){

            return response()->json(['success' => 'success' , 'categoria'   =>  Categoria::where('nome_categoria' , $request->get('nome_categoria'))->first()]);
        }

    }

    return response()->json(['response' => 'This is get method']);
}

Edit Method

 public function edit($id){
    $categoria = Categoria::findOrFail($id);
    return response()->json($categoria);
}

Update method

public function update(Request $request){
    $categoria = Categoria::findOrFail($request->get('id_categ'));

    $result = $categoria->update([
        'nome_categoria' => $request->get('nome_categoria'),
    ]);
    if($result){
        return response()->json('sucesso');
    }
}
  • Put the controller code too.

  • Ready to go. @Andre Gusmão

1 answer

0


You’ve made a tremendous mess of your code.. When you start your code, javascript is loaded and fires an event store pro button id "#dashboard_register category", when you will change the record you take the button by the class

$('.butao_categoria').attr('id', 'update_');

and edit the id, so that when you click do not go to the store event, until then the intention is correct, but the onClick event will no longer leave that button, when you change the id of nothing helps, every time you click on that button the snippet of code that’s in there will be executed. So summarizing when you click change it executes the first event that was written to the "#dashboard_register category"(store) and then runs by the "class". butao_category" the update event.

I give you 4 options to solve this problem:

1º (time consuming and effective) - You can elaborate another logic so that the flow runs more naturally, what you did sounds like gambiarra. Slow, because you’ll have to think .

2º (time consuming and efficient) - you can use datatables, have ready-made methods that help you get the data from the line, without having to make an additional ajax request. Time consuming, because you will have to study the api.

3º (fast and effective) - You can put 2 Buttons one to edit and one to save when saving hides the edit and when editing hides the save.

4º (fast and effective) - you can still do it this way:

var evento=1;
// 1 para store
// 2 para update

$('.butao_categoria').click(function () {
    if(evento == 1){
        //Dispara evento para salvar o objeto
    }else{
        //Dispara evento para alterar o objeto
    }
});

OBS. Always look for solutions where the code is clean and you can understand the flow naturally.

  • Perfect. I’ve used the Yajra datatables Api I think that’s the name. More tomorrow I will see this there and give you a feedback if everything went well and mark as solved your solution. I am already grateful for the help

Browser other questions tagged

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