ap-laravel-ajax-helper 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,24 +1,46 @@
1
1
  # Laravel AJAX Helper
2
2
 
3
- A lightweight utility to simplify Laravel AJAX form requests with validation error handling.
3
+ A lightweight JavaScript utility to simplify AJAX requests in Laravel applications. Handles CSRF protection, form data submission, and validation error display with minimal setup.
4
4
 
5
- ## 🚀 Usage
5
+ ---
6
6
 
7
- ### 📄 HTML Form Example
7
+ ## 🚀 Features
8
+
9
+ * ✅ One-liner AJAX integration with Laravel routes
10
+ * ✅ Automatically appends CSRF token from `<meta name="csrf-token">`
11
+ * ✅ Displays validation errors in `.error-[field_name]` elements
12
+ * ✅ Optional loading spinner with button text
13
+ * ✅ Built for modern browsers and Laravel developers
14
+
15
+ ---
16
+
17
+ ## 📦 Installation
18
+
19
+ ```bash
20
+ npm install laravel-ajax-helper
21
+ ```
22
+
23
+ ---
24
+
25
+ ## 📄 HTML Form Example
26
+
27
+ Add proper `name` attributes to inputs and matching `.error-[field_name]` spans for error display.
8
28
 
9
29
  ```html
10
30
  <form id="loginForm">
11
31
  <input type="email" name="email" />
12
- <span class="error-email text-red-500"></span>
32
+ <span class="error-email"></span>
13
33
 
14
34
  <input type="password" name="password" />
15
- <span class="error-password text-red-500"></span>
35
+ <span class="error-password"></span>
16
36
 
17
37
  <button id="loginBtn">Login</button>
18
38
  </form>
19
39
  ```
20
40
 
21
- ### 🧠 JavaScript Usage
41
+ ---
42
+
43
+ ## 🧠 JavaScript Usage
22
44
 
23
45
  ```js
24
46
  import laravelAjax from 'laravel-ajax-helper';
@@ -28,7 +50,8 @@ laravelAjax({
28
50
  method: 'POST',
29
51
  formId: 'loginForm',
30
52
  buttonId: 'loginBtn',
31
- loadingText: 'Logging in...'
53
+ loadingText: 'Logging in...',
54
+ csrf: true // Will read from <meta name="csrf-token" content="...">
32
55
  })
33
56
  .then(response => {
34
57
  console.log('Success:', response);
@@ -38,45 +61,62 @@ laravelAjax({
38
61
  });
39
62
  ```
40
63
 
41
- ## 🧰 Parameters
64
+ ---
65
+
66
+ ## ⚙️ Parameters
67
+
68
+ | Parameter | Type | Required | Description |
69
+ | ------------- | ------- | -------- | ----------------------------------------------------------------------------- |
70
+ | `url` | string | ✅ Yes | Laravel route URL. |
71
+ | `method` | string | ❌ No | HTTP method: 'POST', 'GET', 'PUT', 'DELETE'. Defaults to `'POST'`. |
72
+ | `formId` | string | ✅ Yes | HTML form ID (grabs data from inputs). |
73
+ | `buttonId` | string | ❌ No | Button ID for loading state UX. |
74
+ | `loadingText` | string | ❌ No | Text to show with spinner while loading. Defaults to `'Loading...'`. |
75
+ | `csrf` | boolean | ❌ No | If `true`, automatically uses `<meta name="csrf-token">`. Defaults to `true`. |
76
+
77
+ ---
78
+
79
+ ## ❗️ CSRF Handling
80
+
81
+ If `csrf: true` and no meta tag is found, the function will throw an error.
82
+
83
+ Make sure your HTML includes:
84
+
85
+ ```html
86
+ <meta name="csrf-token" content="{{ csrf_token() }}">
87
+ ```
42
88
 
43
- | Parameter | Type | Required | Description |
44
- | ------------- | ------ | -------- | -------------------------------------------------------------------- |
45
- | `url` | string | ✅ Yes | The Laravel route URL for the AJAX request. |
46
- | `method` | string | ❌ No | Request method: 'POST', 'GET', 'PUT', 'DELETE'. Default: 'POST'. |
47
- | `formId` | string | ✅ Yes | ID of the form element (do not pass form data manually). |
48
- | `buttonId` | string | ❌ No | ID of the button to show a loading spinner during request. |
49
- | `loadingText` | string | ❌ No | Text to show with spinner during the request. Default: 'Loading...'. |
89
+ ---
50
90
 
