The Laravel Way : Ajax request

The Laravel Way : Ajax request

It was 1st day of my job at a local firm as a Laravel developer. And I didn’t knew a thing about laravel at that time.

I started my learning from Laracasts.

On probably 10th day, my manager told me to create a blog application for a client. In which he requires to have all the posts on the left side and when the user clicks on the a particular post’s heading, on the right side, should open it’s full content. He told me to make an ajax request to get the post details when user clicks on the post’s heading.

I was new to laravel, and was first time hearing the word an AJAX request. It get’s a little tough when you come for the first time in the industry at least the first 6 months or so. But if you are a fast paced learner as I am, it is pretty easy to make an Ajax request and I will tell you all about it.

So Let’s get into this.

First thing to know is what do I mean by AJAX.

AJAX : Asynchronous JavaScript and  Xml. It is a way to communicate with the server from javascript and get responses from server and display it’s result in real time.

It is what is used by many big websites like facebook for like, comment. How does that like immediately appear or that comment you wrote on your friend’s post immediately showing at last your comment without reloading and saving the comment in the database. It’s all done via Ajax request and shown in real time. That’s what makes it more awesome.

There might be many ways to initiate an Ajax call, I feel the jquery way is the best one. So, I am going to show you that one.

Note: You need jquery to get this working. and of course laravel setup (as it’s the laravel way).

Okay, so I need a laravel project set up and I will show you how you can submit a form by sending it via an Ajax call.

I am assuming you have a little knowledge of Laravel structure and have played with it a little.

 

  1. Create a blade file with a normal form with (FirstName, LastName and Gender in it) and a submit button, which can look like this :
    Ajax Demo Form
  2. Make the route for the form submit. Which should look something like this :
    //For Ajax Demo
    Route::get('/ajaxDemo', 'FrontendController@ajaxDemo')->name('ajaxDemo');
    Route::post('/ajaxDemo', 'FrontendController@ajaxDemo')->name('postAjaxDemo');
    • First one is the route for opening the form. (using ‘GET’ method)
    • Second route is for submitting the form. (using ‘POST’ method)
  3. Now comes the part of ajax Request in jquery
    $("#ajaxDemoForm").on('submit', function(e){
    	
        e.preventDefault();
        //serializing form data		
        var formData = $(this).serialize();
        var ajaxUrl = $(this).attr('action'); //Getting the url
    
    $.ajax({
    
    	url: ajaxUrl,
    	data : formData,
    	method : "POST",
    	success : function(data) {
    		$(".message").addClass('alert alert-success');
    		$(".message").html(data.result);
    	},
    	error : function(data) {
    		$(".message").addClass('alert alert-danger');
    		$(".message").html(data.result);
    	}
    });
    • I have used the form submit event to trigger the ajax Request.
    • Before making the ajax Request, I have taken the form data by serializing it.
    • And took the url from the form’s action attribute.

It is as simple as that.

Now I will tell you what those parameters to ajax call are :

  1. url : It the url where you want to send the data and get the response.
  2. data : The data you want to send to the server.
  3. method : Through which method you want to send the data (GET, POST, PUT, PATCH, DELETE).
  4. success : It is a function which is called when the ajax call went successfully and you have your result.
  5. error : It is a function which is called when the ajax call returns with an error.

As, you through routes can assign a route with a controller’s method, as I have did it in my routes. You can play with the data as much as you can in the method and return the success or failure and even return views in return.

There are many more parameters to the ajax call. I have explained only the few, to get you started.

A quick google can help.

My controller’s function (for reference) :

/**
* Ajax Demo 
*
* @return json response or view
* @author 
**/
public function ajaxDemo (Request $request)
{
	if($request->method() == "POST")
	{
		/**
    		 * Do all the processing on the data and return success or failure 
    		 */    		
    		return response()->json(array("result" => "success"));
    	}
    	else
    	{
    		return view('ajaxDemo');
	}
}

Thanks. Hope I could help.

See you in the next tutorial.

www.000webhost.com