Crud Ajax Laravel 5. *

0

I have a problem. I'm doing a crud with Ajax + Laravel. "Everything" is working, except that when I update a data, it also registers. Well, look what I'm doing. I have a Bhutan that I have an id called dashboard_character_category. This id is for me to retrieve 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 go to update I change this id with jQuery to update_.

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

When I update it updates and registers soon after. What could it be?

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

$(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 the most I suspect that after I update it in this method I do not know why.

Medoto Ajax that 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 finally 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');
    }
}
    
asked by anonymous 03.11.2017 / 00:18

1 answer

0

You have made a tremendous confusion in your code .. When you start your code, javascript loads and triggers a store pro button event of id "#dashboard_core_category", when you change the registry you take the button by class

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

and edit the id, so that at the time you click do not go to the store event, until then the intention is correct, however the onClick event will no longer exit that button, when you change the id nothing is good, every time you click on that button the code snippet that is in there will be executed. So summarizing when you click on change it executes the first event that was written to the "#dashboard_category_category" (store) and then executes by the class ".butao_categoria" the update event.

I give you 4 options to solve this problem:

1st (time-consuming and effective) - You can work out another logic so that the flow flows more naturally, what you did sounds like gambiarra. Delayed, because you will have to think.

2nd (time-consuming and efficient) - You can use datatables, have ready-made methods that help you get row data, without having to do an additional ajax request. Delayed, because you will have to study api.

3º (fast and effective) - You can put 2 buttons one to edit and one to save when it is hiding the edit and when editing hides the save.

4th (fast and effective) - you can still do this:

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 stays clean and you can understand the flow in a natural way.

    
05.11.2017 / 05:22