Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'


        ];
    }
}
like image 578
jackjoesmith Avatar asked Sep 08 '15 21:09

jackjoesmith


People also ask

How do I submit a form after ajax success?

ajax() function is used for ajax call using jQuery. We can submit a form by ajax using submit button and by mentioning the values of the following parameters. type: It is used to specify the type of request. url: It is used to specify the URL to send the request to.

How send data from ajax to laravel?

Import jquery library in your view file to use ajax functions of jquery which will be used to send and receive data using ajax from the server. On the server side you can use the response() function to send response to client and to send response in JSON format you can chain the response function with json() function.


1 Answers

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.

like image 172
samrap Avatar answered Sep 29 '22 02:09

samrap