Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8799317
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T00:17:33+00:00 2026-06-14T00:17:33+00:00

I’ve made an ajax post function, and when I call it once, the callback

  • 0

I’ve made an ajax post function, and when I call it once, the callback function that is passed to it ends up getting called 3 times. Why is the callback being called multiple times?

I’m attempting to use a “module” javascript pattern that uses closures to wrap like functionality under one global variable. My ajax module is its own file, and looks like this:

var ajax = (function (XMLHttpRequest) {
    "use strict";

    var done = 4, ok = 200;

    function post(url, parameters, callback) {

        var XHR = new XMLHttpRequest();

        if (parameters === false || parameters === null || parameters === undefined) {
            parameters = "";
        }

        XHR.open("post", url, true);
        XHR.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        XHR.onreadystatechange = function () {
            if (XHR.readyState === done && XHR.status === ok) {
                callback(XHR.responseText);
            }
        };
        XHR.send(parameters);
    }

    // Return the function/variable names available outside of the module.
    // Right now, all I have is the ajax post function.
    return {
        post: post
    };

}(parent.XMLHttpRequest));

The main application is also it’s own file. It, as an example, looks like this:

// Start point for program execution.

(function (window, document, ajax) {
    "use strict";

    ajax.post("php/paths.php", null, function () { window.alert("1"); });

}(this, this.document, parent.ajax));

As you can see, I’m trying to bring in dependencies as local variables/namespaces. When this runs, it pops up the alert box 3 times.

I’m not sure if this problem is due to the ajax function itself or the overall architecture (or both), so I’d appreciate comments or thoughts on either.

I’ve tried un-wrapping the main part of the program from the anonymous function, but that didn’t help. Thanks in advance!

EDIT:
Here’s the entire HTML file, so you can see the order I include the <script>‘s in.

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta http-equiv="expires" conent="0" />
    <title>Mapalicious</title>
    <link href="css/main.css" type="text/css" rel="stylesheet" />
    <script src="js/raphael.js"></script>
</head>
<body>
    <div id="map"></div>
    <script src="js/promise.js"></script>
    <script src="js/bigmap.js"></script>
    <script src="js/ajax.js"></script>
    <script src="js/init.js"></script>
</body>
</html>

EDIT 2:

I had a typo in my example, and changed

(function (window, document, bigmap, ajax) {

to

(function (window, document, ajax) {

EDIT 3:

I’ve changed the onreadystatechange function to log the ready state to the console:

XHR.onreadystatechange = function () {
    console.log("readyState: " + XHR.readyState);
    if (XHR.readyState === done && XHR.status === ok) {
        callback(XHR.responseText);
    }
};

When I step through the code in Google Chrome, the callback is called three times, and the console logs:

readyState: 4
readyState: 4
readyState: 4

However, when I run the page as normal and don’t step through it, the function works as expected and only runs the callback once. In this case, the console logs:

readyState: 2
readyState: 3
readyState: 3
readyState: 4

So now my question is, why is the callback called multiple times when stepping through code?

SOLVED:

When I asked this question, I didn’t realize that it was only happening when I was stepping through the code while debugging.

So, the state changed 3 times, but execution has been delayed by the break-point, so all 3 onreadystatechange functions see the current state of 4, instead of what the state was when the change actually occurred.

The takeaway is that onreadystatechange change does not store what that state is. Instead, it reads the readyState at the time its executed, even if the program gets interrupted, and the state changes again in the mean time.

Therefore, AJAX requires different debugging techniques than you use with completely synchronous code… but you probably already knew that.

Thanks to everyone who helped out here.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T00:17:34+00:00Added an answer on June 14, 2026 at 12:17 am

    The readyState has 4 distinct states:

    0 – no request initialized
    1 – connected to server
    2 – request was received
    3 – processing
    4 – Done, response received

    Each of these changes will call the onreadystatechange handler. That’s why most of these functions will look like this:

    xhr.onreadystatechange = function()
    {
        if (this.readyState === 4 && this.status === 200)
        {
            //do stuff with this.responseText
        }
    }
    

    Just hard-code them, instead of using dodgy variables (the names done and ok seem dangerous to me).

    Other than that, try declaring the post function either directly in the returned object:

    return {post : function()
    {
    };
    

    Or as an anon. function, assigned to the variable post:

    var post = function(){};
    

    Various engines do various things with functions, the way you declare them, hoisting them, for one. Also post doesn’t feel right as a function name if you ask me… I’d try to use names that don’t look like they might be reserved…

    Also, you’re not explicitly setting the XHR’s X-Requested-With header:

    XHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    

    Which might just be what’s causing the problem (HTTP1.1 and transfer-encoding chunked?)

    To make debugging easier, try logging the XHR object each time the alert shows up by changing callback(XHR.responseText); to callback.apply(this,[this.responseText]);, although the argument is redundant. Then, change ajax.post("php/paths.php", null, function () { window.alert("1"); }); to:

    ajax.post("php/paths.php", null,
    function (response)
    {
         console.log(this.readyState);//or alert the readyState
         window.alert(response);//check the response itself, for undefined/valid responses
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I need a function that will clean a strings' special characters. I do NOT
I'm trying to create an if statement in PHP that prevents a single post
Let's say I'm outputting a post title and in our database, it's Hello Y&#8217;all
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I've got a string that has curly quotes in it. I'd like to replace
I have a small JavaScript validation script that validates inputs based on Regex. I
I have a French site that I want to parse, but am running into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.