51
- ## Error Handling
91
+ ## ⚠️ Error Handling
52
92
 
53
- * Laravel validation errors (422) are automatically displayed in elements with class `.error-[field_name]`.
93
+ * **422 Validation Errors**: Automatically shown in `.error-[field_name]` spans.
94
+ * **Other Errors (500, 403, etc.)**: Logged to console or returned via `.catch()`.
54
95
 
55
- * **Example:** For field `email`, use `.error-email`
56
- * On other errors (like 500), a generic error is returned.
96
+ ---
57
97
 
58
- ## 📁 File Structure (Simplified)
98
+ ## 📁 File Structure
59
99
 
60
100
  ```
61
101
  laravel-ajax-helper/
62
- ├── dist/
63
- │ └── index.js # Transpiled output
102
+ ├── dist/ # Compiled code
64
103
  ├── src/
65
- │ └── index.js # Main AJAX function
104
+ │ └── index.js # Core logic
66
105
  ├── README.md
67
106
  ├── LICENSE
68
107
  ├── package.json
69
108
  ```
70
109
 
71
- ## 🪪 License
110
+ ---
72
111
 
73
- This project is licensed under the [MIT License](./LICENSE).
112
+ ## 🗪 License
74
113
 
75
- ## 🙌 Contributing
114
+ Licensed under the MIT License.
76
115
 
77
- Pull requests are welcome! Feel free to open issues or suggest improvements.
116
+ ---
78
117
 
79
118
  ## 💬 Author
80
119
 
