Here you can use javascript Promise
For example, if you need a display list of students on the listing page, and on the details page only use one student detail.
So, generally, we are using each page different ajax call. But better way is you can use Promise function.
Following example to guide how to use Promise function
Simple ajax call:
$.ajax({
url: url,
type: "GET",
dataType: "json",
contentType: "application/json",
success(data) {
/*play with response data*/
},
error(xhr, status, message) {
/*manage error handing*/
}
});
Use Promise function:
function students(url){
var myPromise = new Promise(function (resolve, reject) {
$.ajax({
url: url,
type: "GET",
dataType: "json",
contentType: "application/json",
success(data) {
resolve(data);
},
error(xhr, status, message) {
reject(xhr, status, message);
}
});
});
return myPromise;
}
Function use:
1) On student list page:
students('students.php').then(
function (response) {
/*play with response data*/
},
function (xhr, status, message) {
/*manage error handing*/
}
);
2) On student details page:
students('students.php/{student-id}').then(
function (response) {
/*play with response data*/
},
function (xhr, status, message) {
/*manage error handing*/
}
);
For example, if you need a display list of students on the listing page, and on the details page only use one student detail.
So, generally, we are using each page different ajax call. But better way is you can use Promise function.
Following example to guide how to use Promise function
Simple ajax call:
$.ajax({
url: url,
type: "GET",
dataType: "json",
contentType: "application/json",
success(data) {
/*play with response data*/
},
error(xhr, status, message) {
/*manage error handing*/
}
});
Use Promise function:
function students(url){
var myPromise = new Promise(function (resolve, reject) {
$.ajax({
url: url,
type: "GET",
dataType: "json",
contentType: "application/json",
success(data) {
resolve(data);
},
error(xhr, status, message) {
reject(xhr, status, message);
}
});
});
return myPromise;
}
Function use:
1) On student list page:
students('students.php').then(
function (response) {
/*play with response data*/
},
function (xhr, status, message) {
/*manage error handing*/
}
);
2) On student details page:
students('students.php/{student-id}').then(
function (response) {
/*play with response data*/
},
function (xhr, status, message) {
/*manage error handing*/
}
);