/    Sign up×
Community /Pin to ProfileBookmark

Show Bootstrap modal after submitting form using PHP

I have rewritten a website for a charity, using Bootstrap 4.

It is a single page website, with 3 forms on it, submitting the forms sends an email to different officials of the charity.

The form handling is done using PHP on the same page.

That all works well, but I am trying to work out how to display a Bootstrap “Thank you” modal after the form handling.
I should point out that I know practically nothing about Javascript so have been trying code found on the internet

I have tried using a call within the PHP to call a JS modal.show function after sending the mail, but that isn’t working.
I have used a session variable to determine which form and the result (e.g. sent/not sent) and within the modal code use PHP to determine text to display. and was wondering if I could use that variable in a Javascript in a document.ready function to call the modal.show, but haven’t been able to get that to work either.
The attached pseudo code shows the PHP/HTML <head> structure that I have tried.

Can anyone help me sort this?

Thanks

“`
<?php

if (!isset($_SESSION[“modalform”])) {
session_start();
$_SESSION[“modalform”] = “”;
} else {
if (isset($_POST[“submit_CU”])) {
/* Handle email */
$form = “CU”;
} else if (isset($_POST[“submit_WL”])) {
/* Handle email */
$form = “WL”;
} else if (isset($_POST[“submit_UF”)) {
/* Handle email */
$form = “UF”;
}
$sent = mail($email_to, $email_subject, $message, $headers, “-f” . $email_from);
if ($sent) {
$_SESSION[“modalform”] = $form;
} else {
$_SESSION[“modalform”] = “FAIL”;
}
/* Have tried to echo a <script> function here, but didn’t work */
}

/* Helper Functions */

function tidy_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title>V3 PHP</title>
<meta content=”width=device-width, initial-scale=1.0″ name=”viewport”>

<!– Favicon –>
<link href=”img/favicon.ico” rel=”icon”>

<!– Google Fonts –>
<link href=”https://fonts.googleapis.com/css?family=Montserrat:300,400,500,700|Open+Sans:300,300i,400,400i,700,700i” rel=”stylesheet”>

<!– Bootstrap CSS File –>
<link href=”lib/bootstrap/css/bootstrap.min.css” rel=”stylesheet”>

<!– Libraries CSS Files –>
<link href=”lib/font-awesome/css/font-awesome.min.css” rel=”stylesheet”>

<!– Main Stylesheet File –>

<link href=”css/style.css” rel=”stylesheet”>

<script src=”lib/jquery/jquery.min.js”></script>
<script src=”lib/bootstrap/js/bootstrap.bundle.min.js”></script>

<script>
$(document).ready(function () {
var value = <?php echo $_SESSION[‘modalform’]; ?>;
if
value < > “” (
value = “#” + value;
$(value).modal(‘show’);
}
});
</script>

</head>

<body>
“`

to post a comment
JavaScript

8 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumJul 26.2021 — @Phredd#1634755

Please use code tags: `your code here</C> or triple backticks when posting code. I edited your posting accordingly.

There are several errors in your javascript. Change it to this:
<CODE>
`<i>
</i> &lt;script&gt;
$(document).ready(function () {
var value = &lt;?php echo $_SESSION['modalform']; ?&gt;;
if (value != "") {
value = "#" + value;
$(value).modal('show');
}
});
&lt;/script&gt;<i>
</i>
``
Copy linkTweet thisAlerts:
@PhreddauthorJul 27.2021 — Apologies about the code format - didn't relise until after I pressed SUBMIT that only half had been formatted, and couldn't see how to edit the post.

However I still can't get it to work.

I have amended the code:
``<i>
</i>&lt;?php
if (empty($_SESSION) &amp;&amp; !isset($_SESSION)) {
session_start();
$_SESSION["modalform"] = "";
} elseif (isset($_POST)) {
if ($_POST["submit_CU"]) {
$_SESSION["modalform"] = "CU";
} elseif ($_POST["submit_WL"]) {
$_SESSION["modalform"] = "WL";
} elseif ($_POST["submit_UF"]) {
$_SESSION["modalform"] = "UF";
}
}
?&gt;
&lt;!DOCTYPE html
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="utf-8"&gt;
&lt;title&gt;Modal on Page Load Trial&lt;/title&gt;
&lt;link rel="stylesheet" href="css/bootstrap.min.css"&gt;
&lt;script src="js/jquery.min.js"&gt;&lt;/script&gt;
&lt;script src="js/bootstrap.min.js"&gt;&lt;/script&gt;
&lt;!--
&lt;script&gt;
$(document).ready(function () {
$("#ModalThanks").modal('show');
});
&lt;/script&gt;
--&gt;
&lt;script&gt;
$(document).ready(function () {
var value = &lt;?php echo $_SESSION['modalform']; ?&gt;;
if (value != "") {
$("#ModalThanks").modal('show');
}
});
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div&gt;
&lt;form id="formCU" action=""&gt;
&lt;button type="submit" name="submit_CU" title="Send Message"&gt;Submit CU Form&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;form id="formWL" action=""&gt;
&lt;button type="submit" name="submit_WL" title="Send Message"&gt;Submit WL Form&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;form id="formUF" action=""&gt;
&lt;button type="submit" name="submit_UF" title="Send Message"&gt;Submit UF Form&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;