81
- Akash Ap – [@akashap](https://github.com/aakashap01)
82
- Built with ❤️ for Laravel developers.
120
+ **Akash Ap**
121
+ Built with ❤️ for Laravel developers
122
+ GitHub: [@aakashap01](https://github.com/aakashap01)
@@ -0,0 +1,105 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/index.js
20
+ var index_exports = {};
21
+ __export(index_exports, {
22
+ default: () => laravelAjax
23
+ });
24
+ module.exports = __toCommonJS(index_exports);
25
+ function laravelAjax({
26
+ url,
27
+ method = "POST",
28
+ formId,
29
+ buttonId = null,
30
+ loadingText = "Loading...",
31
+ csrf = false,
32
+ // << true to auto-fetch from meta tag
33
+ onSuccess = null,
34
+ onError = null
35
+ }) {
36
+ return new Promise((resolve, reject) => {
37
+ if (!url) return reject({ error: "URL is required." });
38
+ if (!formId) return reject({ error: "formId is required." });
39
+ const form = document.getElementById(formId);
40
+ if (!form) return reject({ error: `Form with ID "${formId}" not found.` });
41
+ form.addEventListener("submit", (e) => e.preventDefault());
42
+ const formData = new FormData(form);
43
+ const btn = buttonId ? document.getElementById(buttonId) : null;
44
+ const originalBtnText = btn ? btn.innerHTML : null;
45
+ if (btn) {
46
+ btn.disabled = true;
47
+ btn.innerHTML = `<span class="spinner-border spinner-border-sm me-2"></span>${loadingText}`;
48
+ }
49
+ document.querySelectorAll('[class^="error-"]').forEach((el) => {
50
+ if (["DIV", "SPAN"].includes(el.tagName)) el.innerText = "";
51
+ });
52
+ const headers = {};
53
+ if (csrf) {
54
+ const tokenTag = document.querySelector('meta[name="csrf-token"]');
55
+ if (!tokenTag) {
56
+ if (btn) {
57
+ btn.disabled = false;
58
+ btn.innerHTML = originalBtnText;
59
+ }
60
+ return reject({
61
+ error: `CSRF token not found. Please add <meta name="csrf-token" content="..."> in <head>.`
62
+ });
63
+ }
64
+ headers["X-CSRF-TOKEN"] = tokenTag.getAttribute("content");
65
+ }
66
+ $.ajax({
67
+ url,
68
+ method,
69
+ data: formData,
70
+ headers,
71
+ contentType: false,
72
+ processData: false,
73
+ cache: false,
74
+ success: function(response) {
75
+ if (btn) {
76
+ btn.disabled = false;
77
+ btn.innerHTML = originalBtnText;
78
+ }
79
+ if (typeof onSuccess === "function") onSuccess(response);
80
+ resolve(response);
81
+ },
82
+ error: function(xhr) {
83
+ if (btn) {
84
+ btn.disabled = false;
85
+ btn.innerHTML = originalBtnText;
86
+ }
87
+ if (xhr.status === 422 && xhr.responseJSON?.errors) {
88
+ const errors = xhr.responseJSON.errors;
89
+ for (const field in errors) {
90
+ const el = document.querySelector(`.error-${field}`);
91
+ if (el && ["DIV", "SPAN"].includes(el.tagName)) {
92
+ el.innerText = errors[field][0];
93
+ }
94
+ }
95
+ if (typeof onError === "function") onError(errors);
96
+ reject(errors);
97
+ } else {
98
+ const fallbackError = { error: "Unexpected error occurred." };
99
+ if (typeof onError === "function") onError(fallbackError);
100
+ reject(fallbackError);
101
+ }
102
+ }
103
+ });
104
+ });
105
+ }
@@ -0,0 +1,85 @@
1
+ // src/index.js
2
+ function laravelAjax({
3
+ url,
4
+ method = "POST",
5
+ formId,
6
+ buttonId = null,
7
+ loadingText = "Loading...",
8
+ csrf = false,
9
+ // << true to auto-fetch from meta tag
10
+ onSuccess = null,
11
+ onError = null
12
+ }) {
13
+ return new Promise((resolve, reject) => {
14
+ if (!url) return reject({ error: "URL is required." });
15
+ if (!formId) return reject({ error: "formId is required." });
16
+ const form = document.getElementById(formId);
17
+ if (!form) return reject({ error: `Form with ID "${formId}" not found.` });
18
+ form.addEventListener("submit", (e) => e.preventDefault());
19
+ const formData = new FormData(form);
20
+ const btn = buttonId ? document.getElementById(buttonId) : null;
21
+ const originalBtnText = btn ? btn.innerHTML : null;
22
+ if (btn) {
23
+ btn.disabled = true;
24
+ btn.innerHTML = `<span class="spinner-border spinner-border-sm me-2"></span>${loadingText}`;
25
+ }
26
+ document.querySelectorAll('[class^="error-"]').forEach((el) => {
27
+ if (["DIV", "SPAN"].includes(el.tagName)) el.innerText = "";
28
+ });
29
+ const headers = {};
30
+ if (csrf) {
31
+ const tokenTag = document.querySelector('meta[name="csrf-token"]');
32
+ if (!tokenTag) {
33
+ if (btn) {
34
+ btn.disabled = false;
35
+ btn.innerHTML = originalBtnText;
36
+ }
37
+ return reject({
38
+ error: `CSRF token not found. Please add <meta name="csrf-token" content="..."> in <head>.`
39
+ });
40
+ }
41
+ headers["X-CSRF-TOKEN"] = tokenTag.getAttribute("content");
42
+ }
43
+ $.ajax({
44
+ url,
45
+ method,
46
+ data: formData,
47
+ headers,
48
+ contentType: false,
49
+ processData: false,
50
+ cache: false,
51
+ success: function(response) {
52
+ if (btn) {
53
+ btn.disabled = false;
54
+ btn.innerHTML = originalBtnText;
55
+ }
56
+ if (typeof onSuccess === "function") onSuccess(response);
57
+ resolve(response);
58
+ },
59
+ error: function(xhr) {
60
+ if (btn) {
61
+ btn.disabled = false;
62
+ btn.innerHTML = originalBtnText;
63
+ }
64
+ if (xhr.status === 422 && xhr.responseJSON?.errors) {
65
+ const errors = xhr.responseJSON.errors;
66
+ for (const field in errors) {
67
+ const el = document.querySelector(`.error-${field}`);
68
+ if (el && ["DIV", "SPAN"].includes(el.tagName)) {
69
+ el.innerText = errors[field][0];
70
+ }
71
+ }
72
+ if (typeof onError === "function") onError(errors);
73
+ reject(errors);
74
+ } else {
75
+ const fallbackError = { error: "Unexpected error occurred." };
76
+ if (typeof onError === "function") onError(fallbackError);
77
+ reject(fallbackError);
78
+ }
79
+ }
80
+ });
81
+ });
82
+ }
83
+ export {
84
+ laravelAjax as default
85
+ };
@@ -0,0 +1 @@
1
+ var laravelAjax=(()=>{var m=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var k=Object.prototype.hasOwnProperty;var q=(t,r)=>{for(var o in r)m(t,o,{get:r[o],enumerable:!0})},x=(t,r,o,f)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of N(r))!k.call(t,s)&&s!==o&&m(t,s,{get:()=>r[s],enumerable:!(f=D(r,s))||f.enumerable});return t};var A=t=>x(m({},"__esModule",{value:!0}),t);var H={};q(H,{default:()=>y});function y({url:t,method:r="POST",formId:o,buttonId:f=null,loadingText:s="Loading...",csrf:S=!1,onSuccess:p=null,onError:l=null}){return new Promise((g,i)=>{if(!t)return i({error:"URL is required."});if(!o)return i({error:"formId is required."});let c=document.getElementById(o);if(!c)return i({error:`Form with ID "${o}" not found.`});c.addEventListener("submit",n=>n.preventDefault());let L=new FormData(c),e=f?document.getElementById(f):null,u=e?e.innerHTML:null;e&&(e.disabled=!0,e.innerHTML=`<span class="spinner-border spinner-border-sm me-2"></span>${s}`),document.querySelectorAll('[class^="error-"]').forEach(n=>{["DIV","SPAN"].includes(n.tagName)&&(n.innerText="")});let T={};if(S){let n=document.querySelector('meta[name="csrf-token"]');if(!n)return e&&(e.disabled=!1,e.innerHTML=u),i({error:'CSRF token not found. Please add <meta name="csrf-token" content="..."> in <head>.'});T["X-CSRF-TOKEN"]=n.getAttribute("content")}$.ajax({url:t,method:r,data:L,headers:T,contentType:!1,processData:!1,cache:!1,success:function(n){e&&(e.disabled=!1,e.innerHTML=u),typeof p=="function"&&p(n),g(n)},error:function(n){if(e&&(e.disabled=!1,e.innerHTML=u),n.status===422&&n.responseJSON?.errors){let a=n.responseJSON.errors;for(let b in a){let d=document.querySelector(`.error-${b}`);d&&["DIV","SPAN"].includes(d.tagName)&&(d.innerText=a[b][0])}typeof l=="function"&&l(a),i(a)}else{let a={error:"Unexpected error occurred."};typeof l=="function"&&l(a),i(a)}}})})}return A(H);})();
package/package.json CHANGED
@@ -1,14 +1,18 @@
1
1
  {
2
2
  "name": "ap-laravel-ajax-helper",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "A lightweight JavaScript utility for Laravel-style AJAX requests.",
5
- "main": "dist/index.js",
6
- "module": "dist/index.esm.js",
5
+ "main": "dist/laravel-ajax.cjs.js",
6
+ "module": "dist/laravel-ajax.esm.js",
7
+ "browser": "dist/laravel-ajax.min.js",
8
+ "exports": {
9
+ "import": "./dist/laravel-ajax.esm.js",
10
+ "require": "./dist/laravel-ajax.cjs.js",
11
+ "default": "./dist/laravel-ajax.min.js"
12
+ },
7
13
  "scripts": {
8
- "build": "babel src --out-dir dist"
14
+ "build": "esbuild src/index.js --bundle --minify --format=iife --global-name=laravelAjax --outfile=dist/laravel-ajax.min.js && esbuild src/index.js --bundle --format=cjs --outfile=dist/laravel-ajax.cjs.js && esbuild src/index.js --bundle --format=esm --outfile=dist/laravel-ajax.esm.js"
9
15
  },
10
- "author": "AkashAp",
11
- "license": "MIT",
12
16
  "keywords": [
13
17
  "laravel",
14
18
  "ajax",
@@ -16,10 +20,13 @@
16
20
  "validation",
17
21
  "jquery"
18
22
  ],
23
+ "author": "AkashAp",
24
+ "license": "MIT",
19
25
  "devDependencies": {
20
26
  "@babel/cli": "^7.28.0",
21
27
  "@babel/core": "^7.28.0",
22
28
  "@babel/preset-env": "^7.28.0",
29
+ "esbuild": "^0.25.8",
23
30
  "rollup": "^3.0.0"
24
31
  },
25
32
  "peerDependencies": {
@@ -30,5 +37,13 @@
30
37
  "src/",
31
38
  "README.md",
32
39
  "LICENSE"
33
- ]
40
+ ],
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "https://github.com/aakashap01/ap-laravel-ajax-helper.git"
44
+ },
45
+ "bugs": {
46
+ "url": "https://github.com/aakashap01/ap-laravel-ajax-helper/issues"
47
+ },
48
+ "homepage": "https://github.com/aakashap01/ap-laravel-ajax-helper#readme"
34
49
  }
