dispatch email display Twitter Bootstrap notification utilizing Ajax

I'm trying to set up an email sending feature via a contact form. I want it to send the email and display a Bootstrap alert confirming that the email has been sent. Below is the HTML code: https://jsfiddle.net/6rfeas35/. Additionally, here is my PHP code within the AJAX JQuery at the bottom of index.php:

   <script>
       AOS.init();
       $(document).ready(function(){
           $('#contactForm').submit(function(e){
               e.preventDefault();
               const $this = $(this);

               // disable submit button
               const $button = $(this).find('button[type="submit"]').text('Submit...').attr('disabled', 'disabled');

               // send message
               $.ajax({
                   type: 'POST',
                   url: 'contact.php',
                   data: $this.serialize(),
                   success: function(data){
                       alert("E-mail envoyé avec succès ! Merci pour votre message ! Une réponse vous sera apportée dans les plus brefs délais.");
                        $this[0].reset(); // reset form
                   },
                   error: function(jqXHR, textStatus, errorThrown){
                       alert('An error occurred. Please try again')
                   },
                   complete: function(jqXHR, textStatus){
                       // enable submit button
                       $button.text('Submit').removeAttr('disabled');
                   }
               })
           })
       })
   </script>

Here's the contact.php code:


 <?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

if(isset($_POST["send"])){

    $body = $_POST['message'];
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    

    $mail = new PHPMailer(true);
    
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="271014094652534809101467404a464e4b0944484a">[email protected]</a>';
    $mail->Password = 'rlylecrtuvztqosz';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
    $mail->Port = 465;      
    $mail->setFrom('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5463677a3521203b7a6367143339353d387a373b39">[email protected]</a>');

    $mail->addAddress($_POST["email"]);

    $mail->isHTML(true);

    $mail->Subject = 'Projet web';
    $mail->Body = "Message:" . $body . "<br>Phone number: " . $phone . "<br>Name: " . $name . "<br>Mail: " . $email;

    $mail->send();

    echo "success";
    
}

The issue I'm facing is that the bootstrap alert pops up but the email is not being sent. I can't figure out why this is happening. If I remove the AJAX jQuery code, the email gets sent but it opens a blank success page. How can I make sure both the email is sent and the Bootstrap alert is displayed simultaneously?

Answer №1

To ensure that the isset($_POST["send"]) check in the contact.php file works correctly, make sure there is an input with the name="send" attribute present in the form within the index.php file.

  • Add a hidden field with name="send" to the form and remove it from the submit button.

index.php

https://jsfiddle.net/y3s79nqa/

contact.php

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

if(isset($_POST["send"])){

    $body = $_POST['message'];
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    

    $mail = new PHPMailer(true);
    
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b1c18055a5e5f44051c186b4c464a424705484446">[email protected]</a>';
    $mail->Password = 'rlylecrtuvztqosz';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
    $mail->Port = 465;      
    $mail->setFrom('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2116120f4054554e0f161261464c40484d0f424e4c">[email protected]</a>');

    $mail->addAddress($_POST["email"]);

    $mail->isHTML(true);

    $mail->Subject = 'Web project';
    $mail->Body = "Message:" . $body . "<br>Phone number: " . $phone . "<br>Name: " . $name . "<br>Mail: " . $email;

    $mail->send();

    echo "success";
    die;
}

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

Adjust the width of the dropdown menu to match the text input field using jQuery

Struggling with jquery-mobile to collect user information, I am facing an issue aligning the width of my select menu with the text input fields. Despite successfully matching the background and border colors of the select menu with the text input fields, ...

Reconfigure a portion of a string using Vue's dynamic replacement feature

Currently tackling a problem. In my possession is a string that essentially consists of HTML code: let htmlTitle = "<a href="/news/sky-sport-hd-in-italia-dal-18-novembr">Sky Sport HD in italia dal 18 novembre</a> | <a href="/news/ecco-il-g ...

Fetching Data Using Cross-Domain Ajax Request

