the onreadystatechange function is not being triggered

When trying to call the show_Message function, I expected an alert box to appear. However, the onreadystatechange is not working as expected. All other alert boxes are functioning properly.

Below is my JavaScript function:

 function send_Message(){
  var msg=document.getElementById("msg").value;
if(msg.length===0||msg===""){
    alert("please enter some message");
    return;
}

var sender=document.getElementById("username").value;
var sendto=document.getElementById("chat_id").options[document.getElementById("chat_id").selectedIndex].value;
alert(sender+" "+sendto);
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
    alert('hello');
    if(xhttp.readyState==4 && xhttp.status==200){
        document.getElementById("chat_logs").innerHTML=xhttp.responseText;
    }
    xhttp.open('GET','send_messages.php?sender='+sender+'&sendto='+sendto+'&message='+msg,true);
    xhttp.send(null);
}
 }

Answer №1

xhttp.open('GET','send_messages.php?sender='+sender+'sendto='+sendto+'message='+msg,true);
 xhttp.send(null);

Make sure to place it outside of the onreadystatechange function.

Here is the updated version:

function sendMessage(){
  var message=document.getElementById("message").value;
if(message.length===0||message===""){
    alert("Please enter a message before sending.");
    return;
}

var sender=document.getElementById("username").value;
var recipient=document.getElementById("recipient_id").options[document.getElementById("recipient_id").selectedIndex].value;
alert(sender+" "+recipient);
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
    alert('Request completed');
    if(xhttp.readyState==4 && xhttp.status==200){
        document.getElementById("chat_history").innerHTML=xhttp.responseText;
    }
}
xhttp.open('GET','send_message.php?sender='+sender+'&recipient='+recipient+'&message='+message,true);
    xhttp.send(null);
 }

Answer №2

You made an error in closing the code block. xhttp.onreadystatechange=function(){

The above function should be closed after the if statement.

See the corrected code below:

function send_Message(){
  var msg=document.getElementById("msg").value;
if(msg.length===0||msg===""){
    alert("please enter some message");
    return;
}

var sender=document.getElementById("username").value;
var sendto=document.getElementById("chat_id").options[document.getElementById("chat_id").selectedIndex].value;
alert(sender+" "+sendto);
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
    alert('hello');
    if(xhttp.readyState==4 && xhttp.status==200){
        document.getElementById("chat_logs").innerHTML=xhttp.responseText;
    }
}; 
    xhttp.open('GET','send_messages.php?sender='+sender+'sendto='+sendto+'message='+msg,true);
    xhttp.send(null);

 }

Answer №3

Perhaps the issue lies in having your open and send functions nested within the onstatechange function.

function sendMessage(){
  var message = document.getElementById("message").value;
  if (message.length === 0 || message === "") {
    alert("Please enter a message");
    return;
  }

  var sender = document.getElementById("sender").value;
  var recipient = document.getElementById("recipient_id").options[document.getElementById("recipient_id").selectedIndex].value;
  
  alert(sender + " " + recipient);

  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    alert('Hello');
    if (request.readyState == 4 && request.status == 200) {
      document.getElementById("chat_history").innerHTML = request.responseText;
    }
  }

  request.open('GET', 'send_message.php?sender=' + sender + '&recipient=' + recipient + '&message=' + message, true);
  request.send(null);
}

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

In Google Chrome, the edges of hexagons appear jagged and not smooth

I have encountered an issue in Chrome where I created a hexagon group using HTML and CSS. While it displays fine in Firefox, the edges of the hexagons appear distorted in Chrome. Here are my code snippets: HTML <div class="col-sm-12 margin-left-100" i ...

Utilize pg-promise for inserting data with customized formatting using the placeholders :name and :

After reviewing the pg-promise documentation, I came across this code snippet: const obj = { one: 1, two: 2 }; db.query('INSERT INTO table(${this:name}) VALUES(${this:csv})', obj); //=> INSERT INTO table("one"," ...

Issues with sending parameters in JQuery Ajax POST request

Currently, I am delving into Ajax and encountering some issues with sending requests from the client side. I have a jsp file located at "/web" on my local server to manage requests. Though unsure if this is the best approach or if it should be handled by ...

If the visitor navigated from a different page within the site, then take one course of action; otherwise

How can I achieve the following scenario: There are two pages on a website; Parent page and Inside page. If a user navigates directly to the Inside page by entering the URL or clicking a link from a page other than the Parent page, display "foo". However, ...