&lt;div class="modal fade" id="ModalThanks"&gt;
&lt;div class="modal-dialog"&gt;
&lt;div class="modal-content"&gt;
&lt;!-- Modal Header --&gt;
&lt;div class="modal-header"&gt;
&lt;h4 class="modal-title"&gt;Thank You&lt;/h4&gt;
&lt;button type="button" class="close" data-dismiss="modal"&gt;×&lt;/button&gt;
&lt;/div&gt;
&lt;!-- Modal body --&gt;
&lt;div class="modal-body"&gt;
&lt;?php
if ($_SESSION["modalform"] === "CU") {
echo("&lt;b&gt;CU was selected&lt;/b&gt;");
} elseif ($_SESSION["modalform"] === "WL") {
echo("&lt;b&gt;WL was selected&lt;/b&gt;");
} elseif ($_SESSION["modalform"] === "UF") {
echo("&lt;b&gt;UF was selected&lt;/b&gt;");
}
?&gt;
&lt;/div&gt;
&lt;!--Modal Footer--&gt;
&lt;div class="modal-footer justify-content-center"&gt;
&lt;button type="button" class="btn btn-outline-danger btn-rounded btn-md ml-4" data-dismiss="modal"&gt;Close&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt; &lt;!-- Modal ---&gt;

&lt;/body&gt;
&lt;/html&gt;<i>
</i>
``

The session variable seems to be reset to "" after each "page load" (The modal displays with an empty body) if I use the commented out script, but if I use the script that is not commented out no modal is displayed at all.

I realise it might be because I do not "get" how the PHP is working, but would be grateful if someone could explain what I am missing.

Many thanks
Copy linkTweet thisAlerts:
@NogDogJul 27.2021 — > @Phredd#1634793 &lt;?php
<i>&gt; </i>if (empty($_SESSION) &amp;&amp; !isset($_SESSION)) {
<i>&gt; </i> session_start();
<i>&gt; </i> $_SESSION["modalform"] = "";
<i>&gt; </i>}


Maybe try this, with some error-trapping in case something's going on:
[code=php]
<?php
ini_set('display_errors', true); // set to false in production
error_reporting(E_ALL);

if(session_status() != PHP_SESSION_ACTIVE) {
session_start());
}
[/code]

Another possible gotcha is inconsistent use of www. or other sub-domains when accessing the pages. This can be avoided by a bit of session cookie configuration before any/all calls to session_start():
[code=php]
<?php
session_set_cookie_params(0, '/', '.example.com'); // replace with your domain, note leading dot
session_start();
[/code]
Copy linkTweet thisAlerts:
@NogDogJul 27.2021 — PS: The session_start() command always needs to be used on any page that is going to use $_SESSION, so unless this file might be included/required by some other file, there's no reason to test if the session is active first: just do the session_start() right away (and make sure it's done before _anything_ gets output to the browser, even white-space or non-printing characters);
Copy linkTweet thisAlerts:
@SempervivumJul 27.2021 — @Phredd#1634793

NogDog was faster.

I fixed the following errors:
  • - In order to make the session variables available you have to call session_start unconditionally.

  • - You have to use isset when testing if a post variable is set.


  • This resulted in the following PHP:
    ``<i>
    </i>session_start();
    if (empty($_SESSION) &amp;&amp; !isset($_SESSION)) {
    $_SESSION["modalform"] = "";
    } elseif (isset($_POST)) {
    if (isset($_POST["submit_CU"])) {
    $_SESSION["modalform"] = "CU";
    } elseif (isset($_POST["submit_WL"])) {
    $_SESSION["modalform"] = "WL";
    } elseif (isset($_POST["submit_UF"])) {
    $_SESSION["modalform"] = "UF";
    }
    }<i>
    </i>
    `</CODE>
    <LIST><LI>- Apostrophes were missing when assigning the value of <C>
    $_SESSION['modalform']</C> as this is a string.<br/>
    That line should read: <C>
    var value = '&lt;?php echo $_SESSION['modalform']; ?&gt;';</C></LI></LIST>

    After having fixed these errors, the modal is popping up after submitting one of the forms.

    Edit: I forgot about that, I had to add <C>
    method="post"` to the form tag as GET is default.
    Copy linkTweet thisAlerts:
    @PhreddauthorJul 27.2021 — Thanks folks, that seems to have sorted the major problems. Just one thing whenever the page is opened, whether after a page reload, or as a new browser startup, it looks like the previous session is still active, as the modal displays on startup using the credentials last assigned to the modalform session variable..
    Copy linkTweet thisAlerts:
    @NogDogJul 27.2021 — > @Phredd#1634799 it looks like the previous session is still active

    It will be active until either the session cookie expires, or the corresponding session data stored on the web server is deleted. If you want the session cookie to have a limited lifespan, you can either specify it in your default PHP config via the session.cookie_lifetime option, or explicitly in your code via the session_set_cookie_params(), e.g.:
    [code=php]
    <?php
    session_set_cookie_params(1800, '/', '.yoursite.com'); // 1800 seconds == 30 minutes
    session_start();
    [/code]

    Also, while testing, you can always clear cookies for that page via your browser menu/tools, and it will effectively drop the old session and have to start a new one.
    Copy linkTweet thisAlerts:
    @PhreddauthorJul 27.2021 — Have sorted it by using a $_SESSION["modalform"]="", at the end of the PHP if.... construct in the modal-body

    Not elegant, but seems to work!
    ×

    Success!

    Help @Phredd spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 3.29,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,

    tipper: Anonymous,
    tipped: article
    amount: 10 SATS,
    )...