jQuery AJAX Error with Status Code 0 – What It Means and How to Fix It

//

user

While working on a form that submits via AJAX, I ran into a frustrating issue.
Every time I hit the submit button, the AJAX call failed—
and xhr.status returned 0.

What does status code: 0 even mean?

Let’s dive in.


🔍 The Setup

I had a typical HTML form like this:

<form name="Frm" method="post" onsubmit="return submit_check(this);">
<input type="submit" value="submit">
</form>

And the submit handler looked like this:

function submit_check(f) {
jQuery.ajax({
type: "GET",
url: target_url,
success: function(msg) {
// success!
},
error: function(xhr, status, error) {
alert("code: " + xhr.status);
}
});

f.action = submit_url;
return true;
}

Every time the form was submitted, the alert showed:

code: 0

What Does AJAX status = 0 Mean?

There’s no official HTTP status code 0. But jQuery (and other XHR tools) will return 0 when:

1. Cross-Origin Request Fails

The browser silently blocks access to another domain due to CORS restrictions.

2. Network Issues

The target URL is unreachable (e.g., wrong domain, DNS error, typo in URL).

3. Page Navigation Before Response

Your script makes an AJAX request, but the page refreshes or navigates away (e.g., form submits or window reloads) before the response comes back.
That cancels the request, and jQuery throws a status = 0.

In my case, it was Reason #3.
The form was submitting before the AJAX request could complete.


🛠️ The Fix – Delay Form Submission Until AJAX Completes

✅ Step 1: Remove onsubmit from <form>

<!-- ❌ No more onsubmit -->
<!-- ✅ Use a button with an event handler -->
<input type="button" value="submit" onclick="submit_check()">

✅ Step 2: Trigger form submission after AJAX success

function submit_check() {
jQuery.ajax({
type: "GET",
url: target_url,
success: function(msg) {
// ✅ AJAX succeeded, now submit the form
document.Frm.action = submit_url;
document.Frm.submit();
},
error: function(xhr, status, error) {
alert("code: " + xhr.status);
}
});
}

Final Thoughts

When working with AJAX, timing matters.

The browser doesn’t wait for your AJAX call to finish—it just keeps executing.
If the form is submitted or the page refreshes before the AJAX call finishes, the call gets canceled, and jQuery returns a mysterious status = 0.

To avoid that:

  • Use <input type="button"> instead of <input type="submit">
  • Submit the form manually after the AJAX call succeeds

This gives your logic full control and ensures a smooth experience.
No more disappearing requests. No more confusing error codes.

Happy debugging! 🔧

Leave a Comment