Laravel 5.3 with Ajax

1

I would appreciate your help in solving an Ajax problem with Laravel 5.3

I'm experiencing problems with Internal Server Error 500, and looking for information about it may be routing problem or csrf_token (), but I've already made the changes and it just does not resolve. Where can I be wrong? The system does not even arrive in the Controller method.

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

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

The setting for the zip code 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 loads through 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 the Controller I mounted this way to retrieve the information and return the zip code collecting 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);
    }
    
asked by anonymous 10.02.2017 / 02:02

2 answers

0

Virgil, I got it sorted out. You gave the way and I went looking for the problem.

What was happening was an interference / section location within the Blade master with the blade that was the form / javascript. I also started to use your Ajax example, then I'll test what I had done to see if it could also cause a problem.

but the answer is that I was able to solve it like this:

In the master blade, I put the meta tag and the Ajax configuration handler in the intermediate Blade, inside the Body area I created a section with the name @section ('script') and the form I used before @stop

Then I put the code to better exemplify how it was.

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

    
13.02.2017 / 13:46
1

I have decided to develop a minimal example , so I can compare it with your code, I had some coding errors.

Minimum 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><metaname="_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');

Note: To get all inquiries you can use this code as an experiment by copying and pasting the settings in your project and testing. / p>     

10.02.2017 / 20:55