ajax requests in Laravel

7

This is the example code of a controller and the normal handling (not AJAX) of a Request or request.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

use Illuminate\Routing\Controller;

class UserController extends Controller
{
    /**
     * Store a new user.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $name = $request->input('name');
        //
    }
}

What should I do to make it work for AJAX requests in the store() function?

If I create another function storeAjax() , I can include it in routes.php (with a new assigned route) and it works, but it is not a good practice, because I have 2 routes and it must be the same for both requests.

    
asked by Shaz 01.12.2015 в 19:58
source

4 answers

5

Maybe this can help you:

if($request->ajax()){ }//procesa la peticion ajax 
else{return $view;} //retornas por ejemplo,una vista

Regarding Routes.php , there is no need to modify, what you do in your JS is a request of type GET :

$.ajax(type: 'GET', ...)

And you process the petition, I hope it helps you.

    
answered by 01.12.2015 / 21:07
source
4

Use the following example to create a more powerful driver function.

  • We check if the request comes from an AJAX request or not, and we return a response in JSON or a Redirect depending on the case
  • Using Try / Catch to capture errors
  • Using Log for error log

-

public function store()
{
    $data = [
        'name'  =>  Input::get('name'),
    ];

    try
    {
        $result = $this->repository->create($data);
    }
    catch (Illuminate\Database\QueryException $e)
    {
        Log::error("[email protected]: register your error", array('created_by' => Auth::user()->id, 'message' => $e->getMessage());

        if (!Request::ajax())
        {       
            return Redirect::back()
                ->with('type_message', "danger")
                ->with('message', trans('web.error'))
        }
        else
        {
            return "{\"result\":\"ko\",\"error\":\"$e->getMessage()\"}";
        }
    }

    if ($result)
    {
        if (!Request::ajax())
        {
            Log::info("[email protected]: Created OK", array('created_by' => Auth::user()->id, 'result' => $result->toArray()));

            return Redirect::back()
                ->with('type_message', "success")
                ->with('message', trans("web.created_ok"));
        }
        else
        {
            return "{\"result\":\"ok\",\"id\":\"$result->id\",\"name\":\"$result->name \"}";
        }
    }
    else
    {
        return "{\"result\":\"ko\",\"error\":\"Hubo un error guardando\"}";
    }
}

Example of AJAX request:

$.ajax({
        url: "{{ route('my_route')}}",
        data: "name="+name+"&_token={{ csrf_token()}}",
        dataType: "json",
        method: "POST",
        success: function(result)
        {
            if (result['result'] == 'ok')
            {

            }
            else
            {

            }
        },
        fail: function(){
        },
        beforeSend: function(){
        }
    });
});

Create a route that points to the Store method of your controller, which will serve you both for requests from a form and for AJAX requests:

Route::post('/my_route', array('as' => 'my_route', 'uses' => '[email protected]'));
    
answered by 02.12.2015 в 11:33
3

It is not necessary to implement another method.

If it does not work for you, it may be because Laravel 5 includes a validation of the CSRF token, for security reasons, in all POST, PUT and DELETE requests. You must include this token in the request.

You can see different methods to include this token in the official documentation: link

    
answered by 01.12.2015 в 21:06
0

You can try this

public function store(Request $request)
{
    if($request->ajax())
    {
        $name = $request->input('name');
        Response->json($name);
    }
}
    
answered by 27.08.2016 в 00:35