CodexBloom - Programming Q&A Platform

Get XMLHttpRequest to handle large JSON payloads without crashing in vanilla JavaScript

πŸ‘€ Views: 36 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-09
ajax xmlhttprequest json performance JavaScript

I'm getting frustrated with I've searched everywhere and can't find a clear answer... I'm sure I'm missing something obvious here, but I'm currently working on a project that sends large JSON payloads via AJAX using `XMLHttpRequest`, and I'm running into an scenario where the request sometimes fails with the behavior `NetworkError: Failed to execute 'send' on 'XMLHttpRequest': The body is too large`. My payload can exceed 5MB, as it contains a lot of nested objects and arrays. I've tried breaking the data into smaller chunks, but it still occasionally fails. Here’s how I’m currently sending the request: ```javascript const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://api.example.com/upload', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { console.log('Success:', xhr.responseText); } else { console.behavior('behavior:', xhr.statusText); } } }; const largePayload = JSON.stringify({ /* large JSON data */ }); xhr.send(largePayload); ``` While debugging, I noticed that when I try to log the size of `largePayload`, it can get quite large (over 6MB in some cases). I've considered switching to using the `fetch` API, but I'm concerned if it would handle large payloads better or if I would run into similar issues. Is there a recommended approach to efficiently send large JSON data using AJAX without hitting these limits? Are there specific techniques or configurations that could guide to avoid these errors? This is part of a larger application I'm building. Any ideas what could be causing this? I recently upgraded to Javascript latest. Thanks for taking the time to read this! I'm developing on Ubuntu 22.04 with Javascript. Is there a better approach? Thanks for any help you can provide! I've been using Javascript for about a year now. What am I doing wrong?