How to use ajax with jquery in laravel

 

Sometimes in your web application if you want to update some parts of your web page(without reloading the webpage) then you can use AJAX with your server side scripting language.AJAX is the composition of Asynchronous JavaScript and XML. It is a client side script, which updates your content asynchronously in the background of your web page without reloading the whole page.So here I am going to show you how to use ajax with laravel.

In laravel how you will send data to your controller or route using ajax? Before you implement ajax in laravel, remember one thing you need to take care of csrf token. CSRF(Cross-site request forgery) is a method of website attack where unwanted actions can be performed on behalf of the authenticated user.For each active user session laravel automatically generates a CSRF “token”. This token verify whether the request is actually made by the authenticated user. When you create a form using laravel’s {{Form}} tag then laravel will automatically add a hidden input tag for you.It will look something like below:

<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">

If you have a form which is using HTML form tag then you need to manually add in your blade template file which will generate same as above code.If your form does not have _token hidden field then AJAX might not work properly and it throw an error with “500 internal server error”.On every HTTP post request, laravel checks the post token value with automatically generated token which is generated by itself.

In this script we will create a country dropdown and retrieve all it’s state list using ajax.

Database
Create country and cities table with below sql code.

CREATE TABLE IF NOT EXISTS `country` (
`country_id` int(10) unsigned NOT NULL,
  `country_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `country` ADD PRIMARY KEY (`country_id`);
ALTER TABLE `country` MODIFY `country_id` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1;


CREATE TABLE IF NOT EXISTS `cities` (
`city_id` int(10) unsigned NOT NULL,
  `country_id` int(10) unsigned NOT NULL,
  `city_name` varchar(70) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


ALTER TABLE `cities` ADD PRIMARY KEY (`city_id`), ADD KEY `cities_country_id_foreign` (`country_id`);
ALTER TABLE `cities` MODIFY `city_id` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1;
ALTER TABLE `cities` ADD CONSTRAINT `cities_country_id_foreign` FOREIGN KEY (`country_id`) REFERENCES `country` (`country_id`);

Sample Data
Insert some records into the country and cities table.

INSERT INTO `country` (`country_id`, `country_name`) VALUES
(1, 'Afghanistan'),
(2, 'Armenia'),
(3, 'India'),
(4, 'Bahrain'),
(5, 'Bangladesh'),
(6, 'Bhutan');


INSERT INTO `cities` (`city_id`, `country_id`, `city_name`) VALUES
(1, 1, 'Kabul'),
(2, 1, 'Kandahar'),
(3, 1, 'Farah'),
(4, 1, 'Jalalabad'),
(5, 2, 'Yerevan'),
(6, 2, 'Vagharshapat'),
(7, 3, 'Odisha'),
(8, 3, 'New Delhi'),
(9, 3, 'Maharastra'),
(10, 3, 'Uttar Pradesh'),
(11, 4, 'Manama'),
(12, 4, 'Riffa'),
(13, 5, 'Jamalpur'),
(14, 5, 'Kishoreganj'),
(15, 6, 'Chhukha'),
(16, 6, 'Damphu');

Routes
Add below code in your “app/Http/routes.php” file

Route::get('country','CountryController@getCountryList');
Route::post('get_cities_list','CountryController@getCitiesList'); 

Controller:
Create the CountryController.php controller file under “app/Http/Controllers/CountryController.php” and paste below code in that controller.

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

class CountryController extends Controller {

	/*Return all country list*/
	public function getCountryList(){
		$countries=DB::table('country')->select('country_id','country_name')->get();
		return view('country', ['countries' => $countries]);
	}
	
	
	/*Return all cities as per country id*/
	public function getCitiesList(Request $request){		
		if ($request->ajax()){ //If it is a ajax request				
		  $CountryID=$request->input('CountryId');						
			if($CountryID>0){
				$CityList=DB::table('cities')
					->select('city_id','city_name')
					->where('country_id', '=',(int)$CountryID)
					->orderBy("city_name")	
					->get();
				$TotalCity=count($CityList);
				$CityArr=array(''=>'Select City Name');
				if($TotalCity>0){
					  foreach($CityList as $city_data){
						$CityArr[$city_data->city_id]=$city_data->city_name;
					  }
				}					
				echo Form::select('city_id',$CityArr);
			}			
			
		}else{
			echo 0;	
		}
	}
}
?>

You can send _token input value to your controller in different ways which are discussed below:

Adding _token on each ajax request
Now create country blade template file under “redources/views/country.blade.php”. Either you can use the javascript code in your template file or put it in a separate .js file and include that file in your template. Here {{ csrf_token() }} is used which will generate the token.In the javascript code laravel’s url helper method is used which genarates full URL to the given path. I always suggest you, mention the full URL path of your action else the script will throw “page not found” error.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Cities List</title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
function getCityList(country_id){	
	$('#state_id').html('Loading...');
	$.ajax({
      url: "{{ URL::to('get_cities_list') }}", //Full path of your action
      type: "post",	  
      data: {'CountryId':country_id,'_token': '{{ csrf_token() }}'},
      success: function(data){
        $('#show_city_list').html(data);
      },
	  error: function (xhr, status) {              
            alert('There is some error.Try after some time.'); 
          }
    });
}
</script>
</head>
<body>
<div class="content">
  {!! Form::open() !!}
    <?php
	$CountryArr=array(''=>'Select Country');
	if(count($countries)>0){
		foreach($countries as $country){
			$CountryArr[$country->country_id]=$country->country_name;
		}
	}
	?>    
  	Country : {!!Form::select('country', $CountryArr,'',
['Onchange'=>'getCityList(this.value)','id'=>'country'])!!}
    <br /><br />
    City :<span id="show_city_list">
    	 {!!Form::select('city_id',[''=>'Select City'])!!}
    </span>
  {!! Form::close() !!}
  </div>
</body>
</html>

Using _token globally
In this method first you need to add a meta tag in your template file like below.

<meta name="csrf-token" content="{{ csrf_token() }}" />

After adding above code in your header part, laravel will genarate a csrf token. Next add below code either in a separate javascript file and then include it in your template file or placed it in your template’s footer part. so when you send ajax request to your controller from your template file laravel will send the token automatically in thee ader part so you dont need to pass _token variable in every request.

<script type="application/javascript">
$.ajaxSetup({
	headers: {
		'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
	}
});
</script>

COMMENTS ( 13 )

Thanks for another excellent article. The place else may just anyone get that kind of info
in such a perfect means of writing? I have a presentation next week, and I am at the look for such info.

Reply

DoriCBline says:

This really is a topic that’s in close proximity to my heart…
Many thanks! Where are the information though?

Reply

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories