Sending form via Ajax in Laravel + Request

0

I have a registration form for people. I need to send it with Ajax to not reload the page.

So far, I have the following ready that I followed for a tutorial.

Sending Js.

$("form#pessoasCadastrar" ).submit(function( event ) {

    event.preventDefault();

    data = $("form#pessoasCadastrar" ).serialize(),
    url = '/pessoas/salvar',

    var posting = $.post( url, { formData: data } );
    posting.done(function( data ) {
    if(data.fail) {
      $.each(data.errors, function( index, value ) {
        var errorDiv = '#'+index+'_error';
        $(errorDiv).addClass('required');
        $(errorDiv).empty().append(value);
      });
      $('#successMessage').empty();          
    } 
    if(data.success) {
        $('.register').fadeOut(); //hiding Reg form
        var successContent = '<div class="message"><h3>Registration Completed Successfully</h3><h4>Please Login With the Following Details</h4><div class="userDetails"><p><span>Email:</span>'+data.email+'</p><p><span>Password:********</span></p></div></div>';
      $('#successMessage').html(successContent);
    } //success
  }); //done
});

PersonaRequest.php

public function rules(){ ... }
public function messages(){ .... } 

public function response(array $errors)
{
    if ($this->ajax() || $this->wantsJson())
    {
        return response()->json($errors, 422);
    }
       $dados = array('fail' => true, 'errors' => $errors);
       return response()->json(array('fail' => true,'errors' => $errors));
}

PersonController.php

public function salvar(PessoaRequest $request){

 $p = new Pessoa();
 [....]

 return Response()->json(array('success' => true,$request->all()));

}

When submitting the form, if it does not fill in the input, it falls on a white screen with the json return of the PersonRequest, stating which fields are to be filled. If it succeeds to send, it gives the json return of success.

My problem is when it gives the error in the request, I would like to get the json return and treat in my view to show the errors, but whenever I send it, it falls on that white screen with the errors

{"fail":true,"errors":{"nome":["O campo nome \u00e9 obrigat\u00f3rio!"]}}

How do I get these info in my view without reloading it?

    
asked by anonymous 30.04.2016 / 16:56

1 answer

1
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.6/jquery.validate.js"></script><scriptsrc="\jquery\funcoes\Validacao.js" charset="utf-8"></script>

The Validation.js File

$(document).ready(function(){
    $('#idDoForm').validate({
        rules:{
            nome:{
                required: true,
                minlength: 3
            },
            dataNasc: {
                required: true,
            },
            telCel: {
                required: true
            },
            email: {
                required: true,
                email: true
            },
        },
        messages:{
            nome:{
                required: "O campo nome é obrigatorio.",
                minlength: "O campo nome deve conter no mínimo 3 caracteres."
            },
            dataNasc:{
                required: "O campo Data de Nascimento é obrigatorio."
            },
            telCel:{
                required: "O campo Telefone Celular é obrigatorio."
            },
            email: {
                required: "O campo email é obrigatorio.",
                email: "O campo email deve conter um email válido."
            },
        }

    });
});

My HTML

{!! Form::label('DataNasc','Data de Nascimento:') !!}
              <input type="date" id="dataNasc" name="dataNasc" value="" class="form-control" onblur="CalcIdade();"/>
            </div>

            <!--Tel Cel Cliente Inputs-->
            <div class="form-group">
              {!! Form::label('TelCel','Telefone Celular:') !!}
              {!! Form::text('telCel', null, array('class'=>'form-control', 'id'=>"telCel"))!!}
            </div>

            <!--Tel Res Cliente Inputs-->
            <div class="form-group">
              {!! Form::label('TelRes','Telefone Residencial:') !!}
              {!! Form::text('telRes', null, array('class'=>'form-control', 'id'=>"telRes"))!!}
            </div>

            <!--Tel Res Cliente Inputs-->
            <div class="form-group">
              {!! Form::label('Email','E-mail:') !!}
              {!! Form::email('email', null, array('class'=>'form-control', 'id'=>"email"))!!}
            </div>

            <!--Sexo Cliente Inputs-->
            <div class="radio">
              <label>
                {!! Form::radio('sexo', 'Masculino')!!}
                <p>Masculino</p>
              </label>
            </div>
            <div class="radio">
              <label>
                {!! Form::radio('sexo', 'Feminino')!!}
                <p>Feminino</p>
              </label>
            </div>

            <input type="hidden" name="idade" id="idade" value="">
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            {!! Form::submit('Salvar Cliente', ['class'=>'btn btn-primary']) !!}
          </div>
        {!! Form::close() !!}

In case the library will only need its form and the ids of the inputs and that's it. I hope I have helped.

    
04.03.2017 / 04:17