Writing Custom Callback for ajax
In this post, I will share how could you use callbacks to write efficient and maintainable ajax using callbacks. Promises can also be use but here i will discuss it with callbacks.
The definition of callback is
The definition of callback is
A reference to executable code, or a piece of executable code, that is passed as an argument to other code.Let's see an example code of custom callback,
function test(param1, param2, callback) { alert('Started function.\n\nIt has: ' + param1 + ', ' + param2); callback(); } test('foo', 'bar', function() { alert('Finished function.'); });Now I will share the code where you can leverage the callbacks for ajax and maintainable code.
function ajaxGetData(formId, callback) { $.ajax({ url: "/FormController/GetDataFromDb", type: "POST", dataType: "json", data: { id: formId }, success: function (data, status, xhr) { callback(data); } }); }; ajaxGetData(123, function(data) { console.log(data); });