Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimum Working Example for ajax POST in Laravel 5.3

Tags:

ajax

post

laravel

Can someone please explain the ajax post method in Laravel 5.3 with a full-working minimum example? I know there are some resources in the web, but I miss a concise, straight-forward minimum example.

like image 425
jonathan.scholbach Avatar asked Feb 01 '17 14:02

jonathan.scholbach


People also ask

Can Ajax use POST?

post() makes Ajax requests using the HTTP POST method. The basic syntax of these methods can be given with: $. get(URL, data, success); —Or— $.

How does Ajax POST work?

data : A plain object or string that is sent to the server with the request. success : A callback function that is executed if the request succeeds.it takes as an argument the returned data. It is also passed the text status of the response.

How do I know if Ajax is working in Laravel?

In Laravel, we can use $request->ajax() method to check request is ajax or not.

What is difference between Ajax and POST?

$. post is a shorthand way of using $. ajax for POST requests, so there isn't a great deal of difference between using the two - they are both made possible using the same underlying code.


1 Answers

I presume you have a basic understanding of the model-controler-view paradigm, a basic understanding of Laravel and a basic understanding of JavaScript and JQuery (which I will use for reasons of simplicity).

We will create an edit field and a button which posts to the server. (This works for all versions from Laravel 5.0 to 5.6)

1. The Routes

At first you need to add routes to your routes/web.php. Create one route for the view, just as you know from ordinary views:

Route::get('ajax', function(){ return view('ajax'); }); 

The second route you need to create is the route that handles the ajax post request. Take notice that it is using the post method:

Route::post('/postajax','AjaxController@post'); 

2. The Controller Function

In the (second) route you created just now, the Controller function post in the AjaxController is called. So create the Controller

php artisan make:controller AjaxController 

and in the app/Http/Controllers/AjaxController.php add the function post containing the following lines:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request;   class AjaxController extends Controller {     public function post(Request $request){       $response = array(           'status' => 'success',           'msg' => $request->message,       );       return response()->json($response);     } } 

The function is ready to receive data via a Http request and returns a json-formatted response (which consists of the status 'success' and the message the function got from the request).

3. The View

In the first step we defined the route pointing to the view ajax, so now create the view ajax.blade.php.

<!DOCTYPE html> <html> <head>      <!-- load jQuery -->     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>      <!-- provide the csrf token -->     <meta name="csrf-token" content="{{ csrf_token() }}" />      <script>         $(document).ready(function(){             var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');             $(".postbutton").click(function(){                 $.ajax({                     /* the route pointing to the post function */                     url: '/postajax',                     type: 'POST',                     /* send the csrf-token and the input to the controller */                     data: {_token: CSRF_TOKEN, message:$(".getinfo").val()},                     dataType: 'JSON',                     /* remind that 'data' is the response of the AjaxController */                     success: function (data) {                          $(".writeinfo").append(data.msg);                      }                 });              });        });         </script>  </head>  <body>     <input class="getinfo"></input>     <button class="postbutton">Post via ajax!</button>     <div class="writeinfo"></div>    </body>  </html> 

If you wonder what's the matter with this csrf-token, read https://laravel.com/docs/5.3/csrf

like image 110
jonathan.scholbach Avatar answered Sep 25 '22 17:09

jonathan.scholbach