How do I create an email alert in Javascript?

I have been trying the echo statement

echo '<script type="text/javascript">alert("Your message has been sent!");</script>';

to be called inside an if statement when all conditions are met as in

if(empty($error_name) === true && empty($error_email) === true && empty($error_number) === true && empty($error_msg) === true){
    SentMail();
        echo '<script type="text/javascript">alert("Your message has been sent!");</script>';
        mail($yourEmail, 'Message from website: Subject: ' . $subjectField, $messageField, $headers, '-fanemail@domain.com');
       //redirect user
        
        header('Location: index.php');
        exit();
        }

This does not work, how would I be able to get this working?
Somehow the full echo statement is not showing

Your logic is reversed. You want to check to see whether any fields are empty, and provided there aren’t, then send the email. Right now, you’re currently checking to see if all fields are empty, and if so, then send the email. To rectify this, you want to negate the return value for all empty()'s (making the checks become if (some_var is not empty)):

if(!empty($error_name) && !empty($error_email)  && !empty($error_number) && !empty($error_msg)) {
    // code here
}

We negate the value using an exclamation mark to get the complement of empty()'s return value.

Aside from your condition logic, the logic of what happens inside the condition block doesn’t really make sense. Four things happen, in this order:

  1. SentMail() is called, which does something unspecified, but presumably doesn’t exit or redirect?
  2. You echo your “Message has been sent” JavaScript alert.
  3. You actually send the mail. (Ignoring the return value, which is never a good thing!)
  4. You redirect to *index.php"

The main problem here is the redirect. The moment that header reaches the browser it’ll redirect you to the index page. The JavaScript code you print before it will in all likelihood be ignored, and the alert never shown, as the browser will never get around to executing that line of code before the redirect takes effect.

Another issues - while not a fatal issue - is that you print the message that the message was sent before you actually send the message, and regardless of whether or not the message was actually sent successfully. That message is essentially a lie, since at that point in the code you have no way to know whether it’s true. You need to grab the return value of the mail() call and make sure it returns true, indicating a successful call, before printing this message.

My suggestion to you would be to do the redirect on the client-side, either in JavaScript after an alert, or by exchanging the old-school alert() call out for a HTML/CSS based alert-like dialog, where the “OK” button is actually a link. - I’d advice you to use the latter method, as alert() popups are generally considered bad for the user experience. You can make custom alert dialogs look much better, and they don’t have to be difficult to create. (Even just using cookie-cutter dialogs like the one from jQuery UI can look far better than the alert box.)

Yeah, the SentMail() was something I just made up the day I made this thread, hence the reason why it’s still in the copy and paste version i.e. on this thread

About 4, you’re saying that I should re-direct it back to the page where the form is? As in, I should send all the variables (because this is done on the same page), to a process page and then re-direct to the mail page?

You can do that if you want to, but you don’t have to.

All I’m saying there is that you can’t echo your JavaScript alert first, and then use a PHP header redirect. For one thing, the echo will very likely cause the redirect to fail (you’re not allowed to set headers after you echo anything), and even if your system is set up to allow that (via output buffering) then the header will take effect first and the alert will never show.

However if you echo the alert and a JavaScript redirect, then it will show the alert first and then redirect.

<script>
    alert("Page will redirect when you close this box!");
    window.location = '/index.php';
</script>

The alert call blocks the execution until it’s closed, so the following window.location assignment (which is how you redirect using JavaScript) will be halted until then.

Not necessarily. Some people have the debugging alerts turned off and so wouldn’t see it while others will always click the checkbox in the alert to turn off JavaScript as you have asked them to and so the redirect will never run.

True, it’s possible that people have either the alert boxes blocked, or even have JavaScript turned off entirely. It’s a small minority these days thought, and it’s usually safe to assume JavaScript is running normally. Or at least in a way that lets your code manipulate the DOM, if not raise alerts.

Which is one reason I prefer Lightbox-like modals over old-school alerts. They are a far more user friendly way of raising alerts; less intrusive and annoying, and can be styled to match the site.

As far as I know, none of the browsers actually turn off JavaScript execution when you check the box to prevent further alert boxes. Chrome will simply silently ignore alert calls, while Firefox will throw errors. IE doesn’t even offer this as an option, so it is a non-issue. Not sure about the others though, but odds are they share the behaviour of one of the major three.

Also, this won’t be a problem if there is only one box. The option only shows up on the second alert box.

If you want to make sure this doesn’t interfere with the commands following the alert calls in Firefox, you can simply wrap the alert calls in try-catch blocks. Something akin to:

try {
    alert("Page will redirect when you close this box!");
}
catch (e) {
    // Alert boxes have been blocked. We don't really care.
}
window.location = '/index.php';

Even before some browsers started asking og you wanted to continue displaying alerts in thedebugging alert message others simply aske if you want to disable JavaScript for the page (and do that in the first debugging alert call instead of waiting for the second one).

While there is no reason to use alert for debugging any more as all browsers now have a built in debugger, there is even less reason to use alert for anything else. The last browser that needed alert to be used for anything other than debugging is Netscape 4.

