Controller in Laravel is not receiving values sent by Ajax

Asked

Viewed 59 times

-1

I’m doing a Wizard where I add one product at a time by clicking on a button and Jquery adds the values in an array, and when I click on the next button I make an ajax request sending the values of that array but the data is not getting to my file in the Laravel, the return I receive is a "Undefined: null". I’ve tried everything and I don’t think what’s wrong.

At my head:

<meta name="csrf-token" content="{{ csrf_token() }}">

On my route:

Route::post('/get-fornecedores', 'MeuController@getFornecedores');

In HTML:

<table class="table table-striped">
                    <thead>
                        <tr>
                            <th scope="col">Id</th>
                            <th scope="col">Quantidade</th>
                            <th scope="col">Add</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($produtos as $produto)
                        <tr>
                            <td>{{ $produto->codigo }}</td>
                            <td>
                                <input type="hidden" class="idProduto" id="idProduto" value="{{ $produto->id_produto }}">
                                <input type="text" class="inputQuantidade" id="inputQuantidade">
                            </td>
                            <td>
                                <a href="#" class="btn disabled addproduto" name="addproduto">
                                </a>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
<button class="btn btn-success button_active" type="button" id="nextOrcamentoBtn">Next</button> 

Ajax in jquery

var produtosAdicionados = [];

$(function() {
  $( ".addproduto" ).click(function() {

    var produtos = {
      'produto': $(this).closest('tr').find('#idProduto').val(),
      'quantidade': $(this).closest('tr').find('#inputQuantidade').val(),
    };

    produtosAdicionados.push(produtos);

    console.log(produtosAdicionados);
  });
});



$( "#nextOrcamentoBtn" ).click(function() {

      var xmlDocument = produtosAdicionados;

      $.ajaxSetup({
        headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
      });
      $.ajax({
        method: "POST",
        url: "get-fornecedores",
        dataType: 'JSON',
        data: xmlDocument,
        success:function(data){

          console.log(data);
        },
        error:function(){
          alert("Request failed");
        },
      });
    });

In my Controller:

public function getFornecedores(Request $request) {

    $data = [
      'produto'  => request('produto'),
      'quantidade'  => request('quantidade'),
    ];      

    return response()->json($data);

}
  • If you try to return a fixed value by the controller, do you still receive null? If possible you can post the return of the full request json?

  • When I set a fixed value it returns normal. Only returns: Undefined: null even.

  • Post the result of return response()->json($request);

  • returns this: {product: null, quantity: null}

  • Let’s discuss in the chat

  • I can’t :/ "You must have 20 reputation on The Stack Exchange Network to chat here."

  • Do the following then, check if there is data in xmlDocument before submitting the ajax, go the reverse way until you find where the value is not being passed forward

  • It is from that point that I do not know what happens with the data, I gave a console.log in xmlDocument and it shows the normal values. In the controller the data does not arrive in $request, in the middle of these two points I do not know how to verify where the data is lost. Is it the way I’m putting them in the ajax date? the xmlDocument variable there is getting a JSON.

  • Yes, the problem is the content I am passing on - or itself - xmlDocument variable. I switched to fixed values on the date and returned correctly. So, in this case, how could I receive in jquery the values that are two equal fields for several rows of Table and store them in an array? Or if the form I’m doing is correct, how to pass the variable with this data by the date?

  • Try to pass the following and return $request...data: {&#xA; "_token": "{{ csrf_token() }}",&#xA; "valores": xmlDocument&#xA; } and adds in the question the result of the xmlDocument log console and the return of the above

  • Did not work. Gives error 419 (Unknown status).

  • If possible, upload the project to git to clone, take a closer look and test

Show 7 more comments

1 answer

0

The only way it worked was this: I am taking the values of only ONE table field and placing it in an array. And, in ajax I added one processData: false.

My question now is: How to send multiple equal fields with different values from a dynamically populated table with database values?

    var produtosAdicionados = [];

    $(function() {
      $( ".addproduto" ).click(function() {

        produtosAdicionados.push($(this).closest('tr').find('#idProduto').val());

      });
    });

    $.ajax({
    method: "POST",
    url: "get-fornecedores",
    processData: false,
    data: produtosAdicionados,
    success:function(data){
      console.log(data);
    },
    error:function(){
      alert("Request failed");
    },
  });

Browser other questions tagged

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