TorontoJim
TorontoJim

Reputation: 11

Ajax response increments with each submission

I have an odd situation with Ajax that may only be odd due to my lack of experience with it.

I have a test form I've been using and have found that I get an increasing number of responses with each test iteration.

What I mean is that after the page loads and I submit test data, I get a single OK response.

Then I submit a second time and get 2 responses of OK. Submit 3 times ... 3 responses. It will only go back to a single response if I refresh the page.

I could put a counter in the function and block more than one response, but I'd rather know why this is happening and see if I can correct it. In the end, I won't have the alert window in the final product but I'll still know it's happening and that will annoy the heck out of me.

Can anyone provide an idea why I'm getting an increasing number of responses with each submission iteration?

Here is the JS:

var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
  XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
  XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}

function sendAjaxFormData(url, frmName) {
    const jsonString = formToJson(frmName);
    console.log(jsonString);
    // Define what happens on successful data submission
    XMLHttpRequestObject.addEventListener('load', (event) => {
        alert('Yeah! Data sent and response loaded.');
    });
    // Define what happens in case of an error
    XMLHttpRequestObject.addEventListener('error', (event) => {
        alert('Oops! Something went wrong.');
    });
    // Set up our request
    XMLHttpRequestObject.open('POST', url, true);
    XMLHttpRequestObject.setRequestHeader("Content-Type", "application/json");
    // Send our FormData object; HTTP headers are set automatically
    XMLHttpRequestObject.send(jsonString);
}

function formToJson(frmName) {
    var form = document.getElementById(frmName);
    var frmDict = {};
    for(let field of form.elements) {
        frmDict[field.name] = field.value;
    }
    return JSON.stringify(frmDict);
}

Here is the HTML (I've removed the URL for brevity).

<form name="frmTest" id="frmTest" method="post" class="basic" action="">
<input type="text" name="field1" id="field1" value="" style="width:200px;" /><br />
<input type="text" name="field2" id="field2" value="" style="width:200px;" /><br />
<input type="text" name="field3" id="field3" value="" style="width:200px;" /><br />
<input type="button" name="btnTest" value="Test"  onclick="sendAjaxFormData('URL_GOES_HERE', 'frmTest');" />
</form>

Upvotes: 1

Views: 30

Answers (1)

notrev
notrev

Reputation: 680

The problem is that everytime you click on the button, you add a new event listener to the XMLHttpRequestObject, and they accumulate.

You should add the event listeners only once.

Try adding them right after you instantiate the XMLHttpRequestObject instead of when the button is clicked. Like this:

var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
  XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
  XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}

// Define what happens on successful data submission
XMLHttpRequestObject.addEventListener('load', (event) => {
    alert('Yeah! Data sent and response loaded.');
});

// Define what happens in case of an error
XMLHttpRequestObject.addEventListener('error', (event) => {
    alert('Oops! Something went wrong.');
});

function sendAjaxFormData(url, frmName) {
    const jsonString = formToJson(frmName);
    console.log(jsonString);
    // Set up our request
    XMLHttpRequestObject.open('POST', url, true);
    XMLHttpRequestObject.setRequestHeader("Content-Type", "application/json");
    // Send our FormData object; HTTP headers are set automatically
    XMLHttpRequestObject.send(jsonString);
}

function formToJson(frmName) {
    var form = document.getElementById(frmName);
    var frmDict = {};
    for(let field of form.elements) {
        frmDict[field.name] = field.value;
    }
    return JSON.stringify(frmDict);
}

Upvotes: 0

Related Questions