The onreadystatechange function in AJAX is malfunctioning

I am facing an issue with the onreadystatechange while making an ajax request. Previously, it would call the processRequest function successfully but now it seems to be malfunctioning.

I'm uncertain if I inadvertently made any changes or modifications that caused this problem. Can someone offer assistance?

function createAjaxObject(url, callback) 
{
    /// @par Implementation 
    var req = init();
  req.onreadystatechange = processRequest;

    /// @brief  Creates a new ajax object based on the running browser    
    function init() 
    {
        if (window.XMLHttpRequest)
            return new XMLHttpRequest();
        else if (window.ActiveXObject) 
            return new ActiveXObject("Microsoft.XMLHTTP");
    }

    /// @brief Checks if the request is complete and HTTP call is successful
    function processRequest () 
    {   

        /// A readyState of 4 signifies a completed request

        if (req.readyState == 4){

            /// A status of 200 indicates a successful HTTP call
            if (req.status == 200){
                if (callback) 
                callback(req.responseXML);
            }
        }
    }

     this.doPost = function(param) {

             if (req.readyState == 4) {

        /// Make an asynchronous HTTP POST request to the specified URL
        req.open("POST",url, true);
        req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        req.setRequestHeader("Content-length",param.length);
        req.setRequestHeader("Connection", "close");
        req.send(param);

        }
    }
}

Thank you,

Answer №1

Here is a suggestion regarding your code:

if (req.readyState == 4) {

The above line (and the corresponding }) should not be included in the function that you are assigning to this.doPost. The correct approach would be:

this.doPost = function(param) {

    /// make a HTTP GET request to the URL asynchronously
    req.open("POST",url, true);
    req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    req.setRequestHeader("Content-length",param.length);
    req.setRequestHeader("Connection", "close");
    req.send(param);
};

It seems like you intend to use it this way:

var obj = new createAjaxObject(url, callback);
obj.doPost();

Just a tip: It is recommended to capitalize the initial letter of functions used as constructors in JavaScript code. For example, consider using CreateAjaxObject (or simply AjaxObject) instead of createAjaxObject.

There are some other changes you might want to consider implementing as well, but for now, these adjustments should suffice.


On a side note: I suggest utilizing a JavaScript library such as jQuery, Prototype, YUI, Closure, or any other reputable options available. These libraries help iron out browser inconsistencies and offer a wide range of pre-tested utility functions, enabling you to focus on your core tasks without worrying about cross-browser compatibility.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Angular application sent an OPTIONS request instead of a POST request via HTTP

I'm encountering CORS errors while attempting to send HTTP requests from my angular.js application to my server. The code used to make the HTTP request is as follows: functions.test = function(foo, bar) { return $http({ method: 'POS ...

Instead of broadcasting your message to the channel, try sending it directly to the user

While attempting to send this embed to a user's DMs instead of a channel, I have encountered numerous outdated and irrelevant posts that do not address my specific question. module.exports = { name: 'help', description: 'this is a ...

Building intricate hierarchical menus with Material-UI 4.9

I am currently incorporating the @material-ui/core library into my application and aiming to implement a nested menu feature. I have referred to the material.io specification which discusses nested menus, but unfortunately, the material-ui library does not ...

Inconsistent 404 Error when Making Socket.io Ajax Requests

My Node server is responsible for managing user sessions, chatrooms, messaging, web scraping, and other tasks. Sometimes, when attempting to send messages from the website to the Node server, I encounter a 404 error in the response. This issue occurs rare ...

Why is it necessary to include await for my query to work properly? What can be done to resolve the issue of 'query.orderBy' not being recognized as a function?

I have been working with node.js, MySQL, knex, and express to execute a simple database query using db.findAllEmoji(). The code snippet for this query is shown below: const findAllEmoji = () => { return knex('emoji') .select('*') ...

Retrieve the parent's current state by accessing it through a callback function in React

My callback function onRestore is only logging the history until the id of the clicked snapshot. Why is it showing incorrect state? I've exhausted all options, so any help would be appreciated. import React, { useState, useEffect, useRef } from "re ...

What are some ways to create a ui-view that maintains its content without refreshing automatically?

My application utilizes 2 ui-views to display content - one for the friendlist and the other for a specific view: <div class="container-fluid h100"> <div ui-view class="h100"> </div> <div ui-view="connected"> </div> ...

The table vanishes once the AJAX operation has been completed

After clicking the button to request data from my controller, my table disappears inexplicably. The table structure is as follows: <div id="SelectedTm" style= float:right> <table id = "PlyrsTm2" style = float:right> <tr>& ...

Table data is being displayed from form data in another file using only JavaScript

I am trying to figure out how to use local storage to store form data in one HTML file and display it in a table on another HTML file. The form data should be stored in the columns of the table but on a separate page. Can anyone provide assistance with thi ...

Issue encountered while trying to execute Reapp project demo

As I embark on setting up my initial Reapp project, I encounter a roadblock right at the start. A blank screen greets me, accompanied by a console error stating that main.js is not found (error 404). Upon executing reapp run -d, the following errors manif ...

HTML5 input type Color displays individual RGB values

This code snippet opens up a variety of options for the user to manipulate different color values such as R, G, B, HEX VALUE, HUE, etc. However, the specific requirement is to only extract the Red value. <input id="color_pick"type="color" value="#ff0 ...

Attempting to convert a Raw image file and upload it onto the server

I am currently attempting to upload an image to my server using PHP. I have two files for this task - index.php and myscript.php. Index.php <div id="results">Your captured image will appear here...</div> <h1>Mugshot Test Page& ...

Is there a way to incorporate Vue script in Laravel without utilizing Vue templates?

I have a question that may seem simple, but I'm curious about the best way to use vue script on pages individually without declaring it globally. For example, I have multiple pages in Laravel Blade such as the home page, category page, and product pag ...

Display/Modify HTML form

Looking for advice on how to create an interactive HTML form that displays data and allows users to edit it by clicking 'Edit' before submitting changes. Any suggestions on how to implement this functionality? ...

Using JavaScript to assign the title property to an <a> tag

I'm currently working on modifying a code snippet that utilizes jQuery to display the "title" attribute in an HTML element using JavaScript: <a id="photo" href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><i ...

Tips for avoiding repeated Modal Popup instances and preventing the page from automatically scrolling to the last element when using ReactJS

I've been working on a project where I'm fetching data from a server and displaying 10 different sets of data in Bootstrap cards using the map() function. Each card contains a button to open a modal, along with a Link that shows the route related ...

Refresh outfit designs or retrieve information from fragment shader post-processing

While working on image processing in the fragment shader (specifically thresholding), I find myself wanting to access the processed result from JavaScript so that I can save the modified image using standard JavaScript methods. I send the original texture ...

Is there a way to manipulate the appearance of a scroller using JavaScript?

I'm intrigued by how fellow front-end developers are able to customize the scrollbar shape on a webpage to enhance its appearance. Can anyone guide me on using JavaScript to accomplish this? ...

How can I retrieve routing parameters in a Vue.js/Nuxt/TypeScript app?

In the process of developing my website based on the Nuxt TypeScript Starter template, I've encountered a challenge. Specifically, I have created a dynamically routed page named _id.vue within my pages folder and am looking to access the id property i ...

When a new component is loaded, React Martial UI component may face issues due to overwriting or

Currently, we are working on a vast web application that utilizes jquery and bootstrap. Our current task involves transitioning this extensive app to React with Material UI, piece by piece. As we progress towards transforming it into a React app, everythin ...