Using different elements of Snack bar function in different stages of program

35
February 12, 2019, at 9:10 PM

As a beginner, I've defined a snack bar function(snackbarfunction) and there are 3 elements which should be shown in different stages of the program(For instance,when user enters email the message 'Successful, Thanks' should be shown by snack bar) thus, I was going to separate elements by a variable from my PHP page. However, the variable isn't detectable either in JS or HTML part.

Is there any different way except the way I'm working on?

there is the form:

<?php
     require_once "indexRequest.php";
 ?>
                <form class="news-letter" id="email-form" method="post" action="indexRequest.php">
                 <div class="subscribe-hide">
                        <input class="form-control" type="email" id="subscribe-email" name="email" placeholder="Email Address" required>
                        <button onclick="snackbarfunction()"  id="subscribe-submit" class="btn"><i class="fa fa-envelope"></i>
                        </button>
                       <span id="subscribe-loading" class="btn"> <i class="fa fa-refresh fa-spin"></i> </span> 
                        <div id="snackbarrepeated">Email already exists.</div>
                        <div id="snackbardone">Successful, Thanks.</div>
                        <div id="snackbarfailed">Unsuccessful, Please try again.</div>

                  </div>
                </form>
                <br>
                <p class="section-description">
                    We Will Notify You!
                </p><!-- /.section-description -->
                <br>
            </div>
        </div>
        <br> <br>

    </div>
    <!-- /.container -->
</div>
<!-- /.pattern -->
</section>
function snackbarfunction() {
    <?php  if(!is_null($status)) { ?>
    var x = document.getElementById("snackbarfailed");
    x.className = "show";
    setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
    var y = document.getElementById("snackbarrepeated");
    y.className = "show";
    setTimeout(function(){ y.className = y.className.replace("show", ""); }, 3000);
    var z = document.getElementById("snackbardone");
    z.className = "show";
    setTimeout(function(){ z.className = z.className.replace("show", ""); }, 3000);
    <?php  } ?>
}
</script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
    // bind 'email-form' and provide a simple callback function
    $('#email-form').ajaxForm(function() {
    });
});
</script>
</body>
</html>

and that's my PHP codes:

<?php
require_once "DB.php";
        $status = null;

        if($_SERVER["REQUEST_METHOD"] == "POST")
        {
            $status = "s";
            $email = $_POST['email'];
            if(filter_var($email , FILTER_VALIDATE_EMAIL) && htmlspecialchars($_POST['email']))
            {
                $conn = connectToDB();
                if( ! userGet($email , $conn))
                {
                    userSave($email , $conn) ? $status = "Done" : $status = "Not-Done";
                }
                else
                {
                    $status = "Duplicated";
                }
            }
        }
        ?>

Thanks in advance for any help you are able to provide.

Answer 1

First thing, the php scrips runs on the server side and the js, run on the client side, so it wont be possible to do what you are trying to do without both sides "talking" to eachother. I can see that you made a ajax, that's one way to make that communication happen.

Second thing: You php script needs to send a response to the ajax. I believe the common way to do so is to use json response. At the end of your .php you should place the following code:

header('Content-Type: application/json');
echo json_encode($status);

Now you need to make the js read the response and do something with it. You'll have to add a response on the form, so that the js knows that you will use it somehow

$(document).ready(function() {
    // bind 'email-form' and provide a simple callback function
    $('#email-form').ajaxForm(function(response) {
         console.log(response); //here you will have your $status variable, but readable from js.
         // now you shoul call the function to make the changes on the page
         snackbarfunction(response);
    });
});

Obs1: I place a console.log('response') because the $status may not be directly the responsevariable, it may be inside the response, like this: response.data

I took the liberty to change your function to use the JS variable:

