Doubt Laravel + Ajax

Asked

Viewed 24 times

0

I have the following table below, with a listing, there is a TD, which the user can choose between yes and no, html tag option, would like to know how to make the change from yes to no or vice-versa, via ajax, so that it is not necessary to keep making client server request, and update via ajax. Below follows image of how the table is.

inserir a descrição da imagem aqui

I am currently trying to do the ajax this way, but it is giving error:

jQuery(document).ready(function(){
jQuery('#viewpergunta').change(function(e){
   e.preventDefault();
   $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
  });
   jQuery.ajax({
      url: '../perguntascadastro/1',
      method: 'post',
      data: {
         viewpergunta: jQuery('#viewpergunta').serialize(),
      },
      success: function(result){
         console.log(result);
      }});
   });
});

Below follows my route which gives to update in the bank, the same route I use for registration, serves to atulizar.

Route::any('/perguntascadastro/{id}', 'PerguntasController@addPerg')->where('id', '[0-9]+');

My controller

public function addPerg(PerguntasRequest $request, $id){

    if($id == 0){
        Perguntas::create($request->all());
    }else{
        Perguntas::find($request->id)->update(Request::except($id));
    }

    return redirect()->action('PerguntasController@index', $id = 0);
}

My Html only the table part

<td>
                    <select class="form-control" id="viewpergunta" name="viewpergunta">
                        <option value="{{ $lista->viewpergunta == 1 ? 1 : 0 }}">{{ $lista->viewpergunta == 1 ? "Sim" : "Não" }}</option>
                        <option value="{{ $lista->viewpergunta == 1 ? 0 : 1 }}">{{ $lista->viewpergunta == 1 ? "Não" : "Sim" }}</option>
                    </select>
                </td>
  • what error is giving?

  • Failed to load Resource: the server responded with a status of 419 (Unknown status)

  • How is set in the header your goal?

  • Like using the Laravel, I’m only using "@csrf" <meta charset="utf-8">&#xA; <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />&#xA; <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />&#xA; <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no' name='viewport' />

  • Try adding one more like this <meta name="csrf-token" content="{{ csrf_token() }}">

  • now gave error 422 (Unprocessable Entity)

  • solved? have you tried debugging your function to see if the ajax reaches it? it is worth noting that to analyze the result you will have to look at the network tab in the browser!

Show 3 more comments
No answers

Browser other questions tagged

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