Laravel 5.3 with Ajax

Asked

Viewed 1,382 times

1

Dear friends, I ask your help to help me solve an Ajax problem with Laravel 5.3

I am facing problems with Internal Server Error 500, and looking for information about it, it may be a problem of routes or csrf_token(), but I have already made the changes and simply does not solve. Where can I be wrong? The system doesn’t even reach the method in the Controller.

Below I put the project information to try to explain the logic and where it might be happening.

This code is to automatically load the zip code into the fields.

The definition of the CEP field of the page containing the Ajax code is:

{!! Form::open(['route'=>'alunos.store','method'=>'POST']) !!}
<div class="col-md-2">
    <div class="form-group{{ $errors->has('CEP') ? ' has-error' : '' }}">
        <input type="text" name="cep" id="cep" class="form-control" placeholder="CEP somente números" value="{{old('CEP')}}" required="required"/>
   </div>
   @if ($errors->has('CEP'))
       <span class="help-block">
           <strong class="text-danger">{{ $errors->first('CEP') }}</strong>
       </span>
   @endif
</div>
<div class="panel panel-footer">
     <button type="submit" class="btn btn-primary"><i class="fa fa-check"> <b style="font-family: Arial">Salvar</b></i></button>
     <a href="{{ route('alunos.index')}}"><button type="button" class="btn btn-warning" ><i class="fa fa-times"></i><b style="font-family: Arial"> Cancelar</b></button></a>
</div>
{!! Form::close() !!}

I have a Plane.blade.php that is loaded on all pages. Its content is:

<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
    <meta charset="utf-8"/>
    <title>Nova Escola</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1" name="viewport"/>
    <meta content="" name="description"/>
    <meta content="" name="author"/>
    <meta name="_token" content="{!! csrf_token() !!}"/>
    <link rel="stylesheet" href="{{ asset("assets/stylesheets/styles.css") }}" />
    <script src="{{asset('js/jquery-3.1.1.min.js')}}"></script>
</head>
<body>
    @yield('body')
    <script src="{{ asset("assets/scripts/frontend.js") }}" type="text/javascript"></script>
</body>
</html>
@yield('scripts')
<script type="text/javascript">
    $.ajaxSetup({
        headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
    });
</script>

The page that makes the Ajax request has the following code:

@section('scripts')
<script type='text/javascript'>
    $(document).ready( function() {
        /* Executa a requisição quando o campo CEP perder o foco */
        $('#cep').blur(function(){
            /* Configura a requisição AJAX */
            $.ajax({
                url :'/cep', /* URL que será chamada */
                type : 'POST', /* Tipo da requisição */
                data: 'cep=' + $('#cep').val(), /* dado que será enviado via POST */
                dataType: 'json', /* Tipo de transmissão */
                success: function(data){
                    if(data.sucesso == 1){
                        $('#rua').val(data.rua);
                        $('#bairro').val(data.bairro);
                        $('#cidade').val(data.cidade);
                        $('#estado').val(data.estado);
                        $('#numero').focus();
                    }
                    else{
                        alert('retornou <> 1');
                    }
                }
            });
            return false;
            })
        });
</script>
@stop

In web.php (Route) I defined this way:

Route::post('/cep', 'alunosController@cep');

In Controller I rode this way to retrieve the information and return the ZIP Code collection data.