package/src/index.js CHANGED
@@ -1,9 +1,12 @@
1
1
  export default function laravelAjax({
2
2
  url,
3
3
  method = 'POST',
4
- formId = null,
4
+ formId,
5
5
  buttonId = null,
6
6
  loadingText = 'Loading...',
7
+ csrf = false, // << true to auto-fetch from meta tag
8
+ onSuccess = null,
9
+ onError = null,
7
10
  }) {
8
11
  return new Promise((resolve, reject) => {
9
12
  if (!url) return reject({ error: 'URL is required.' });
@@ -12,55 +15,77 @@ export default function laravelAjax({
12
15
  const form = document.getElementById(formId);
13
16
  if (!form) return reject({ error: `Form with ID "${formId}" not found.` });
14
17
 
15
- const formData = new FormData(form);
18
+ // Prevent default form submission
19
+ form.addEventListener('submit', (e) => e.preventDefault());
16
20
 
21
+ const formData = new FormData(form);
17
22
  const btn = buttonId ? document.getElementById(buttonId) : null;
18
- const originalButtonText = btn ? btn.innerHTML : null;
23
+ const originalBtnText = btn ? btn.innerHTML : null;
19
24
 
20
- // Disable and show loading on button
25
+ // Disable button and show loading text
21
26
  if (btn) {
22
27
  btn.disabled = true;
23
28
  btn.innerHTML = `<span class="spinner-border spinner-border-sm me-2"></span>${loadingText}`;
24
29
  }
25
30
 
26
- // Clear all validation error messages
31
+ // Clear previous validation errors
27
32
  document.querySelectorAll('[class^="error-"]').forEach((el) => {
28
- if (el.tagName === 'DIV' || el.tagName === 'SPAN') {
29
- el.innerText = '';
30
- }
33
+ if (['DIV', 'SPAN'].includes(el.tagName)) el.innerText = '';
31
34
  });
32
35
 
36
+ // Prepare headers
37
+ const headers = {};
38
+ if (csrf) {
39
+ const tokenTag = document.querySelector('meta[name="csrf-token"]');
40
+ if (!tokenTag) {
41
+ if (btn) {
42
+ btn.disabled = false;
43
+ btn.innerHTML = originalBtnText;
44
+ }
45
+ return reject({
46
+ error: `CSRF token not found. Please add <meta name="csrf-token" content="..."> in <head>.`,
47
+ });
48
+ }
49
+ headers['X-CSRF-TOKEN'] = tokenTag.getAttribute('content');
50
+ }
51
+
52
+ // Perform AJAX request
33
53
  $.ajax({
34
54
  url,
35
55
  method,
36
56
  data: formData,
57
+ headers,
37
58
  contentType: false,
38
59
  processData: false,
39
60
  cache: false,
40
61
  success: function (response) {
41
62
  if (btn) {
42
- btn.innerHTML = originalButtonText;
43
63
  btn.disabled = false;
64
+ btn.innerHTML = originalBtnText;
44
65
  }
66
+ if (typeof onSuccess === 'function') onSuccess(response);
45
67
  resolve(response);
46
68
  },
47
69
  error: function (xhr) {
48
- if (xhr.status === 422) {
49
- const errors = xhr.responseJSON?.errors || {};
70
+ if (btn) {
71
+ btn.disabled = false;
72
+ btn.innerHTML = originalBtnText;
73
+ }
74
+
75
+ if (xhr.status === 422 && xhr.responseJSON?.errors) {
76
+ const errors = xhr.responseJSON.errors;
50
77
  for (const field in errors) {
51
- const target = document.querySelector(`.error-${field}`);
52
- if (target && (target.tagName === 'DIV' || target.tagName === 'SPAN')) {
53
- target.innerText = errors[field][0];
78
+ const el = document.querySelector(`.error-${field}`);
79
+ if (el && ['DIV', 'SPAN'].includes(el.tagName)) {
80
+ el.innerText = errors[field][0];
54
81
  }
55
82
  }
83
+ if (typeof onError === 'function') onError(errors);
56
84
  reject(errors);
57
85
  } else {
58
- reject({ error: 'Unexpected error occurred.' });
59
- }
60
-
61
- if (btn) {
62
- btn.innerHTML = originalButtonText;
63
- btn.disabled = false;
86
+ const fallbackError = { error: 'Unexpected error occurred.' };
87
+ if (typeof onError === 'function') onError(fallbackError);
88
+ reject(fallbackError);
64
89
  }
65
90
  },
66
91
  });
package/dist/index.js DELETED
@@ -1,81 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports["default"] = laravelAjax;
7
- function laravelAjax(_ref) {
8
- var url = _ref.url,
9
- _ref$method = _ref.method,
10
- method = _ref$method === void 0 ? 'POST' : _ref$method,
11
- _ref$formId = _ref.formId,
12
- formId = _ref$formId === void 0 ? null : _ref$formId,
13
- _ref$buttonId = _ref.buttonId,
14
- buttonId = _ref$buttonId === void 0 ? null : _ref$buttonId,
15
- _ref$loadingText = _ref.loadingText,
16
- loadingText = _ref$loadingText === void 0 ? 'Loading...' : _ref$loadingText;
17
- return new Promise(function (resolve, reject) {
18
- if (!url) return reject({
19
- error: 'URL is required.'
20
- });
21
- if (!formId) return reject({
22
- error: 'formId is required.'
23
- });
24
- var form = document.getElementById(formId);
25
- if (!form) return reject({
26
- error: "Form with ID \"".concat(formId, "\" not found.")
27
- });
28
- var formData = new FormData(form);
29
- var btn = buttonId ? document.getElementById(buttonId) : null;
30
- var originalButtonText = btn ? btn.innerHTML : null;
31
-
32
- // Disable and show loading on button
33
- if (btn) {
34
- btn.disabled = true;
35
- btn.innerHTML = "<span class=\"spinner-border spinner-border-sm me-2\"></span>".concat(loadingText);
36
- }
37
-
38
- // Clear all validation error messages
39
- document.querySelectorAll('[class^="error-"]').forEach(function (el) {
40
- if (el.tagName === 'DIV' || el.tagName === 'SPAN') {
41
- el.innerText = '';
42
- }
43
- });
44
- $.ajax({
45
- url: url,
46
- method: method,
47
- data: formData,
48
- contentType: false,
49
- processData: false,
50
- cache: false,
51
- success: function success(response) {
52
- if (btn) {
53
- btn.innerHTML = originalButtonText;
54
- btn.disabled = false;
55
- }
56
- resolve(response);
57
- },
58
- error: function error(xhr) {
59
- if (xhr.status === 422) {
60
- var _xhr$responseJSON;
61
- var errors = ((_xhr$responseJSON = xhr.responseJSON) === null || _xhr$responseJSON === void 0 ? void 0 : _xhr$responseJSON.errors) || {};
62
- for (var field in errors) {
63
- var target = document.querySelector(".error-".concat(field));
64
- if (target && (target.tagName === 'DIV' || target.tagName === 'SPAN')) {
65
- target.innerText = errors[field][0];
66
- }
67
- }
68
- reject(errors);
69
- } else {
70
- reject({
71
- error: 'Unexpected error occurred.'
72
- });
73
- }
74
- if (btn) {
75
- btn.innerHTML = originalButtonText;
76
- btn.disabled = false;
77
- }
78
- }
79
- });
80
- });
81
- }