Insert new text and apply class with fadeIn animation

My form is equipped with AJAX functionality. I aim for it to smoothly 'fade in' when the submission is either successful or unsuccessful. In case of success, the script appends the 'has-success' class to the div and alters the content. I want to achieve a 'fade in' effect when there is a change in content and class. I attempted to use 'fadeIn(500)' after the 'append' function, but it didn't yield the desired outcome. You can view a live demonstration here.

<div class="container">
<form class="ajaxForm" action="https://formcarry.com/s/YN2IlAj4rfL" method="POST" accept-charset="UTF-8">
<div class="form-group">
<input type="email" class="form-control" id="email" aria-describedby="emailHelp" name="Correo" placeholder="Correo electrónico"><!-- use this to reply visitors and prevent spam via akismet -->
</div>
<div class="form-group"><input type="text" class="form-control" id="nombre" name="Nombre" placeholder="Nombre"></div>
<div class="form-group"><textarea rows="4" class="form-control" id="textarea" name="Mensaje" placeholder="Cuéntanos"></textarea></div>
<input type="hidden" name="_gotcha"><!-- use this to prevent spam -->
<div class="form-group"><input type="submit" class="btn-contacto float-right"><div class="spinner-border" role="status">
  <span class="sr-only">Cargando...</span>
</div></div></div></form></div>

JQuery:

$(function(){
    $(".ajaxForm").submit(function(e){
        $('.spinner-border').css("display", "block");
        e.preventDefault();
        var href = $(this).attr("action");
        $.ajax({
            type: "POST",
            dataType: "json",
            url: href,
            data: $(this).serialize(),
            success: function(response){
                if(response.status == "success"){
        $(".ajaxForm").html(response).addClass("has-success");
        $(".ajaxForm").append( "<p>¡Gracias! Contactaremos contigo lo antes posible.</p>" ).fadeIn(500);

                }else{
                    alert("An error occurred.");
                }
            }
        });
    });
});

Answer №1

Before you proceed, make sure to implement this solution by sending a response back from your server.

if (isset($_POST['Correo'])) {
// Add your server-side logic here to send a success or failure response
echo json_encode(['status' => 'success']);
die;
}

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<form class="ajaxForm" action="https://formcarry.com/s/YN2IlAj4rfL" method="POST" accept-charset="UTF-8">
<div class="form-group">
<input type="email" class="form-control" id="email" aria-describedby="emailHelp" name="Correo" placeholder="Correo electrónico">
</div>
<div class="form-group"><input type="text" class="form-control" id="nombre" name="Nombre" placeholder="Nombre"></div>
<div class="form-group"><textarea rows="4" class="form-control" id="textarea" name="Mensaje" placeholder="Cuéntanos"></textarea></div>
<input type="hidden" name="_gotcha">
<div class="form-group"><input type="submit" class="btn-contacto float-right"><div class="spinner-border" role="status">
<span class="sr-only">Cargando...</span>
</div></div></div></form></div>

Here is the JavaScript code that appends a message after the form:

