-
-
Notifications
You must be signed in to change notification settings - Fork 5
Replace jQuery AJAX calls with fetch API #381
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Replace jQuery AJAX calls with fetch API #381
Conversation
- Replaced all $.ajax() calls with fetch() across frontend and templates - Replaced $.ajaxSetup with direct CSRF token handling in fetch requests - Replaced $.post() calls with fetch() for consistency - Used URLSearchParams for form data encoding - Maintained all existing error handling and success callbacks - Added proper timeout handling using AbortController where needed Files modified: - frontend/src/microscope-form.js - frontend/src/my-litemol.js - frontend/src/js/project.js (15+ replacements) - frontend/src/js/favit.js - frontend/src/js/scope_report.js - packages/blast/src/App.jsx - backend/proteins/templates/proteins/spectrum_form.html All changes compile successfully and maintain backward compatibility.
for more information, see https://pre-commit.ci
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #381 +/- ##
==========================================
+ Coverage 60.52% 60.58% +0.06%
==========================================
Files 110 110
Lines 8823 8809 -14
==========================================
- Hits 5340 5337 -3
+ Misses 3483 3472 -11 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
This PR migrates all jQuery AJAX calls to the native Fetch API across the FPbase codebase, modernizing the networking layer while maintaining backward compatibility with Django's AJAX detection.
Key changes:
- Created unified
ajax-sentry.jsmodule providingfetchWithSentry()wrapper with Sentry error tracking for both jQuery AJAX (legacy) and fetch requests - Replaced 15+
$.ajax(),$.post(), and$.getJSON()calls with fetch across frontend JavaScript files and Django templates - Added proper CSRF token handling via headers for fetch requests
- Maintained backward compatibility by including
X-Requested-With: XMLHttpRequestheader where needed - Removed backend
is_ajax()checks that are no longer necessary
Reviewed Changes
Copilot reviewed 17 out of 17 changed files in this pull request and generated 24 comments.
Show a summary per file
| File | Description |
|---|---|
| frontend/src/js/ajax-sentry.js | New unified module replacing jquery-ajax-sentry.js, adds fetchWithSentry wrapper with Sentry integration for both jQuery and fetch |
| frontend/src/js/project.js | Migrated 15+ AJAX calls to fetch with URLSearchParams for form data encoding |
| frontend/src/js/favit.js | Converted favorite add/remove endpoints to fetch |
| frontend/src/js/scope_report.js | Migrated scope report polling and update requests to fetch |
| frontend/src/js/fret.js | Converted FRET calculator data fetching to fetch |
| frontend/src/my-litemol.js | Migrated PDB data fetching with proper timeout handling using AbortController |
| frontend/src/microscope.js | Updated spectra fetching with proper error handling |
| frontend/src/microscope-form.js | Converted filter import form submissions to fetch |
| packages/blast/src/App.jsx | Migrated BLAST form submission to fetch in React component |
| backend/proteins/templates/proteins/spectrum_form.html | Replaced inline jQuery AJAX with fetch for spectrum preview |
| backend/proteins/views/ajax.py | Removed unnecessary is_ajax() checks from AJAX view endpoints |
| backend/favit/views.py | Removed is_ajax() checks from favorite endpoints |
| backend/tests/test_proteins/test_ajax_views.py | Updated test to reflect that X-Requested-With header is no longer required |
| frontend/src/index.js | Updated import to use new ajax-sentry module |
| frontend/src/fret.js | Updated import to use new ajax-sentry module |
| frontend/src/scope-report.js | Updated import to use new ajax-sentry module |
| frontend/src/microscope-form.js | Updated import to use new ajax-sentry module |
| .finally(() => { | ||
| $("#footerSpinner").hide() | ||
| // $('#importModal').modal('hide') | ||
| }) | ||
| }) |
Copilot
AI
Nov 17, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing error handler for this fetch call. If the request fails (network error or HTTP error status), it will result in an unhandled promise rejection. The .finally() block will execute but errors won't be handled. Add a .catch() handler before .finally() to handle errors and potentially show user feedback.
| .finally(() => { | |
| $("#footerSpinner").hide() | |
| // $('#importModal').modal('hide') | |
| }) | |
| }) | |
| .catch((error) => { | |
| $(`#${brand}Input`).addClass("is-invalid"); | |
| $(`#${brand}Help`) | |
| .removeClass("text-muted") | |
| .addClass("invalid-feedback") | |
| .text(`ERROR: ${error && error.message ? error.message : "An unexpected error occurred."}`) | |
| .show(); | |
| $("#footerSpinner").hide(); | |
| $("#footerFail").show(); | |
| $("#footerSuccess").hide(); | |
| }) | |
| .finally(() => { | |
| $("#footerSpinner").hide() | |
| // $('#importModal').modal('hide') | |
| }) |
| fetchWithSentry(button.attr("data-action-url"), { | ||
| method: "POST", | ||
| headers: { | ||
| "Content-Type": "application/x-www-form-urlencoded", | ||
| // Legacy header required by Django is_ajax() check in dual-purpose endpoints | ||
| "X-Requested-With": "XMLHttpRequest", | ||
| }, | ||
| success: (response) => { | ||
| body: formData, | ||
| }) | ||
| .then((response) => response.json()) | ||
| .then((response) => { | ||
| if (response.status === "deleted") { | ||
| button.closest("tr").remove() | ||
| } | ||
| }, | ||
| }) | ||
| e.preventDefault() | ||
| }) |
Copilot
AI
Nov 17, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing error handler for this fetch call. If the request fails (network error or HTTP error status), it will result in an unhandled promise rejection. Add a .catch() handler to gracefully handle errors.
| fetchWithSentry(form.attr("data-action-url"), { | ||
| method: "POST", | ||
| headers: { | ||
| "Content-Type": "application/x-www-form-urlencoded", | ||
| // Legacy header required by Django is_ajax() check in dual-purpose endpoints | ||
| "X-Requested-With": "XMLHttpRequest", | ||
| }, | ||
| body: data, | ||
| cache: "no-store", | ||
| }) |
Copilot
AI
Nov 17, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing promise handlers for this fetch call. The request is initiated but there's no .then() or .catch() to handle the response or errors. This will result in unhandled promise rejections on network errors. Either add proper handlers or, if this is intentionally fire-and-forget, add a .catch() to silently handle errors and document the intention.
| "There was an error processing your input. Please double check that it is an amino acid or nucleotide sequence, or multiple sequences in FASTA format" | ||
| ) | ||
| } | ||
| }) |
Copilot
AI
Nov 17, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing error handler for this fetch call. If the request fails (network error or HTTP error status), it will result in an unhandled promise rejection. Add a .catch() handler to gracefully handle errors and provide user feedback.
| }) | |
| }) | |
| .catch((error) => { | |
| console.error("Network or server error during BLAST request:", error); | |
| alert( | |
| "A network or server error occurred while processing your request. Please try again later." | |
| ); | |
| }); |
frontend/src/my-litemol.js
Outdated
| // Legacy header required by Django is_ajax() check in dual-purpose endpoints | ||
| "X-Requested-With": "XMLHttpRequest", |
Copilot
AI
Nov 17, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The comment about the X-Requested-With header is inaccurate. This is not a Django endpoint but an external RCSB GraphQL API (https://data.rcsb.org/graphql). The X-Requested-With header is not needed here and should be removed, along with the misleading comment.
| // Legacy header required by Django is_ajax() check in dual-purpose endpoints | |
| "X-Requested-With": "XMLHttpRequest", |
| }, | ||
| }) | ||
| }) | ||
| } |
Copilot
AI
Nov 17, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing error handler for this promise chain. If the check_status request fails or any of the subsequent operations throw an error, it will result in an unhandled promise rejection. Add a .catch() handler to gracefully handle errors.
| } | |
| .catch((error) => { | |
| // Gracefully handle errors: show alert, reset UI, and optionally log error | |
| $("#update-alert") | |
| .addClass("alert-danger") | |
| .removeClass("alert-info") | |
| .text("An error occurred while checking the report status. Please try again.") | |
| .show(); | |
| reset_button(); | |
| // Optionally log error to console or Sentry | |
| // console.error("Error in check_status:", error); | |
| }); |
| }, | ||
| }) | ||
| e.preventDefault() | ||
| }) |
Copilot
AI
Nov 17, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing error handler for this fetch call. If the request fails (network error or HTTP error status), it will result in an unhandled promise rejection. Add a .catch() handler to gracefully handle errors.
| }) | |
| }) | |
| .catch((error) => { | |
| console.error("Failed to fetch collection data:", error); | |
| // Optionally, show a user-facing error message here | |
| }) |
| fetchWithSentry(form.attr("data-action-url"), { | ||
| method: "POST", | ||
| headers: { | ||
| "Content-Type": "application/x-www-form-urlencoded", | ||
| // Legacy header required by Django is_ajax() check in dual-purpose endpoints | ||
| "X-Requested-With": "XMLHttpRequest", | ||
| }, | ||
| body: form.serialize(), | ||
| }) | ||
| .then((response) => response.json()) | ||
| .then((_data) => { | ||
| $(`<option value="${tax_id}">${sci_name} </option>`).appendTo("#id_parent_organism") | ||
| $(`#id_parent_organism option[value="${tax_id}"]`).prop("selected", true) | ||
| $("#organismModal").modal("hide") | ||
| }, | ||
| }) | ||
| }) |
Copilot
AI
Nov 17, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing the X-Requested-With header that is present in the first fetch call within this handler. For consistency and to ensure Django's legacy AJAX detection works properly (as noted in other files), this nested fetch should also include the header.
| headers: { | ||
| "Content-Type": "application/x-www-form-urlencoded", | ||
| }, |
Copilot
AI
Nov 17, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing the X-Requested-With header. The favit endpoint is a Django AJAX endpoint, and for consistency with other POST requests in the codebase, this should include the 'X-Requested-With': 'XMLHttpRequest' header.
Co-authored-by: Copilot <[email protected]>
|
@claude please review |
|
Claude finished @tlambert03's task —— View job Code Review Complete ✓I've completed a thorough review of this jQuery AJAX to fetch API migration. Overall, this is a well-executed modernization with good attention to backward compatibility and error tracking. Here's my detailed feedback: ✅ Strengths1. Excellent Sentry IntegrationThe new
2. Proper CSRF HandlingCSRF tokens are correctly included via headers across all fetch calls, maintaining Django's security requirements. 3. Backward CompatibilityThe 4. Consistent PatternsMost conversions follow a consistent pattern: fetchWithSentry(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest',
},
body: formData,
})
.then(response => response.json())
.then(data => { /* handle success */ })🔍 Issues to AddressCritical Issues1. Missing Error Handlers (Multiple Locations) Several fetch calls lack
Recommendation: Add .catch(() => {}) // Silent fail for fire-and-forget2. Inconsistent Header Usage Two issues with headers:
3. Nested Fetch Without Header Consistency frontend/src/js/project.js:997 - The nested fetch call inside the taxonomy modal handler is missing the Minor Issues4. Outdated Comments Several files have comments that say "Track jQuery AJAX errors" when they now track both jQuery and fetch:
Recommendation: Update to "Track AJAX and fetch errors" or "Track jQuery AJAX and fetch errors" 5. Potential JSON Parsing Error frontend/src/js/favit.js:63 - If 💡 Suggestions for Improvement1. Error Handling PatternConsider establishing a consistent error handling pattern across the codebase. For example: .catch((error) => {
console.error('Operation failed:', error)
// Optionally show user feedback
})2. AbortController UsageThe 3. Cache StrategyThe PDB metadata caching in 📊 Copilot Review AssessmentThe copilot review identified most of the genuine issues. Here's my assessment of its findings: Valid Issues (Should Fix):
Invalid/Questionable:
✅ What's Working Well
🎯 SummaryThis PR successfully modernizes the AJAX infrastructure with minimal breaking changes. The main work needed is:
Once these issues are addressed, this will be a solid modernization that improves maintainability while preserving all existing functionality. Overall Assessment: ⭐⭐⭐⭐ (4/5)
|
Files modified:
All changes compile successfully and maintain backward compatibility.