function snackbarfunction(response) {
    if(response == "Done"){
       var z = document.getElementById("snackbardone");
       z.className = "show";
       setTimeout(function(){ z.className = z.className.replace("show", ""); }, 3000);
    }else if(response == "Duplicated"){
        var y = document.getElementById("snackbarrepeated");
        y.className = "show";
        setTimeout(function(){ y.className = y.className.replace("show", ""); }, 3000);
    }else{
        var x = document.getElementById("snackbarfailed");
        x.className = "show";
        setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
    }
}

UPDATES

Create a new file in the same directory of the form:

<?php
require_once "DB.php";
$status = null;
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $status = "s";
    $email = $_POST['email'];
    if(filter_var($email , FILTER_VALIDATE_EMAIL) && htmlspecialchars($_POST['email']))
    {
        $conn = connectToDB();
        if( ! userGet($email , $conn))
        {
            userSave($email , $conn) ? $status = "Done" : $status = "Not-Done";
        }
        else
        {
            $status = "Duplicated";
        }
    }
}
header('Content-Type: application/json');
echo json_encode($status);

Your form page:

The rest of the file...
            <form class="news-letter" id="email-form" method="post" action="send_mail.php">
                 <div class="subscribe-hide">
                        <input class="form-control" type="email" id="subscribe-email" name="email" placeholder="Email Address" required>
                        <button onclick="snackbarfunction()"  id="subscribe-submit" class="btn"><i class="fa fa-envelope"></i>
                        </button>
                       <span id="subscribe-loading" class="btn"> <i class="fa fa-refresh fa-spin"></i> </span> 
                        <div id="snackbarrepeated">Email already exists.</div>
                        <div id="snackbardone">Successful, Thanks.</div>
                        <div id="snackbarfailed">Unsuccessful, Please try again.</div>

                  </div>
                </form>
                <br>
                <p class="section-description">
                    We Will Notify You!
                </p><!-- /.section-description -->
                <br>
            </div>
        </div>
        <br> <br>

    </div>
    <!-- /.container -->
</div>
<!-- /.pattern -->
</section>
<script>
    function snackbarfunction(response) {
        if(response == "Done"){
           var z = document.getElementById("snackbardone");
           z.classList.add('show');
           setTimeout(function(){ z.classList.remove('show'); }, 3000);
        }else if(response == "Duplicated"){
            var y = document.getElementById("snackbarrepeated");
            y.classList.add('show');
           setTimeout(function(){ y.classList.remove('show'); }, 3000);
        }else{
            var x = document.getElementById("snackbarfailed");
            x.classList.add('show');
           setTimeout(function(){ x.classList.remove('show'); }, 3000);
        }
    }
// wait for the DOM to be loaded
$(document).ready(function() {
    // bind 'email-form' and provide a simple callback function
    $('#email-form').ajaxForm(function(response) {
         console.log(response); //here you will have your $status variable, but readable from js.
         // now you shoul call the function to make the changes on the page
         snackbarfunction(response);
    });
});
</script>
</body>
</html>

I change className to classList because if the element has another class, it would be replaced. Like this:

<div id="a" class="a b"></div>
<script>
document.getElementById("a").className = "c"; // The element would lose class a and b and only have c
document.getElementById("a").classList.add("c");//The element would have class a,b and c 
</script>
```
Obs2: The code may need some changes, like i pointed on obs1, but if you debug the code you should have no problem with that.
READ ALSO
CraftCMS - CraftQL querying globals always returns error

CraftCMS - CraftQL querying globals always returns error

When querying globals from the GraphiQl interface, from my frontend application, or from an API explorer like Insomnia, CraftQL returns an error Trying to get property of non-object

53
Sending email over SMTP with sendgrid

Sending email over SMTP with sendgrid

I have a html fieldset and a short php file for sending an email via sendgrid when the submit button is clicked

47
bulk insert working in ssms but not working while executing from php

bulk insert working in ssms but not working while executing from php

I'm trying to insert the data from a text file into my databaseI'm using SQL Server Management Studio 17

54
Laravel/LaraCSV - Global Variable in beforeEach

Laravel/LaraCSV - Global Variable in beforeEach

I have a function in my Controller where I'm trying to export acsv file using LaraCSV

54