Virajsinh

jQuery Reusable Module.js

Oct 29th, 2025 (edited)
808
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 4.26 KB | Source Code | 0 0
  1. // actions.js
  2.  
  3. /**
  4.  * Reusable confirmation + AJAX action handler.
  5.  * Can be used for delete, restore, or any other bulk action.
  6.  */
  7. export function actionWithAjax({ajax_call, title, confirmText, successText, btnClass, onSuccess, onError, onComplete})
  8. {
  9.     if (!ajax_call?.formData || !ajax_call?.endpoint) {
  10.         console.error('❌ actionWithAjax: Missing ajax_call.formData or ajax_call.endpoint');
  11.         return;
  12.     }
  13.  
  14.     // SweetAlert confirmation dialog
  15.     Swal.fire({
  16.         html: `Are you sure you want to ${title} ?`,
  17.         icon: 'warning',
  18.         showCancelButton: true,
  19.         buttonsStyling: false,
  20.         confirmButtonText: confirmText,
  21.         cancelButtonText: 'No, cancel',
  22.         allowOutsideClick: false,
  23.         customClass: {
  24.             confirmButton: `btn fw-bold ${btnClass}`,
  25.             cancelButton: 'btn fw-bold btn-active-light-primary'
  26.         }
  27.     }).then(result => {
  28.         if (!result.value) return;
  29.  
  30.         const csrfMeta = $('meta[name="csrf-token"]');
  31.         const csrfToken = csrfMeta.length ? csrfMeta.attr('content') : null;
  32.  
  33.        // Perform AJAX
  34.         $.ajax({
  35.             url: ajax_call.endpoint,
  36.             type: 'POST',
  37.             data: ajax_call.formData,
  38.             cache: false,
  39.             contentType: false,
  40.             processData: false,
  41.             dataType: 'json',
  42.             headers: csrfToken ? { 'X-CSRF-TOKEN': csrfToken } : {},
  43.  
  44.             beforeSend: () =>
  45.             {
  46.                 Swal.fire({
  47.                     title: `${capitalize(title)}...`,
  48.                     html: `Please wait while we ${title} the record(s).`,
  49.                     allowOutsideClick: false,
  50.                     allowEscapeKey: false,
  51.                     didOpen: () => Swal.showLoading()
  52.                 });
  53.             },
  54.  
  55.             success: (res) =>
  56.             {
  57.                 Swal.close();
  58.  
  59.                 if (res.status)
  60.                 {
  61.                     Swal.fire({
  62.                         html: successText,
  63.                         icon: 'success',
  64.                         buttonsStyling: false,
  65.                         showConfirmButton: false,
  66.                         timer: 2000,
  67.                         timerProgressBar: true
  68.                     });
  69.  
  70.                     toastr.success(res.message);
  71.                     if (typeof onSuccess === 'function') onSuccess(res);
  72.                 } else {
  73.                     toastr.error(res.message || 'Action failed.');
  74.                     if (typeof onError === 'function') onError(res);
  75.                 }
  76.             },
  77.  
  78.             error: (xhr) =>
  79.             {
  80.                 Swal.close();
  81.  
  82.                 if (xhr.responseJSON?.errors) {
  83.                     Object.values(xhr.responseJSON.errors).forEach(msg => toastr.error(msg));
  84.                 } else if (xhr.responseJSON?.message) {
  85.                     toastr.error(xhr.responseJSON.message);
  86.                 } else {
  87.                     toastr.error('An unexpected error occurred.');
  88.                 }
  89.  
  90.                 if (typeof onError === 'function') onError(xhr);
  91.             },
  92.  
  93.             complete: (xhr, status) => {
  94.                 if (typeof onComplete === 'function') onComplete(xhr, status);
  95.             },
  96.  
  97.             statusCode:
  98.             {
  99.                 404: function(xhr) {
  100.                     // Get Response ==> xhr.responseJSON
  101.                     // alert("page not found");
  102.                 },
  103.                 403: function(xhr) {
  104.                     // alert("Forbidden");
  105.                 },
  106.                 419: function(xhr) {
  107.                     // alert("CSRF Token Not Valid / Session Invalid");
  108.                 },
  109.                 422: function(xhr) {
  110.                     // alert("Unprocessable Entity");
  111.                 },
  112.                 500: function(xhr) {
  113.                     // alert("Internal Server Error");
  114.                 }
  115.             }
  116.         });
  117.     });
  118. }
  119.  
  120. /**
  121.  * Utility to refresh DataTable without full reload
  122.  * @param {string} tableId - The DataTable ID in window.LaravelDataTables
  123.  */
  124. export function refreshDataTable(tableId)
  125. {
  126.     if (window.LaravelDataTables?.[tableId]) {
  127.         window.LaravelDataTables[tableId].draw(false);
  128.     } else {
  129.         // console.warn(`DataTable '${tableId}' not found`);
  130.     }
  131. }
  132.  
  133. function capitalize(str) {
  134.     return str.charAt(0).toUpperCase() + str.slice(1);
  135. }
  136.  
  137. /*
  138.  
  139. How To Use ?
  140.  
  141. import {actionWithAjax, refreshDataTable} from '../module/actions.js';
  142.  
  143. // Collect form data or any data to send
  144. const formData = new FormData();
  145. formData.append('_method', 'POST');
  146.  
  147. actionWithAjax({
  148.     ajax_call: {
  149.         formData,
  150.         endpoint: backend_url + '/pro-incentive/action-check/' // πŸ‘ˆ Replace this
  151.     },
  152.     title: 'delete',
  153.     confirmText: 'Yes, delete!',
  154.     successText: 'Record deleted successfully!',
  155.     btnClass: 'btn-success',
  156.  
  157.     // Optional Callbacks
  158.     onSuccess: (res) => {
  159.         console.log('βœ… Deleted successfully:', res);
  160.         toastr.success(res.message);
  161.     },
  162.  
  163.     onError: (err) => {
  164.         console.warn('⚠️ Error during deletion:', err);
  165.     },
  166.  
  167.     onComplete: (xhr, status) => {
  168.         console.log('🟑 Request completed with status:', status);
  169.         // e.g. Re-enable button, hide loaders, etc.
  170.         $('#ha_btn').prop('disabled', false);
  171.     }
  172. });
  173.  
  174. refreshDataTable(dataTableID);
  175.  
  176. */
Advertisement
Add Comment
Please, Sign In to add comment