The Clash of Form Action and JavaScript

Can someone help me with this issue?

I have a form and a script to trigger an alert message. The code I'm using is working well:


    <input id="autocomplete" class="input_message" type="text" name="message" autocomplete="off" placeholder="...type your message" ><br/>                              
    <input id="input_send" class="input_send" type="submit" name="send" value="SEND">

However, when I add a form method, the alert in my script stops working.


    <form enctype="multipart/form-data" method="post">
        <input id="autocomplete" class="input_message" type="text" name="message" autocomplete="off" placeholder="...type your message" ><br/>                              
        <input id="input_send" class="input_send" type="submit" name="send" value="SEND">
    </form> 

Below is the script I am using:


<div id="alertbox">
<script>
$(document).ready(function(){
    $('#input_send').click(function(){
        var post = $('#autocomplete').val();
        if(post==""){   
            alert('Enter Message Please');  
        }else{
            $('#loader').fadeIn(400).html('<img src="./loader.gif" align="absmiddle">&nbsp;<span class="loading">sending</span>');
            var datasend = "alert";
            $.ajax({
                type:'post',
                url:'./includes/alerts.php',
                data:datasend,
                cache:false,
                success:function(msg__){    
                    $('#autocomplete').val('');
                    $('#loader').hide();
                    $('#alertbox').fadeIn('slow').prepend(msg__);
                    $('#alerts').delay(5000).fadeOut('slow');   
                }
            });
        }
    })          
});
</script>
</div>

Thank you for any assistance provided.

Answer №1

When the submit button is clicked, the form is sent to the server and the page reloads.

To prevent the form from being submitted to the server, you can include "return false;" after the ajax function.

Answer №2

looking for a solution to stop the form from submitting

$(document).ready(function(){
    $('#input_send').click(function(e){
       e.preventDefault();//using this line to prevent form submission
        var post = $('#autocomplete').val();
        if(post==""){   
            alert('Please Enter a Message');  
        }else{
        $('#loader').fadeIn(400).html('<img src="./loader.gif" align="absmiddle">&nbsp;<span class="loading">sending</span>');
        var datasend = "alert";
        $.ajax({
            type:'post',
            url:'./includes/alerts.php',
            data:datasend,
            cache:false,
            success:function(msg__){    
                $('#autocomplete').val('');
                $('#loader').hide();
                $('#alertbox').fadeIn('slow').prepend(msg__);
                $('#alerts').delay(5000).fadeOut('slow');   
            }
        });
        }
    })          
});

Alternatively, you can change the #input_send type from submit to button to avoid triggering form submission

<input id="input_send" class="input_send" type="button" name="send" value="SEND">

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

Trying out the demonstration of the angular calendar in action

I am currently attempting to run the official example of the angular-calendar component found at http://angular-ui.github.io/ui-calendar/ Unfortunately, I am encountering an error that states: TypeError: undefined is not a function - it seems that the fun ...

Exploring the World of Subclassing Arrays in JavaScript: Uncovering the TypeError of Array.prototype.toString's

Can JavaScript Arrays be subclassed and inherited from? I am interested in creating my own custom Array object that not only has all the features of a regular Array but also contains additional properties. My intention is to use myobj instanceof CustomArr ...

Browse through content without displaying the page title on the navigation bar and without the use of frames

When I sign into certain websites, I have noticed that the address displayed is often something like this: https://examplesite.com/access Even though all the links on the landing page are clickable and functional, their corresponding addresses never show ...

Binding data to custom components in Angular allows for a more flexible

In my current scenario, I am looking to pass a portion of a complex object to an Angular component. <app-component [set]="data.set"></app-component> I want the 'data.set' object in the parent class to always mirror the 'set&apo ...

Dealing with lag in Kendo Grid (Utilizing Kendo Grid, Angular JS, and Web API)

Query : I have integrated a Kendo Grid into my Angular JS HTML page. The data for the Kendo Grid is fetched from a remote service Web API. While paging through the Kendo Grid, it attempts to download a whopping 38 MB of content for every 10 records, taki ...

Unable to send event from JavaScript to Component in Ionic

My goal is to notify a component that a script file has finished loading. My approach involves using the onload event of an element to dispatch an event. A service will then register an event listener for this event, waiting for clients to subscribe to an ...

Is Vercel deploying an incorrect version?

After working on a project for a potential employer and fixing all errors, I deployed it using Vercel. However, upon deployment, the version that was sent to me was displayed instead of the completed one I see when running npm start locally. I would great ...

Tips for customizing the appearance of the day button in a React Material-UI date picker

In my React project, I am using material-ui date picker and I am looking for a way to customize the styling of the day buttons. Specifically, I want to change the text color of the available days. By default, as seen in the screenshot, the text color is bl ...

Placing the template code underneath the existing code within the Handlebars layout.hbs file

I'm currently working on a project using Express Handlebars. I have a template called foo.hbs that contains some JavaScript code which I need to insert below the script tags in the layout.hbs file: <!DOCTYPE html> <html> <head> ...

The PHP file on the server is missing the mandatory "event" parameter for the EventSource

Explaining this issue was a bit of a challenge. I've set up a Javascript EventSource object with some customized event handlers like so: var source = new EventSource('updates.php'); source.addEventListener('add', addHandler, fals ...

Customize the popover in React Material-UI to your liking

I am currently utilizing a Select component within my application. https://i.stack.imgur.com/hjXlY.png I have created a custom modal component that I wish to display instead of the default list items when the select is clicked. Is there a method to overr ...

Managing two variables in C# Controller and View

I am facing an issue with the two variables in my controller class. The first variable, currentUserId, is supposed to store the user currently logged into the website. The second variable, currentRoomId, should track the chat room the user is in. The probl ...

Finding a potential data breach in Node.js, MongoDB, and Chrome, exposed passwords are

My web app is built using nodejs with mongodb as the database backend, and I am encountering an issue with Chrome browser flagging my login process via passport.js as an exposed password. How can I prevent this warning? Should I implement something like Bc ...

Ldap.js: exploring nested searches

My current task involves using ldapjs to conduct a search where the filter is dependent on the outcome of a preceding search. ldapClient.search(base1, opts1, (err1, res1) => { res1.on("searchEntry", entry => { const myObj = { attr1: entr ...

The eternal Three.js animation that loops endlessly whenever it is clicked

The Objective My aim is to create a straightforward camera zoom in animation that increases the zoom level by a specific amount each time the button is clicked. The Current Status I have successfully implemented the animation using Three.js and linked i ...

Using an if statement within a map function in a React component

I am facing a challenge with using an if statement inside a map function without changing the return value. Here is my code snippet: this.example = this.state.data.map((item) => { return( <div> {if(1 + 1 == 2){ dat ...

I am encountering an issue where body-parser is not functioning properly with typescript. Whenever I make a request, the request.body is returning as undefined

Below is the code snippet for my Express application using TypeScript version 3.7.4: import bodyParser from "body-parser"; import config from "config"; import cookieParser from "cookie-parser"; import express from "express"; import mongoose from "mongoose ...

Using AngularJS and Web API to generate a dropdown menu from a one-to-many relationship

I have two tables in my database: People and Payband. Let me simplify the relationship below: dbo.People PersonId : int (Primary Key) FirstName : string MiddleInitial: string LastName : string DateOfBirth: datetime PaybandId : int (Foreign Key) dbo.Payb ...

VueJS failing to pass parent data to child component

I'm fairly new to Vue Framework and I'm trying to figure out how to update a child component based on changes in the parent component's attributes. In the code snippet below, I've created a component that displays a greeting message bas ...

Using json_encode with chart.js will not produce the desired result

I am attempting to utilize chart.js (newest version) to generate a pie chart. I have constructed an array that I intend to use as the data input for the chart. This is the PHP code snippet: <?php if($os != null) { $tiposOs = array('Orçamento ...