Sending form via Ajax in Laravel + Request

Asked

Viewed 944 times

0

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

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

Js who makes the upload.

$("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
});

Pessoarequest.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));
}

Personal controller.php

public function salvar(PessoaRequest $request){

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

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

}

When submitting the form, if you do not fill in the input, it lands on a white screen with the Pessoarequest json return, stating which fields should be filled in. If successful when sending, gives the successful json return.

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

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

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

  • I only managed to solve this problem still using Validator() instead of the request for requests with ajax

1 answer

1

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

The File Validation.js

$(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 input ids and that’s it. I hope I’ve helped.

Browser other questions tagged

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