When the user presses the enter key to submit data, the Ajax page reloads

I am facing an issue with a simple form for sending messages from one person to another using AJAX method POST to prevent page reload. The problem arises when the user hits [ENTER] in the field, causing the page to reload instead of the AJAX working as intended. I need a solution where pressing ENTER triggers the AJAX function smoothly.

Here is my code:

function sendMessage()
    {
        var sender = document.getElementById('sender').value;
        var recipient = document.getElementById('recipient').value;
        var message = document.getElementById("message").value;
        if(message.length == 0 || message.length  > 128)
        {
            return;
        }
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function()
        {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                document.getElementById("messages").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST", "output.php", true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send("sender=" + sender + "&recipient=" + recipient + "&message=" + message);
    }

-HTML:

<form action="" >
    <input type="hidden" id="sender" name="sender" value="Erick">
    <input type="hidden" id="recipient" name="recipient" value="Fernanda">
    <input type="text" id="message" /> <input type="button" value="Send" onclick="sendMessage();">
</form>
<div id="messages"></div>

Answer №1

The issue lies in the fact that the Ajax function is only applied to the onclick handler of the button. To resolve this, you should also include it in the onsubmit action of the form.

<form action=""  onsubmit="enviarMensagem(); return false;">
<input type="hidden" id="remetente" name="remetente" value="Erick">
<input type="hidden" id="destinatario" name="destinatario" value="Fernanda">
<input type="text" id="mensagem" /> <input type="button" value="Enviar" >

You can trigger form submission by clicking the submit button or by pressing Enter after typing. By adding the listener to the onsubmit action, both scenarios are covered.

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

Tips for sorting through a multi-dimensional array of objects

I'm looking to filter this array based on the attributevalue. For example, if I search for blue color, I want all shirts in blue color to be displayed. And then if I further search for cotton fabric in blue color, I want all cotton products with blue ...

Display and conceal frequently asked questions using JQuery

I'm currently facing an issue with using JQuery to toggle between showing and hiding content when a user clicks on a specific class element. Here is my HTML code: <div class="faqSectionFirst"> Question? <p class="faqTextFirst" style=' ...

Creating a Map Using HTML and JavaScript

My current project involves creating a simple map that can be moved with mouse drag functionality, featuring images such as islands. I have successfully retrieved the mouse position by declaring variables posX and e.clientX, as well as for e.clientY. Howe ...

What causes the Element to be null in Vue.js?

Could someone please clarify why the console.log output is showing as null, and provide guidance on how to resolve this issue? <template v-for="day in getMonthLength()"> <td> <input :id="day" type=number :value=&qu ...

Using AJAX in jQuery to toggle the visibility of rows in a table with the each

Currently, I am working on an MVC 5 application where I am attempting to utilize a script to toggle the visibility of buttons in each row based on data retrieved from a database using Ajax. function setButtons() { $('#MyList > tbody > ...

The type 'string | undefined' cannot be assigned to type 'string'

I am facing a challenge in comparing two arrays, where one array is sourced from a third-party AWS service and its existence cannot be guaranteed. Despite my efforts to handle potential errors by incorporating return statements in my function calls, I con ...

The pageSize in React's Material Table does not reflect dynamic updates

Currently, I am attempting to implement pagination for material table data using TablePagination. One issue I am facing is that the pageSize property, initially defined as a state variable, does not update when the selected pageSizeOptions change. Despite ...

The error message "TypeError: res.json is not a function in express.router" indicates that

I encountered the following error message and I'm not sure how to resolve it: TypeError: res.json is not a function I have reviewed the express documentation but couldn't find any syntax errors or issues. Here is my code: index.js import expr ...

employ identical components in v-if and v-else

Currently, I am in the process of designing a login/register page using Vue. The layout includes separate tabs for both login and registration purposes. Here is a snippet of my template code: <transition v-bind:name="TabEffect"> <div ...

It is not possible to trigger an input click programmatically on iOS versions older than 12

Encountering a challenge in triggering the opening of a file dialogue on older iOS devices, particularly those running iOS 12. The approach involves utilizing the React-Dropzone package to establish a dropzone for files with an added functionality to tap ...

Angularfire allows for easy and efficient updating of fields

Currently, I am working on creating a basic lateness tracker using AngularFire. So far, I have successfully added staff members to the miniApp and set the initial late minutes to a value of 0. My challenge lies in updating these values. Ideally, when a us ...

Using Firebase with Angular 4 to fetch data from the database and show it in the browser

Currently diving into Angular 4 and utilizing Firebase database, but feeling a bit lost on how to showcase objects on my application's browser. I'm looking to extract user data and present it beautifully for the end-user. import { Component, OnI ...

Retrieve data from a text file using ajax and then return the string to an HTML document

Just starting out with ajax, I have a text file containing number values For example, in ids.txt, 12345 maps to 54321 12345,54321 23456,65432 34567,76543 45678,87654 56789,98765 Here is the Html code snippet I am using <html><body> < ...

Guide on how to retrieve Twitter Username and Profile Photo through the Twit NPM Package

Utilizing the twit npm package to retrieve the Authenticated Twitter Username and Profile Image, here is the code I am using: const Twit = require('twit'); let T = new Twit({ consumer_key: 'xxx', ...

Has Jade stopped allowing inline variables unless enclosed by JavaScript markers?

Back when I was using Jade version 0.34.1 (prior to the release of version 1.0.0), I had the ability to incorporate inline variables like this: test = 'fun' p #{test} This would typically result in: <p>fun</p> However, the output ...

Disregard Cloudflare's Automatic RocketLoader feature for certain JavaScript scripts

After extensive research and failed attempts, I am seeking help to disable Cloudflare Rocketloader for a specific JavaScript file on my WordPress website. Specifically, I need to exclude the Automatic Rocket Loader for a particular .js file. I attempted t ...

Launching a Node.js Express application on Heroku

I'm facing an issue while trying to deploy my app on Heroku, as I keep encountering the following error: 2022-08-11T12:49:12.131468+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306 2022-08-11T12:49:12.131469+00:00 app[web.1]: at TCPConnect ...

Tips for linking two project routes in NodeJS and incorporating React (I am interested in invoking React within the NodeJS project)

I'm in the process of linking two projects, one using reactJS and the other NodeJS. Currently, NodeJS is running smoothly on localhost:3000. Next, I want to call a React application which redirects to port localhost:3001. How can I seamlessly connect ...

How to Delete an Added Image from a Dialog Title in jQuery

I've tried multiple solutions from various sources, but I'm still struggling to remove an image from a dialog. Whenever I attempt to do so, I end up with multiple images instead of just one. It's important to note that I only want the image ...

Using an Angular route to trigger the resolution of data from a service

I'm having trouble figuring out how to implement Angular route resolve. The documentation does not provide much help for more complex aspects of the javascript framework like this. Here is the service I am using: app.service("AuthService", ["$http", ...