sandip kakade
sandip kakade

Reputation: 1356

How to restrict ajax call on every page in Laravel 5.2?

I am using Laravel 5.2 there are some of ajax call which are calls on every page. Now I want to ajax call required pages only.

My Routes

Route::auth();    
Route::get('/', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('users/client', 'ClientController@showClients');
Route::get('users/client/add', 'ClientController@addClient');
Route::get('dash/manage_graph', 'BoardController@showPowerManage');
// My ajax call 
Route::get('dash/manage_chart/chart/{request}', 'DashboardController@powerChart');
Route::get('dash/manage/chart/{request}', 'DashboardController@powerChart');

My data.js file

$(document).ready(function() {
$.getJSON('dash/manage_chart/chart/' + request, function (data) {
        $('#dg_hours').html(data);
    });
$.getJSON('dash/manage/chart' + request, function (data) {
        $('#dg_sec').html(data);
    });
});

Above is my routes. In my routes I am not using any Middleware for this. Now I am facing problem is my ajax call load on every page. Because of loading ajax my single page load time is more than 50 seconds. Now I don't know how to handle this. Please suggest me.

Upvotes: 0

Views: 127

Answers (1)

Steve Chamaillard
Steve Chamaillard

Reputation: 2339

Doing the :

$.getJSON('dash/manage_chart/chart/' + request, function (data) {
   $('#dg_hours').html(data);
});

will automatically do the AJAX call whenever the HTML page is loaded. That's why your AJAX calls are always made.

Instead, you should do this :

var getPowerChart = function(request, data) {
    $.getJSON('dash/manage_chart/chart/' + request, function (data) {
        $('#dg_hours').html(data);
    });
}

And you should call getPowerChart(request, data) only when you need to do the corresponding AJAX call.

Additional note : since you can't create a new JS file, I guess the most simple way to do this is to add a data-page attribute to the <body> tag for example, and do this in Javascript :

var getPowerChart = function(request, data) {
    $.getJSON('dash/manage_chart/chart/' + request, function (data) {
        $('#dg_hours').html(data);
    });
}

if ($('body').data('page') == 'your-page') {
    var request = '...',
        data = '...';

    getPowerChart(request, data);
}

Upvotes: 3

Related Questions