$(function(){
$(".ajaxForm").submit(function(e){
$('.spinner-border').css("display", "block");
$(document).find('#msg').remove();
e.preventDefault();
var href = $(this).attr("action");
$.ajax({
type: "POST",
dataType: "json",
url: href,
data: $(this).serialize(),
success: function(response){
$('.spinner-border').css("display", "hide");
$(".ajaxForm").addClass("has-success");
$(".ajaxForm").after( "<p id='msg'>¡Gracias! Contactaremos contigo lo antes posible.</p>" ).fadeIn(500);
}else{
$('.spinner-border').css("display", "hide");
alert("An error occurred.");
}
}
});
});

Try implementing this solution and let me know if it worked for you or not. Hopefully, this resolves your issue.

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

Preventing default form submission in jQuery: How to cancel it when a certain condition is met

I have a contact form where I validate the input values upon clicking on the submit button. If there is at least one empty input, I trigger an alert and prevent the form submission by using preventDefault. However, if all inputs are filled and submitted, t ...

Utilize Ajax to transfer an image from an input form to a PHP script

I am currently working on a basic HTML page that includes an image upload form. Here is the code for the form: <input type='file' id='image_uploaded' accept='image'/> <input type='submit' id="upload_image"/ ...

Sharing JSON data across different domains to ASP.NET using jQuery

I have encountered a complex issue. Currently, I am involved in a project that requires generating receipt printouts when users check out on our website at a kiosk. Due to driver and formatting challenges, I am utilizing COM automation with Word for handl ...

Designing a visually appealing widget in a jQuery UI theme by floating two elements neatly inside

My code looks like this: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Testing PasteHTML.co ...

Update the input value following a successful action

How can I update the value of an input field after a successful ajax call? I have tried the following approach but it doesn't seem to be working. The result from the alert is 80000 Here is the HTML input code: <input class="form-control" type=" ...

Tips for choosing a single row in a table using a checkbox

I need help with a table that has multiple rows and four columns. One column is for checkboxes, while the other three are select boxes set to read-only. I want users to be able to edit only one row at a time by checking the checkbox in the first column. If ...

The media queries seem to be ineffective

Looking for some assistance here. I'm having trouble with my media queries not working as expected. Specifically, I'm attempting to adjust the padding on the navigation menu of my website. Despite setting up a media query to change the padding fo ...

Having trouble saving data in Django using ajax(fetch) - encountered an error

Trying to save data using ajax in a model that references other models Example: class Friend(models.Model): name = ... class Main(models.Model): name = .... friend = models.ForeignKey(Friend, on_delete=models.CASCADE) Data is fetched using a ...

React-Native-Web generates default classes for inline styles and erroneously applies them in a jumbled sequence

Currently working on a project involving react native web and NextJS. I have encountered an issue with inline styles in React that seems to be caused by RN-Web. It appears that there is a mechanism within the framework that automatically generates classes ...

React random marker position shifts when the screen size is adjusted

After displaying an image and adding a marker to it, I noticed that the marker's position changes when the screen size is adjusted. Why does this happen? And more importantly, how can I ensure that the marker stays in the same position relative to the ...

Display two columns side by side using Bootstrap on all screen sizes

I'm attempting to have two column divisions appear on the same line. Take a look at my code: <div class="col-md-12"> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6"> Left Division </div> ...

Having trouble getting a DIV to appear on top of another DIV containing an image

I need help with positioning an "InfoBox" above the main header image on my website. Despite trying z-indexes and adjusting position, I can't seem to get it right. If anyone has any suggestions, please share. Thank you! For reference, here is the HTM ...

How can I improve my usage of jQuery in assigning the enter key to submit an ajax form?

My HTML code: <form action="/comment_replies/ajax_create/30?type=2" id="new_comment_2_30" method="post" onsubmit="new Ajax.Request('/comment_replies/ajax_create/30?type=2', {asynchronous:true, eva ...

"Tips for stopping users from using Ctrl+U to view page source in

Is there a way to prevent users from viewing the source code (HTML + JavaScript) of a page by disabling Ctrl+U in the browser? ...

Creating a switch statement that evaluates the id of $(this) element as a case

I have a menu bar with blocks inside a div. I am looking to create a jQuery script that changes the class of surrounding blocks in the menu when hovering over a specific one. My idea is to use a switch statement that checks the ID of $(this) and then modif ...

Using AJAX and FormData to Attach a List upon Submission

I am currently working on connecting a list of "Product Specifications" to my "Add Product" dialog, and I'm using AJAX to submit the form. Since users are able to upload a product image within this form, I am sending the AJAX request with a 'For ...

Tips for breaking out of the foundation row and aligning with the right edge of the viewport

I have a CodePen example showcasing the Zurb Foundation grid. I am looking for a way to make a div extend to the right edge of the viewport while keeping the left edge in line with the grid as the viewport is resized. <div class="row"> <div cla ...

The transition in Vue Js is only effective when elements are entering, not when they are

Attempting to implement a vue js transition from bottom to top and top to bottom. The transition works smoothly from bottom to top when entering, but there is no transition effect when leaving. Below is the CSS code for the transition: .slide-details-mob ...

Concerns with the adaptability of CSS grid rows

I'm struggling to find a solution for the issue I am facing. Is there a way to adjust each column's row height based on its content in a way that differs from the other column rows? The code snippet below demonstrates the current setup, which is ...

Seeking to develop a pair of functions for submitting data via my website's form

I need to pass form data to both Docusign and Zapier with just one button click using JavaScript. When the Submit button is pressed, I want the data to be sent to Zapier without opening a success page and then redirect to the Docusign page with all the in ...