Common AJAX call in JavaScript using jQuery.
Hello guys,
In this session, we will create a function that helps us call AJAX in a common way on every page of a website.
Firstly, Create a file in assists folder named common_ajax.js and
Secondly, write the following function in the file:.
function AjaxCalling(callback, Url, Data) {
$.ajax({
url: Url,
type: 'POST',
headers: authorization(),
data: Data,
async: true,
processData: false, // Set to false when sending FormData
contentType: false, // Set to false when sending FormData
success: callback,
});
}
Then write a function which returns required headers in the same file, as follows:
function authorization() {
let headers = {
'Access-Control-Allow-Origin': '*',
};
return headers;
}
After these steps, we just have to import the JS file into our HTML file.
<script src="/public/common_assets/imports/cdn.lordicon.com_lordicon.js"></script>
<script>
data = {
'search_string': "anydata"
}
AjaxCall(function(data, header, error) {
var response = JSON.parse(data);
//process you wanted to do ....
});
</script>
Thank you.
Tagged:
