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

Can a new frame be created below an already existing frame in HTML?

My main.html file looks like this: ----- main.html---------------- <title>UniqueTrail</title> <script src="main.js"></script> <frameset rows='200,200'> <frame id='one' src="f ...

Merge the chosen values from the drop-down menu into one string

Any suggestions would be greatly appreciated! I am currently developing an application using ASP.NET web forms that consists of a dropdown list and two list boxes. I want these elements to be cloned whenever a specific button is clicked. However, my issue ...

Ways to minimize an array of objects by shared key values?

Suppose I have an array of objects structured like this: var jsonData = [ {"DS01":123,"DS02":88888,"DS03":1,"DS04":2,"DS05":3,"DS06":666}, {"DS01":123,"DS02":88888,"DS03":2,"DS04":3,"DS05":4,"DS06":666}, {"DS01":124,"DS02":99999,"DS03":3,"DS04" ...

Can you provide guidance on how to divide a series of dates and times into an array based

Given a startDate and an endDate, I am looking to split them into an array of time slots indicated by the duration provided. This is not a numerical pagination, but rather dividing a time range. In my TypeScript code: startDate: Date; endDate: Date; time ...

Implementing pagination and filtering in a single MERN controller

Is it possible to implement pagination and filtering in the same controller? Filter service:- const filterPosts = async (filterData, token) => { const config = { headers: { Authorization: `Bearer ${token}`, }, data: { ...

A guide on extracting content from a PDF file with JavaScript

Hey there, I'm experimenting with various methods to extract content from a PDF file but so far nothing seems to be working for me. Even when I try using pdf.js, it shows an error and I can't figure out why. This is the approach I've been tr ...

The function tokenNotExpired encounters an error when attempting to access the localStorage, as it

I am looking to incorporate the angular2-jwt library into my project: https://github.com/auth0/angular2-jwt However, I encountered an exception when attempting to call the tokenNotExpired function: Exception: Call to Node module failed with error: Refe ...

Add various inputs to a table using JavaScript

I came across a situation where I needed to append lines into a table in a specific way. However, I encountered an issue with JavaScript not accepting any input type='text' for an unknown reason. When I used a normal text variable, it worked fine ...

Having trouble retrieving data from the table with AJAX and CodeIgniter

I am currently developing a comprehensive HRM+CRM system (Human Resource Management and Customer Relation Management). I have encountered an issue while trying to generate an invoice for each customer. I am struggling to resolve this problem and would appr ...

Using an onclick function to increment and decrement values

Can anyone help me figure out how to reverse a function onclick? Here is the function: var theTotal = 0; $('button').click(function(){ theTotal = Number(theTotal) + Number($(this).val()); $('.total').text(theTotal); }); ...

Is it possible to modify the CSS styling of the file_field?

I am looking to customize the appearance of the file_field in CSS. Rather than displaying the default browse button, I would like to use a simpler upload button for file submission. What steps can I take to modify the CSS of the file_field and replace it ...

Tips for retrieving the content of an input field using Angular

function HomeController($scope, navbarService) { var vm = this; $scope.showHeader = true; $scope.userNameNav =''; $scope.$on('toggleHeader', function(event, data) { $scope.showHeader = data; }); $s ...

Implementing logic with multiple columns in JavaScript

Looking for a way to display an array of data in multiple columns using Java Script, like this: 1 2 3 4 5 6 7 8 9 instead of 1 4 7 2 5 8 3 6 9 Any suggestions would be greatly appreciated. Thank you. ...

What is the process for incorporating JavaScript files into an Angular project?

I have a template that works perfectly fine on Visual Studio. However, when I try to use it on my Angular project, I encounter an issue with the JavaScript code. I have filled the app.component.html file with the corresponding HTML code and imported the ...

What is the best way to incorporate server-side rendered content from a CMS to hydrate Vue.js?

Consider this scenario: content is managed through a traditional CMS such as Joomla or Drupal content is provided by the CMS as fully rendered HTML and CSS In the Frontend React.js should be utilized for all UI interactions. Despite going over most of R ...

Assign a class to the initial element of the Vuetify v-select module

Hey there! Currently, I'm utilizing the v-select component from Vuetify. I'm looking to customize the appearance of the first item in the v-select component by adding a specific class. For example, I want the text of the first entry "Item A" to b ...

What is the best way to showcase content using Chakra-ui SideBar in a React Application?

After exporting the SideBar, I imported it into my App.jsx SideBar.jsx 'use client' import { IconButton, Avatar, Box, CloseButton, Flex, HStack, VStack, Icon, useColorModeValue, Text, Drawer, Draw ...

Tips for verifying the request body when it consists of a lone JSON array

I am in the process of verifying the content of the request by utilizing the express-validator. The entire body is a singular array, which means there isn't a specific field name. Currently, I am making use of the new version of express-validator alo ...

Choose the camera when utilizing the navigate.getUserMedia() function

I am currently utilizing the navigate.getUserMedia() method to record video on my mobile device and perform additional processing on it. However, at the moment, it is only capturing video using the front camera. How can I make it switch to the rear facing ...

Just starting out with React and encountering the error: Invalid element type, a string was expected

I seem to be going in circles with the following issue as I try to load the basics of a React app into the browser. An error message stating 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite c ...