Alert for button submission

Here, on the right, in my small mail sender.

I have been trying to use “sweetalert” as sent e-mail confirmation message but I am having some problem making it work properly.

Here you can find what should be the official page.

It seems however, it conflicts with some other jQuery call in my page, therefore the snippet of code suggested in the aforementioned link does not work.
Looking around I managed to find this other discussion (there are other threads linked to it which might help to understand better the problem) from which I took the current code snippet I’m using.

Code snippet I’m using:

$(document).ready(function () {
    setTimeout(function () {
        swal({title: 'Error!', text: 'Here\'s my error message!', type: 'error', confirmButtonText: 'Cool'});
    }, 1000);
});

It is supposed to delay sweetalert implementation to not conflict with the other calls and as far as I know it is working as the alert is showing up unlike with the original code suggested in the official site.

It is not clear to me why the alert is popping out as soon as the page gets loaded. It is supposed to appear after the button submission…

Any idea?

It’s because you are calling this code after a delay of one second. No button clicking involved.

Where is the button on your page you are talking about? I cannot see it.

I had this feeling

Forgot to mention. The button pops up if you hover on the “✓” symbol .

So what do you want to happen when the button is clicked?
Do you want the popup to display, then when the user clicks “OK” in the popup, the form to submit?
Submitting the form will of course entail a page refresh.

It would be enough just for the popup to appear once the page has got refreshed just to give the user a confirmation that everything went ok.

Right now when the button is clicked the mail gets sent and the page gets refreshed.
The popup is showing every time the page is refreshed but not because of the button submission.

Er yeah. But how should the page know that the mail was sent correctly or not? HTML is stateless in that respect.

One solution would be to redirect the user to a page with a sucess message after a simple submission. Another idea would be to append a query string to the url (e.g. ?resp=success) and display the popup based on the presence of that. Another would be to submit the form via Ajax and display the popup depending on the server’s response.

What isn’t going to work is to click a button to submit a form which refreshes the page and expect the page to then have some idea of whether the mail was sent successfully.

Personally, I like the Ajax solution, although that means you’re relying on JS being enabled.

Well yes, that way there wouldn’t have been any certitude about the success or not of the process. It was my way to keep things simple given how hard have been for me to find people willing to help with more complex stuff.

But if you say Ajax…why not?! Does it sound too rude or carefree asking what do I need to do?
Does Ajax use a similar sending method that need to be specified within the html <button> tag?
Besides, out of curiosity, can anything similar be done with php?

Ajax is a way that JavaScript can communicate with PHP and return values to the JavaScript without reloading the web page. It doesn’t involve HTML in any way. You would normally use eithe XML or JSON to pass the information back from the PHP to the JavaScript.

No that’s fine. Let’s start with a simple example. You will need to run this on a server.

Say you have a basic page with a button:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Ajax example</title>
  </head>
  <body>
    <button>Click Me!</button>

    <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
  </body>
</html>

Let’s attach an event listener to the button, so that when it’s clicked, it sends an Ajax request to a script called submit.php.

$("button").on("click", function(){
  $.ajax({
    url: '/path/to/submit.php',
    type: 'POST',
  })
  .success(function(response) {
    alert("The server says: " + response);
  })
});

Here, we’re specifying that it should be a POST request. We’re also specifying a success callback. This is a function which will be executed if the request completes successfully.

In submit.php place the following:

<?php
  echo "Hello!";
?>

If you run the script, you should see an alert saying “The server says: Hello!”.

Now let’s apply that to your email script. The part with the button is still the same, but you’ll want to add some validation to check that the user has entered something approaching a valid email address and, if valid, you’ll want to send that email address to the PHP script. The PHP script can then attempt add the user to the database and return a success or failure message.

This gives us:

<p>
  <input type="email" id="email_address" placeholder="Email address"  />
  <button id="subscribe">Subscribe</button>
</p>

and:

$("#subscribe").on("click", function(e){
  e.preventDefault();
  var address = $("#email_address").val();
  if (!/\S+@\S+\.\S+/.test(address)){
    alert("Email address not valid!");
  } else {
    subscribeToNewsletter(address);
    $("#email_address").val("")
  }
});

Now, when the button is clicked, the button’s default action is prevented. We then grab whatever the user has entered into the email field, check that it looks like an email address (i.e. that it has something, followed by an at sign, followed by something, followed by a dot, followed by something). If this test passes, we then call the function subscribeToNewsletter(), passing it whatever the user entered. Finally, we reset the value of the email field.

Your markup here will be slightly different, but hopefully this demonstrates the principal.

Next, let’s look at the function that sends the address to the server:

