Reputation: 2950
Here is my ajax
$.ajax(
{
url: url,
type: 'post',
dataType: 'json',
data: {'id':'1','name':'user'},
success: function(result) {}
});
So here is a basic setup of ajax but I want to add custom option showLoader
in ajax. So how can I achieve it?
$.ajax(
{
showLoader: true,
url: url,
type: 'post',
dataType: 'json',
data: {'id':'1','name':'user'},
success: function(result) {}
});
showLoader
will call when ajax requests start and end when ajax request stops.
in showLoader, there will be an image.
Any help will be greatly appreciated.
Upvotes: 0
Views: 404
Reputation: 458
The service class can be something like this
var Services = function () {
this.showLoader = true;
this.post = function( route, param, callback, showLoader = true, successMessage = '', failCallback = null, errorMessage = '' )
{
this.showLoader = showLoader;
$.post( route, param )
.success(function(data){
if( successMessage.trim().length ) {
//notify successMessage
}
// if to have callback function call than
if( null != callback ) {
callback(data);
}
})
.fail(function(error, status, type){
if( null != failCallback ) {
//notify error callback if this exists
}
});
};
}
Then you implement the methods to execute the ajaxStart and stop inside the class and verify if the this.showLoader attribute is true or false before run.
So in your code you can send ajax request like:
var service = new Service();
service.post('/user/add', form.serialize(), function(){}, false, 'User added successfully!');
I recommend that you create the instance new Service() in a javascript in the begin of you page loader, to you not need to make a new instance every time that you need to send an ajax request.
This is one way, make you own implementation now!
Upvotes: 1