The checkbox and message to the right of it are built into ALL alerts generated by the browser I captured the above image from and checking that checkbox turns off JavaScript for the current page without returning to the script.

Interesting. I don’t recall seeing a browser do that, and I’ve developed for just about every browser released this century at one point. - Granted, I don’t use alert boxes in my own work, so I might have missed their behaviour in some of them.

Which browser did you capture that from? Kind of looks like Opera.

I completely agree with you on the use of alerts. Lightbox-like modal windows are definitely the better option.

It is Opera - I forget which version it was introduce in (9 or 10 I think - anyway long before the other browsers added their checkboxes for tuirning off alerts) but it still works that way in 12 which is still considered a current Opera version as the more recent webkit ones are still missing a lot of the features that version 12 has and so most Opera users are still using version 12).

I don’t see such alerts any more even though I still use Opera 12 a lot as I turned off alerts completely so that I don’t need to see debugging calls that someone forgot to remove from their script.

OK, I see. I take it most devote Opera users weren’t very happy with the WebKit/Blink versions?

With Opera having such a small usage share though (>1.5%, I believe), it’s not a major concern in this scenario, if the OP chooses to use an alert. - If he/she were to also print a "Click here if you are not redirected automatically. " link, the scenario should work out OK. 99% of users would be redirected automatically, and the remaining 1% would probably not be surprised to see it fail on their systems.

I wonder if a <noscript> tag could be used to add a meta redirect, in case browsers stop executing scripts. Might not be executed after the page load though, I suppose.

Yes you can echo out a javascript alert function, you can do that to any javascript function, be it time, date or whatever. I’ve even echoed out part of a javascript that is part of an OOPs routine

Sure, @cssbonding. That was never in question. That’s the purpose of PHP: to dynamically generate client-side content, whether that be HTML, CSS, JavaScript, or whatever else you may need.

What we were discussing was the limitations of the old-school JavaScript alert() call. Not all browsers will show it, even though your PHP code prints the call perfectly into the HTML page. You would do better to use a custom modal window, created in the page with HTML/CSS/JS. Take the jQuery UI Dialog as an example.

With Modern web browsers such as Internet Explorer FIVE+ you no longer need alert() to be able to display messages to your visitors - you can use JavaScript to write the message directly into the web page and style it with CSS to show how important the message is.

No they wouldn’t as somewhere around 5-10% have JavaScript turned off for any given web site. Many more experienced web users keep it off except for those specific sites where they know that it has been written properly.

That seems an awfully high figure. What is your source for it?

From what I’ve seen from my own sites, it’s actually less than 1%. - Granted, my sites are pretty heavily targeted at business users, so it’s doubtful it’s giving me an accurate overall figure.

There are, however, a couple of Yahoo articles from from 2010 that suggest a similar number. Is really the only half-way trustworthy article I could find on this, even though it’s getting a bit dated.

There is actually no way whatsoever to tell - any statistics you see will only be counting some of those with JavaScript disabled. Many stats exclude those with JavaScript disable d completely which is why you see lots of stats around now where it looks like the figure is under 1%.

Just because someone has JavaScript disabled on one page doesn’t mean they have it disabled on another page. I have JavaScript enabled but disable it for all the pages where it is broken and stops me from being able to interact with the page properly.

The last time I saw stats where it was possible to reasonably accurately tell the figures ranged between 5 and 18% depending on which particular stats you looked at. Nothing has happened since then to significantly change the likelihood of people being more likely to have JavaScript on except that is is now possible to have it on or off on a site by site basis so that those who can have it on can now choose which sites to turn it on for. For those who can’t have it on because it makes using the web unusable nothing has changed.

Perhaps this is just me, but based on my experiences with typical users, I seriously doubt 5-18% of internet users know about, care about, or are willing to spend any thought on disabling JavaScript, either per site or even in general. - They can do it, but suggesting that even 5% of them are doing it doesn’t sound at all likely to me.

It’s hard to estimate these things, I’ll give you that. However I can’t help thinking your estimate of 5-10% is no more reliable than my estimate of 1%. Nothing you’ve said actually backs it up, any more than what I’ve said. It all just seems like guesswork, based on our different impressions/hopes of how the users are acting.

Or am I wrong? I’d love to get any half way reliable stats on this, whatever they are.

Neither do I. A significant number of them would have disabilities of some sort so that they are either using a regular browser that has specifically had JavaScript turned off because it creates problems for them OR their disability requires that they use a browser that doesn’t support JavaScript at all.

Then there are those using text only browsers that don’t support CSS, JavaScript or images and simply display the page content and alt text.

There are lots of groups like these which may only be a small fraction of 1% each but which between them certainly add up to at least 2 or 3% of web users. I can’t imagine that there will ever be a time when less than 2.5% of web users have JavaScript completely disabled or not supported by their special browser.

As I have said in a couple of other threads, I am seriously considering turning JavaScript off for this site because some of the scripts are broken and make it extremely difficult to do some things…