function subscribeToNewsletter(address){
  $.ajax({
    url: 'subscribe.php',
    type: 'POST',
    data: {email: address}
  })
  .success(function(message) {
    alert(message);
  })
  .fail(function() {
    alert("There was a problem. Please try again later.");
  });
}

Finally, submit.php:

New things to note:

  • The way we pass data to the server data: {email: address}
  • The introduction of .fail()
  • message will hold the server’s response, which we will display to the users

Onto the PHP. I’m assuming you have the function to do the inserting all set up.

<?php
  $message = "";
  $email = $_POST['email'];

  if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    insertIntoDatabase($email);
    $message = "You were subscribed to the list";
  } else {
    $message = "Invalid email address";
  }

  echo $message;
?>

It might also be an idea to check if the insert was successful. I’ll leave that to you.

And that’s it. Let us know how you get on implementing it.

1 Like

Thank you very much for your time.

This is my PHP which I called “mailcontadinobio.php” instead of “submit.php”.

<?php
/* Set e-mail recipient */
$myemail = "mail@ilcontadinobio.it";
$subject = "New e-mail address from ilcontadinobio.it";
$emailErr = "";

/* If e-mail is not valid show error message */
if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = $_POST["email"];
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
    }
  }
/* Let's prepare the message for the e-mail */
$message = "E-mail: $email";

/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */
header('Location: index.html');
exit();

function show_error( $emailErr)
{
?>
<html>
<body>

<strong><?php echo $emailErr; ?></strong>
<p>Hit the back button and try again</p>

</body>
</html>
<?php
exit();
}
?>

It was a more complex piece of coding; I stripped it almost to the essential. You can spot header('Location: index.html'); which gets the page reloaded when you hit the button.

Tell me if that is ok, otherwise I will strip it further making it looks like the one you suggested.

This is the original code I wanted to use

<?php
/* Set e-mail recipient */
$myemail = "YOUR EMAIL ADDRESS";

/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Enter your name");
$subject = check_input($_POST['subject'], "Enter a subject");
$email = check_input($_POST['email']);
$message = check_input($_POST['message'], "Write your message");

/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* Let's prepare the message for the e-mail */
$message = "

Name: $name
E-mail: $email
Subject: $subject

Message:
$message

";

/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();

/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}

function show_error($myError)
{
?>
<html>
<body>

<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>

</body>
</html>
<?php
exit();
}
?>

It’s got a twisted check_input() function I couldn’t succeed in having it work.

That said, I suppose this

$("#subscribe").on("click", function(e){
  e.preventDefault();
  var address = $("#email_address").val();
  if (!/\S+@\S+\.\S+/.test(address)){
    alert("Email address not valid!");
  } else {
    subscribeToNewsletter(address);
    $("#email_address").val("")
  }
});

go along to all my other snippets of code to either the head or at the end in the body of the page.

What about the subscribeToNewsletter() function?

Apologize for the amount of code. Far from me the intent to scare you away.

So, what I did was to add your code together in the head, like this:

<script>
$("#subscribe_button").on("click", function(e){
  e.preventDefault();
  var address = $("#email_address").val();
  if (!/\S+@\S+\.\S+/.test(address)){
    alert("Email address not valid!");
  } else {
    subscribeToNewsletter(address);
    $("#email_address").val("")
  }
});
function subscribeToNewsletter(address){
  $.ajax({
    url: 'mailcontadinobio.php',
    type: 'POST',
    data: {email: address}
  })
  .success(function(message) {
    alert(message);
  })
  .fail(function() {
    alert("There was a problem. Please try again later.");
  });
}
</script> 

I’ve naturally changed some ids. You can see the result online clicking on the link in my first post.

Seems to me that the alert is still firing on page load, not when someone subscribes : (

Exactly! How can that be possible? Did I do everything you explained correctly?

Because your page still contains the following code:

$(document).ready(function () {
    setTimeout(function () {
       swal("Thank you!", "Your address has been successfully submitted!", "success");
    }, 1000);
});

Right now I just left

<script> swal("Thank you!", "Your address has been successfully submitted!", "success"); </script>

which should be the function to enable the alert when the button is clicked.

Result:
The alert does’t show up and the submission happen without none of the conditions set in your code is applied; in other words if you simply hit the button, an email containing nothing in it will arrive in my inbox. Again you may check it out by yourself.

Nope. This will display an alert when the page is loaded.

What should I do then?

Ok. Could you make a skeleton version of your page with most of the content and the other scripts stripped out?

All scripts in the page are jQuery’s. Do you want me to strip the page of all the jQuery contents?

Yeah, just remove all of the unnecessary stuff, like unrelated scripts. I’ll show you how to get the button sorted out, then you can add the rest back in making sure things don’t break.