public function cep(Request $request){
        $cep = $request; // $_POST['cep'];
        $reg = simplexml_load_file("http://cep.republicavirtual.com.br/web_cep.php?formato=xml&cep=".$cep);
        $dados['sucesso'] = (string) $reg->resultado;
        $dados['rua']     = (string) $reg->tipo_logradouro.' '.$reg->logradouro;
        $dados['bairro']  = (string) $reg->bairro;
        $dados['cidade']  = (string) $reg->cidade;
        $dados['estado']  = (string) $reg->uf;

        return Response::json($cep);
    }
  • withdraw return false; within the blur ... and testing

  • Virgilio, I did what you suggested, but it didn’t help. continues giving [Error] Failed to load Resource: the server responded with a status of 500 (Internal Server Error) (cep, line 0) - http://localhost:8000/cep

  • what is the error that it gives in javascript? has how to place the image, press F12 and check the return error please?

  • Chrome-Extension://ahbkhnpmoamidjgbneafjipbmdfpefad/injectees/jquery/3.1.1/jquery.min.js Failed to load Resource: net:ERR_FILE_NOT_FOUND frontend.js:30 Uncaught Typeerror: Context cannot read Property 'getget' of null(... ) Launcher.js:3 ******** request_settings 2Launcher.js:20 Launching Focusmanager.parse_for_input on DOM Mutation Event - 2Launcher.js:20 Launching Focusmanager.parse_for_input on DOM Mutation Event http://localhost:8000/cep Failed to load Resource: the server responded with a status of 500 (Internal Server Error)

  • 132Launcher.js:20 Launching Focusmanager.parse_for_input on DOM Mutation Even - Virgil is what appears on the console

  • I could not paste, I am using Mac OS Sierra with Safari, however the error in Safari and Chrome and Opera

  • only with these errors gets complicated for sure, but, it seems route that is wrong!

  • Do you have any idea how to assemble? I’ve reviewed this route a number of times and it seems to be ok.

  • When on the console I put console.log(CSRF_TOKEN ) it returns with the following information: VM286:1 Uncaught Referenceerror: CSRF_TOKEN is not defined at <Anonymous>:1:13

  • maybe there are things beyond the assembled form are also wrong, without seeing it gets complicated... it’s a one-off mistake

  • Virgil, I called the chat but I don’t think I’m qualified to answer

  • truth should not be allowed yet

Show 8 more comments

2 answers

0

I decided to develop a minimum example, to make the comparison with your code, had some coding errors (missing code).

Minimal example:

Html - postcep.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js">
    </script>
    <meta name="_token" content="{!! csrf_token() !!}"/>
</head>
<body>
    <form action="">
        <div>
            Cep: <input type="text" id="cep" name="cep" />
        </div>
        <div>
            Rua: <input type="text" id="rua" name="rua" />
        </div>
        <div>
            Bairro: <input type="text" id="bairro" name="bairro" />
        </div>
        <div>
            Cidade: <input type="text" id="cidade" name="cidade" />
        </div>
        <div>
            Estado: <input type="text" id="estado" name="estado" />
        </div>
    </form>
    <script>
        $.ajaxSetup({
            headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
        });
        $(document).ready(function(){
           $("#cep").on('blur', function()
           {
               value = $(this).val();
               if (value.length < 8)
               {
                   alert("Digite o cep");
                   return;
               }
               $.post("/post/cep", {cep:value}, function(data)
               {
                   $("#rua").val('');
                   $("#bairro").val('');
                   $("#cidade").val('');
                   $("#estado").val('');
                    if (data.sucesso != "0")
                    {
                        $("#rua").val(data.rua);
                        $("#bairro").val(data.bairro);
                        $("#cidade").val(data.cidade);
                        $("#estado").val(data.estado);
                    }
               }, 'json');
           });
        });
    </script>
</body>
</html>

Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostCepController extends Controller
{
    public function index()
    {
        return view('postcep');
    }

    public function cep(Request $request)
    {
        $cep = $request->input('cep');
        $url = "http://cep.republicavirtual.com.br/web_cep.php?formato=xml&cep=".$cep;
        $reg = simplexml_load_file($url);
        $dados['sucesso'] = (string) $reg->resultado;
        $dados['rua']     = (string) $reg->tipo_logradouro.' '.$reg->logradouro;
        $dados['bairro']  = (string) $reg->bairro;
        $dados['cidade']  = (string) $reg->cidade;
        $dados['estado']  = (string) $reg->uf;
        return $dados;
    }
}

Routes

Route::get('/post', 'PostCepController@index');
Route::post('/post/cep', 'PostCepController@cep');

Observing: To remove all doubts you can use this code as an experiment, copying and pasting the settings in your project and testing.

0


Virgil, I managed to solve it. You gave way and I went looking for the problem.

What was happening was an interference / location of the Section inside the master blade with the Blade that was the form / javascript. I also went on to use your example of Ajax, then I will test what I had done to check if it could also cause some problem.

but the answer is that I was able to solve it as follows:

In Blade master, I put the meta tag and Ajax configuration Handler, in the intermediate Blade, inside the Body area I created a Section with the name @Section('script') and in the form I used before @stop I opened Section('script') and I put Ajax and then it started working.

Then I put the code to better illustrate how it turned out.

But I would like to thank you very much for your contribution. Thanks!

  • OK @Ricardo ....

Browser other questions tagged

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