Problem
How to Return AJAX Response from Asynchronous JavaScript Call with Code Examples and then do some operations on response result.
Final output
Make a general Asynchronous Ajax JavaScript function with callback which return the result to callback and then we show the result in callback function using console function, for conformation.
What is Ajax?
Ajax stands for Asynchronous JavaScript And XML
Ajax is not a programming language.
Ajax uses JavaScript and HTML DOM (to display or use the data).
Ajax is a concept which allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page by using Ajax.
So, Let’s start to make a general Asynchronous Ajax function which takes Ajax parameters and return the response result. Its good to always follow the best practices 🙂
Solution
1. Firstly, let’s make a base JavaScript file which will be shared through out the web application.
Then define general Ajax variables and function with callback in there like below:
var ajaxCallParams = {}; var ajaxDataParams = {}; // General function for all ajax calls function ajaxCall(callParams, dataParams, callback) { $.ajax({ type: callParams.Type, url: callParams.Url, quietMillis: 100, dataType: callParams.DataType, data: dataParams, cache: true, success: function (response) { callback(response); }, error: function (response) { callback(response); } }); }
2. Set Ajax call and Ajax data parameters
ajaxCallParams.Type = "POST"; // POST type function ajaxCallParams.Url = "/Payment/Create"; // Pass Complete end point Url e-g Payment Controller, Create Action ajaxCallParams.DataType = "JSON"; // Return data type e-g Html, Json etc // Set Data parameters ajaxDataParams.Id = 1; ajaxDataParams.Name = "Shujat Munawar";
3. Now, Just pass these parameters to general Ajax function and on Callback we will display the response result.
// Passing call and data parameters to general Ajax function ajaxCall(ajaxCallParams, ajaxDataParams, function (result) { console.log(result); });
Congratulations now you can get Async Ajax response result and do operation on the result.
Share your love with us 😉
Click on a star to rate it!
Average rating 5 / 5. Vote count: 3
No votes so far! Be the first to rate this post.