What is the best way to target an HTML attribute using jQuery?

I have customized a Textbox by adding a special attribute: <asp.TextBox MyCustomAttribute="SomeValue"><asp.TextBox> Now, I want to retrieve this value from within an AJAX success function. Please note that I have excluded irrelevant attribut ...

Secure your messages with PHP encryption and decrypt them with JavaScript

I am looking for a way to encrypt a message using PHP and then decrypt it using JavaScript on the client side. I tried using Blowfish with mcrypt, but encountered an issue where PHP was outputting non-alphanumeric characters while JavaScript was only displ ...

JavaScript - Utilizing an image file in relation to a URL pathway

Is there a way to reference an image URL using a relative path in a JavaScript file similar to CSS files? To test this, I created two divs and displayed a gif in the background using CSS in one and using JavaScript in the other: -My file directory struct ...

Sending the slider value from a website to a program when the slider is adjusted

I have been experimenting with programming an ESP32 to regulate the LED brightness using a slider. I've pieced together some information from tutorials found on and Currently, I've achieved the ESP32 connecting to my network, displaying the sli ...

Error: Attempting to assign a value to the non-existent property 'user' <br>    at [file path] on sqlite3

I encounter an unspecified error when I try to establish a session for the user after validating their credentials during login. I'm utilizing express-session to create the session, but it's not directly imported into the file as instructed by my ...

Tips for avoiding redundant AJAX requests

Currently, I am working with JavaScript and not jQuery. Imagine a scenario where I have 3 users in my database [Kim, Ted, Box] and 3 buttons structured as follows: <button class="user">Kim</button> <button class="user">Ted</button> ...

The error message "node Unable to iterate over property 'forEach' because it is undefined" appeared

I am facing an error and unable to find the solution. I believe my code is correct. It is related to a video lesson where I attempt to display popular photos from Instagram using the Instagram API. However, when I try to execute it, I encounter this issue. ...

The accordion feature fails to function properly when incorporated into an ajax response

When I click a button, an Ajax response is loaded. The response is successfully appended where it should be, but the issue arises with the accordion not working for the response part. Below is the structure of my response: <div class="articles-content ...

Using jQuery sortable with the overflow property set to hidden to sort items between two lists

I need help with a jQuery sortable feature where I have two lists and can move items between them: $( '#productsList, #orderList' ) .sortable({connectWith: '.containerDiv'}) .disableSelection(); My issue arises when I try to implement ...

Guide to refreshing extensive dataset using MySQL migration scripts

We are in the process of developing a Nodejs application for a client who has requested that we use migration scripts to streamline updating the production database. As someone new to MySQL, I am struggling with how to update table contents using only MySQ ...

Apply Jquery to add emphasis to every item on the list

Can someone help me with this assignment? I need to create a jQuery function that italicizes all list elements on the page when triggered by the client. Here is my current approach: $(document).ready(function() { $("li").click(function() { ...

The 'fetch' operation could not be completed on the current window due to a TypeError

The error message I am receiving is: TypeError: Failed to execute 'fetch' on 'Window' : The provided value is not of type '(sequence<sequence> or record<ByteString, ByteString>)'. My current challenge involves fetc ...

Phase 2 "Loading" visual backdrop

I'm attempting to include a loading animation GIF in my Cycle 2 plugin. Is there a way to ensure that the GIF loads before the images? Right now, I have set my loading.gif as a background image. The issue is that the loading.gif isn't displaying ...

Tips for sending an array with all its elements from jQuery to PHP

Currently, I am attempting to transfer an array from jQuery to PHP. <input type="checkbox" id="name1" name="name[]" value="name1"> Name1 <input type="checkbox" id="name2" name="name[]" value="name2"> Name2 <input type="checkbox" id="name3" ...

Looking to retrieve the full browser URL in Next.js using getServerSideProps? Here's how to do

In my current environment, I am at http://localhost:3000/, but once in production, I will be at a different URL like http://example.com/. How can I retrieve the full browser URL within getServerSideProps? I need to fetch either http://localhost:3000/ or ...

Enhancing the security of various components by utilizing secure HTTP-only cookies

Throughout my previous projects involving authentication, I have frequently utilized localstorage or sessionstorage to store the JWT. When attempting to switch to httpOnly secure cookies, I encountered a challenge in separating the header component from th ...