Creating a Dynamic Chatbox with JavaScript and Asynchronous Loading技术

I have spent hours going through various demos, AJAX, and JavaScript tutorials, but I am still struggling to make this work properly. Here is the code I currently have...

function createRequestObject() {
var ro = false;
if (window.XMLHttpRequest) {             // Mozilla, Safari, ...            
    ro = new XMLHttpRequest();
} else if (window.ActiveXObject) {       // IE                              
    try {
        ro = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            ro = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) { }
    }
}
return ro;
}


function ajaxrequest(){
var http = createRequestObject();
if(http) {
    var name = "Strassburg";
    var message = "Strike three you're out";
    http.open('post', '/server/shout.php');
    // needed in order for most servers to see POST data                    
    http.setRequestHeader('Content-Type',
                          'application/x-www-form-urlencoded');
    http.onreadystatechange = function() {
        if(http.readyState == 4){
            if(http.responseText.indexOf(':') != -1) {
                var data = http.responseText.split(':')
                alert(data)
            }
        }
    };
    http.send('name=' + name + '&message=' + message);
}

}

Currently, I am using static text for the name and message instead of user entered fields, but when I run it, I only get an empty alert. If the readyState is set to 4, does that indicate a successful AJAX call? The server/shout.php file was provided to me, I don't have a strong understanding of PHP, but I can provide a snippet if necessary.

Answer №1

This particular line is critical: http.responseText.indexOf(':' != -1)

When evaluating ( ":" != -1 ), it results in true, hence indexOf is searching for true within the responseText

To address this issue, consider using: http.responseText.indexOf(':') !== -1

Answer №2

When the readyState value is equal to 4, it indicates that the request has been completed. To verify if it was successful, you should check if the http.status value equals 200.


if (http.readyState == 4) {
 if(http.status == 200) {
   alert(http.responseText);
 }
}

By the way, I wanted to add this as a comment but unfortunately, my rating doesn't permit me to do so.

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

Complete the dynamic form submission in a non-blocking manner

My goal is to dynamically add text fields with the click of a button I also aim to extract data from these text fields and insert it into the database Currently, all functions work smoothly, I just need this additional feature. Per ...

Issue with Bcrypt comparison resulting in constant false output

Attempting to implement password verification using bcryptjs, const bcrypt = require('bcryptjs'); login(post){ this.uid = post.uid; this.pin = post.pin; this.getUser(this.uid); if(this.checkUser != undefined ...

Organizer featuring Outlook-inspired capabilities

My goal is to develop a system for efficiently managing appointments. Upon opening the application, I want to display a calendar control that will retrieve an individual's schedule from a SQL server database. For example, if the user has meetings sch ...

Can a websocket be used to communicate with a server that is not the same as the one hosting the html5 website?

My goal is to establish communication between a hardware device and an HTML5 website. It seems like the best way to do this would be through WebSockets or possibly WebRTC over a WiFi network. Is that correct? I haven't come across any solutions invol ...

Exploring the Potential of Using Client-Side Includes with JavaScript/jQuery

Are there techniques for organizing javascript/jquery code in a manner similar to server-side include() script concatenation in PHP? I have an extensive javascript engine embedded with dynamic code sourced from my database. I am looking to segregate the ...

Having difficulty accessing certain code in TypeScript TS

Struggling with a TypeScript if else code that is causing errors when trying to access it. The specific error message being displayed is: "Cannot read properties of undefined (reading 'setNewsProvider')" Code Snippet if (this.newsShow != ...

Is it necessary for React to have NodeJS in the frontend environment?

As a newcomer to the world of React, I am eager to create a simple hello world example from scratch. While most tutorials provide a standard setup involving nodeJS and npm, I decided to take a different approach: app.js var reactElement = React.createEle ...

Using Node.js and Hapi.js alongside Angular.js for web development

Could someone please help me understand how to integrate nodejs (hapi server) with AngularJs? I initially thought that I could intercept all requests made to my Hapi server and handle them using angularjs routes / REST, but it seems like I'm encounter ...

Display an error alert when a specific condition occurs

My page has a code snippet that triggers an error alert when loaded: protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Request.QueryString["message"] == "noemployees") ...

Is Cloud Spanner effectively handling session management?

I've spent some time researching this issue but unfortunately haven't been able to find a satisfactory answer. The Google Cloud Spanner client libraries automatically handle sessions, with a limit of 10,000 sessions per node. So far, so good. M ...

Incorporating native JavaScript classes within an Angular application

I have created a custom JavaScript class: var ExampleClass = new function(elements) { this.elements = elements; this.someFunction() { // logic involving this.elements }; }; How can I incorporate it into an A ...

Unit testing in JavaScript has its limitations, one of which is the inability to verify if a

Currently, I am working with an Angular application that includes a simple directive called animate. My goal is to use Jasmine to verify if the slideDown method is being called. Below is the current setup of my directive: animateDirective var animate = f ...

Retrieve the content of the nearest 'td' element using the '.closest()' method, then locate the desired

I am struggling to assign the value from a <td> to a variable. My approach involves utilizing the closest() and find() methods in jQuery to locate the desired <td>. Interestingly, when I use alert on the <td>, it displays the correct val ...

Ensuring Consistent Headings While Scrolling

Imagine having headings structured like this: <h1 class="fixontop">heading 1</h1> content goes here. . . . long paragraph. <h1 class="fixontop">heading 2</h1> 2nd content goes here. . . . long paragraph. <h1 class="fixontop"> ...

Using PHP, extract information from a database with a MySQL query and present it visually as a stacked bar graph

Hey everyone, I tried searching on Google for an answer to my question but I only found information on how to display a plain bar graph, not a stacked one. My issue is that I need to show a stacked bar graph based on the count of different categories, s ...

Adding the AJAX response to the specified element's ID

I'm having trouble inserting radio buttons into a <div> on my page using an AJAX response. The code I have looks like this: // AJAX form for updating tests after category selection $('#categories').change(function(){ category_id ...

Creating a transparent background for a Canvas animation with three.js and dat.gui

I'm struggling to set up a background animation on this canvas using three.js. However, the background renders as black instead of transparent. I attempted to adjust it with CSS by adding background-color:transparent;, but to no avail. I've searc ...

Display popup depending on the post's identification number

Currently, I'm in the process of integrating Sanity into my blog. Using the json object returned from a query with useState, I managed to display my posts successfully. However, I am now faced with the challenge of populating a React-Modal with the ap ...

Can the issue of mangling be avoided during .NET minification?

Currently, I am utilizing the .NET Bundling and Minification feature to bundle and minify the files for my application. While this method works well, I am interested in exploring alternative solutions due to its complexity. Specifically, I am attempting t ...

After the successful creation of a new user account using createUserWithEmailAndPassword, the collection

I'm having an issue with my signup user page where only half of it is functioning correctly. What works: The createUserWithEmailAndPassword call via firebase firestore runs successfully. What doesn't work: In the promise for that call, I'm ...