Seeking assistance with a cross-domain Get request via Ajax. The code for my ajax request is as follows: var currency_path = "http://forex.cbm.gov.mm/api/latest"; $.ajax({ url: currency_path, crossDomain:true, type:"GET", dataTyp ...

Enhance the editing capabilities of the Json data form

https://i.stack.imgur.com/YZIjb.png My goal is to enhance a form for editing json data by moving beyond the typical <textarea /> tag and making it more user-friendly. Are there any tools available that can help improve the form's usability? Add ...

The For loop with varying lengths that exclusively produces small numbers

I'm currently using a for loop that iterates a random number of times: for(var i = 0; i<Math.floor(Math.random()*100); i++){ var num = i } This method seems to be skewed towards producing lower numbers. After running it multiple times, the &apo ...

In Flow, how is the asterisk (*) type utilized and what is its counterpart in TypeScript?

My expertise lies mostly in TypeScript, but I recently came across Flow which seems quite similar to TS in many aspects. However, one thing that caught my attention is the asterisk (*) type in Flow. Initially, I thought it was just another way of represent ...

Looping through JSON data in PHP with a foreach loop may

Currently, I am working on a project that involves PHP and JSON. Within my code, there is a JSON foreach loop example that I am using to extract latitude and longitude coordinates in order to add markers on Google Maps: "data": [ { "end_t ...

Assigning a new classification to the primary object in the evolving array of objects

I'm working with an element that loops through all the objects using v-for and has a CSS class named top-class{}... I need to dynamically add the top-class to the first object (object[0]) and update it based on changes, removing the old top-class in t ...

"Hey, do you need a see-through background for your

Currently, I am implementing the JS library found at . Unfortunately, I am struggling to make the background transparent or any other color. It appears that the issue lies in the fact that the tab styles are being overridden by the JS library whenever the ...

Interpolating backticks in Javascript allows for constructing a URL containing empty spaces

When utilizing string interpolation with backticks to construct a URL that sends data to a django endpoint, the resulting URL contains unnecessary whitespace and a new line. The problematic JavaScript code is as follows: (function (window, document, unde ...

Creating key elements in JavaScript with the push() function

I'm working on a basic shopping cart system using JavaScript (Ionic 2 / Angular). In my PHP code, I have the following: <?php $cart = array( 48131 => array( 'size' => 'STANDARD', 'qty' => ...

How can you toggle the visibility of a text based on the selection of a jQuery radio button?

Is it possible to dynamically enable or disable a field based on the selection of a radio button? Here are the rules: The field should only be active when the "Inactive" radio button is selected Check out the code snippet below for reference: Radio B ...

`What is the best way to employ the Return statement in programming?`

Trying to grasp the concepts of functions and methods has been a challenge for me. I often find myself confused about when, where, and how to use return statements in different situations. To illustrate this confusion, let's take a look at two code sn ...

Calculate the percentage variance across two figures (multiple occurrences)

My goal is to execute the result function for each instance of item. The desired output of the result function is the percentage calculated by dividing value / max. However, I am facing issues when using value and max as variables in the function. $(".l ...

Using the Slim framework to communicate through JSON

When attempting a simple POST request, I am having trouble reading the JSON data no matter what I try. $.ajax({ url: 'server/account/session', type: 'POST', data: { "username": name, "password": password} , ...

How can we modify this function to interpret multiple selections at once?

For the task of displaying multiple selections from a scrolling list to an alert, I have implemented the following function: var toppings = ""; function displaySelectedToppings() { var topList = document.getElementById('to ...

Insert a user-specified key into an array at a custom position

Similar Question: Modifying associative arrays with array_splice() I am working with an associative array containing product data. Array ( [0] => Array ( [ID] => 1 [Name] => Game 1 [Price] => ...

Is there a way to define a varying number of OR conditions in a Doctrine SQL Where clause?

Is there a way to dynamically generate a Doctrine ORM query that mimics the following SQL statement, considering that the number of values in the 'OR' clause may vary with each execution? SELECT * FROM table1 WHERE table1.group = 1 OR 2 OR ...

What could be causing the Type Error in jsdom?

When attempting to parse a remote site using jsdom, I encountered an error when trying to use it with node-webkit.js: I received the following error: "Uncaught TypeError: A 'super' constructor call may only appear as the first statement of a f ...

Creating multi-dimensional arrays using array lists with Axios and Vue.js

My knowledge of axios and JavaScript is limited, and I find myself struggling with creating a multi-dimensional array. 1. This is how I want my data to be structured : https://i.stack.imgur.com/kboNU.png userList: [ { ...