How do I post a form in laravel 5 using ajax?

24,606

Without looking at any of your code, I can tell you my way of performing this task. There may be other ways, but this is generally how I have approached it since I started using Laravel.

I want to be able to show errors using jquery after validation but I have no idea how to access the object sent to my controller; so I dont even know what to 'return' in the controller.

Let's start by breaking this down into 3 simpler questions.

1. How do I access the object sent to my controller?

Well, in your AJAX you can choose to send a GET or POST request. Convention states that you should use POST for updating the model and GET for retrieving from the model. If you are using REST, then you have other methods to make use of (PUT, PATCH, DELETE, etc). You can learn more about these on your own, but for the sake of this answer I will keep things simple with just GET and POST.

In your example you use POST, so let's go with that. You already called the JQuery serialize method, so that's all you need to do. In your Laravel controller, simply take the argument Request $request for the method, and the Laravel method $request->input() will give you a key/value array of all the parameters sent in the request. You can then handle them accordingly.

2. What should I return in the controller?

Typically you return JSON data for an AJAX request. It is easy to parse, and both JavaScript and JQuery have nice objects for parsing JSON for you.

In your Laravel controller, you can add the following line at the end of your method to return some JSON:

return response()->json($data);

In this example, $data is an array containing the JSON you want to return. In PHP, we can represent a JSON string as an array of key/value pairs, like so:

$data = [
    'success': true,
    'message': 'Your AJAX processed correctly'
];

Typically, if this were a plain old PHP script, we would have to call PHP's json_encode function, but Laravel handles this for us, so all we need to do is pass the array. For debugging purposes, you may want to make use of the JSON_PRETTY_PRINT constant, which will output the JSON nicely on the screen if you access the URL directly:

return response()->json($data, 200, [], JSON_PRETTY_PRINT);

3. How do I access the object sent from my controller?

Well, now that your response is a simple JSON string, you can use any of the built in JavaScript methods for parsing the JSON. I typically use JSON.parse(json), where json is your JSON string returned by the controller. See here for more details.

4. So, how do I get this data?

Well, it looks like you probably already have this figured out, but just to be sure I will clarify. You need to register the route to your controller. Then, you can simply call that URI using the JQuery AJAX object and then the injected variable data will be whatever was returned from the controller, in this case a JSON string.

Share:
24,606
jackjoesmith
Author by

jackjoesmith

Updated on July 09, 2022

Comments

  • jackjoesmith
    jackjoesmith almost 2 years

    I'm having a ton of trouble learning how to make an ajax post in laravel. I want to be able to show errors using jquery after validation but I have no idea how to access the object sent to my controller; so I dont even know what to 'return' in the controller. Can someone please walk me through this?

    This is a part of my view

    <meta name="_token" content="{{ csrf_token() }}" />            
    <div class='row'>
            {!! Form::open(['url'=>'register','id'=>'sign-up','class'=>'col-md-6 col-md-push-4 form-horizontal'])!!}
    
                <div class='form-group'>
                    {!! Form::label('first_name', 'First Name:',['class'=>'col-xs-12 col-md-3']) !!}
                    <div class= 'col-xs-12 col-md-6'>
                        {!! Form::text('first_name', null, ['class' => 'form-control'])!!}
                    </div>
                </div>
                <div class='form-group'>
                    {!! Form::label('last_name', 'Last Name:',['class'=>'col-xs-12 col-md-3']) !!}
                    <div class= 'col-xs-12 col-md-6'>
                        {!! Form::text('last_name', null, ['class' => 'form-control'])!!}
                    </div>
                </div>
                <div class='form-group'>
                    {!! Form::label('email', 'Email Address:',['class'=>'col-xs-12 col-md-3']) !!}
                    <div class= 'col-xs-12 col-md-6 '>
                        {!! Form::text('email', null, ['class' => 'form-control'])!!}
        <div class='form-group'>
                {!! Form::label('password', 'Password:',['class'=>'col-xs-12 col-md-3']) !!}
                    <div class= 'col-xs-12 col-md-6'>
                        {!! Form::password('password', null, ['class' => 'form-control'])!!}
                    </div>
                </div>
    
                        <div class='form-group'>
                {!! Form::label('password_confirmation', 'Confirm Password:',['class'=>'col-xs-12 col-md-3']) !!}
                    <div class= 'col-xs-12 col-md-6'>
                        {!! Form::password('password_confirmation', null, ['class' => 'form-control'])!!}
                    </div>
                </div>
                        </div>  <div class='btn btn-small'>
                    {!! Form::submit('Join Us!',['class'=>'btn btn-success btn-sm form-control'])!!}
                </div>
    
            {!! Form::close() !!}
            </div>
    

    .js file:

    $(function(){
    
    $('#sign-up').on('submit',function(e){
        $.ajaxSetup({
            header:$('meta[name="_token"]').attr('content')
        })
        e.preventDefault(e);
    
            $.ajax({
    
            type:"POST",
            url:'/register',
            data:$(this).serialize(),
            dataType: 'json',
            success: function(data){
                console.log(data);
            },
            error: function(data){
    
            }
        })
        });
    });
    

    controller:

    <?php 
    
    namespace App\Http\Controllers;
    
    use App\Http\Requests\CreateRegisterRequest;
    use App\Http\Controllers\Controller;
    use App\User;
    use Illuminate\HttpResponse;
    use Input;
    class UserController extends Controller
    {
    
        public function create(CreateRegisterRequest $request)
        {
    
        }
    
        public function show()
        {
            return view('user.profile');
        }
    
    }
    

    Form Request:

    <?php
    
    namespace App\Http\Requests;
    
    use App\Http\Requests\Request;
    
    class CreateRegisterRequest extends Request
    {
        public function authorize()
        {
            return true;
        }
    public function rules()
        {
            return [
                'first_name' =>'required',
                'last_name'=>'required',
                'url'=>'url',
                'description',
                'email'=>'unique:users,email|email',
                'password'=>'min:6|confirmed',
                'password_confirmation'=>'min:6'
    
    
            ];
        }
    }
    
  • jackjoesmith
    jackjoesmith over 8 years
    Thank you! I have a somewhat better understanding of this now :)
  • samrap
    samrap over 8 years
    Glad I could help. I know it isn't a "here's the code plug it in and go" type answer, but I think this way is better because now you know the general steps and it's up to you to figure out the specifics :) Good luck!
  • jackjoesmith
    jackjoesmith over 8 years
    Yeah I was able to create an object with ajax with this mini lesson haha. Now I'm trying to show errors...
  • samrap
    samrap over 8 years
    Why not make your error reporting a JSON response? That way you can return an error code, a message, and a description, or any other number of useful information.
  • jackjoesmith
    jackjoesmith over 8 years
    the $request object contains the error messages so I should be able to return it as a response and parse it with javascript right?
  • samrap
    samrap over 8 years
    Correct, but if your request contains the error messages than why pass it to the controller in the first place? If you know the errors before sending them, then you should handle the errors in the JS without sending a request to prevent an unneeded request
  • jackjoesmith
    jackjoesmith over 8 years
    Oh right. true. But I would still need to do that for things like unique email right?
  • samrap
    samrap over 8 years