1

i'm coding my very first own website. there is a section where you can enter your name, mail and a message to me. by clicking "send message" the message should be sent to my personal mail. the website visitor should receive an alert via a pop-up "message has been sent successfully" or sth like that. sadly, when clicking "send message" an additional website is opened stating "failed to sent message". any help is MUCHLY appreciated.

html:

<form action="untitled.php" method="post" target="self">
      <p><input class="w3-input w3-border" type="text" id="name" name="name" placeholder="Name" required name="Name"></p>
      <p><input class="w3-input w3-border" type="email" id="email" name="email" placeholder="Email" required name="Email"></p>
      <p><textarea id="message" type="text" name="message" required placeholder="Message" rows="6" cols="30" ></textarea>
      </p>

        <button class="w3-button w3-black" type="submit" name="submit" value="submit">
          <i class="fa fa-paper-plane"></i> Sende Nachricht
        </button>
      </p>
    </form>

php: code

<?php
$posted = false;
if( $_POST ) {
    $posted = true;

    $to = 'xx@gmail.com';

    $name = $_POST['name'];
    $mail_from = $_POST['email'];
    $subject = 'Message sent from website';
    $message = $_POST['message'];

    $header = "From: $name <$mail_from>";

    $result = $_POST['name'] == "danny"; // Dummy result
}
?>

   <html>
   <head></head>
  <body>

 <?php
if( $posted ) {
    if( $result )
        echo "<script type='text/javascript'>alert('submitted    successfully!')</script>";
    else
        echo "<script type='text/javascript'>alert('failed!')         </script>";
}
?>
  <form action="" method="post">
  Name:<input type="text" id="name" name="name"/>
   <input type="submit" value="submit" name="submit"/>
 </form>
 </body>
  </html>

2 Answers2

1

Welcome to stackoverflow :) i Tested your formula below(you can click run) and seems it works, but you need the untitled.php for it or you can rename it to email.php to make it more specific that email.php is a code only to send email :)

inside email.php(currently untitled.php) please have a look this thread How to send an email using PHP?

or copy paste this code to email.php(currently untitled.php)

<?php
$to      = 'myemail@mail.com'; //your email
$subject = 'from my website  - email form'; 
$message = $_POST['message'];
$headers = 'From: '.$_POST['email']. "\r\n" .
    'Reply-To: myemail@mail.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>  

//thank you message
<div>Thanks for your message, I'll answer your email as soon as i can. best regards <a href="/">back &raquo;</a></div>

<form action="untitled.php" method="post" target="self">
      <p><input class="w3-input w3-border" type="text" id="name" name="name" placeholder="Name" required name="Name"></p>
      <p><input class="w3-input w3-border" type="email" id="email" name="email" placeholder="Email" required name="Email"></p>
      <p><textarea id="message" type="text" name="message" required placeholder="Message" rows="6" cols="30" ></textarea>
      </p>

        <button class="w3-button w3-black" type="submit" name="submit" value="submit">
          <i class="fa fa-paper-plane"></i> Sende Nachricht
        </button>
      </p>
    </form>
  • Hi, thank you very much. I implemented your code - it works, but after clicking "send message" button a blank site is opened. my goal is, to have a pop up after hitting the button saying that the message has been sent – user7618897 Feb 13 '19 at 09:29
  • @user7618897 See my comment on ur Q. `target` is set to a named window, thus a new window/tab is opened. You do not need any target so stay in `_self`. If you do not want to reload the page at all, use AJAX to post data, e.g. [jQuery](http://api.jquery.com/jquery.ajax/) intercepting the form's `submit` event. – Pinke Helga Feb 13 '19 at 09:32
  • Okay, thank you. I am a bloody beginner, sorry about that. Where do i have to implement the jQuery.ajax( url [, settings ] ) code? – user7618897 Feb 13 '19 at 09:40
  • @user7618897 `$(()=>{ $('#form-id').on('submit', ev=>{ev.preventDefault(); /*send ajax here*/ }); });` The outer `$();` function is just wrapping the `DOMContentLoaded` event, jQuery's default shorthand. I.e. when the page has been loaded, add an event listener to the form. You have to set the `id="form-id"` accordingly of course. To be more generic, see also https://developer.mozilla.org/en-US/docs/Web/API/FormData (but not stringently required) – Pinke Helga Feb 13 '19 at 09:51
  • @user7618897 If you do not achieve your goals using jquery properly on your own, your are welcome to open a new properly formed jquery question showing your code progress. – Pinke Helga Feb 13 '19 at 09:58
  • @user7618897 you need a javascript which is a bit advanced level :S but i guess you can find the simplier one... same when i started 9 years ago :P i wont really rush you to learn javascript/jquery or at the end :S would take time to learn many things at once...but i can suggest so it works today. – Joe Lorthemier Rauzes Feb 13 '19 at 10:00
  • im trying to figure it out right now :D stumbling through the w3schools introduction to jquery. thats my progress so far LOL: $("submit").click(function(){ if(statusTxt == "success") alert("External content loaded successfully!"); if(statusTxt == "error") alert("Error: " + xhr.status + ": " + xhr.statusText); }); }); – user7618897 Feb 13 '19 at 10:06
  • @JoeYdoanRauzes Jumping the into cold water doing things properly from the beginning isn't as bad as one might think since it avoids forming bad habits. With no advice it is hard to find the correct way, however, with some advise to the resources and docs it's a steep but manageable lerning curve. – Pinke Helga Feb 13 '19 at 10:06
  • i added a thank you message whilst you are trying javascript popup, please look above :) – Joe Lorthemier Rauzes Feb 13 '19 at 10:07
  • @Quasimodo'sclone agree, but when i started things learning my own.. i was totally lost what is server side and client side :( no stackoverflow back then :S, i started from software developer to web... its tricky... – Joe Lorthemier Rauzes Feb 13 '19 at 10:10
  • @JoeYdoanRauzes They will beat us due to chatting :D ... I started in the 80ies with TurboPascal compiling CGI programs, later Perl, and early JavaScript was a real pain making things bloated and very slow. However, I never confused server/client side since it's very intuitive. Ok, I started 11 years old and the computer has been my living room since those days. Client-side scripts were very innovative and even first images could be included into the text pages. Yahoo, the primary search engine, had the browser default black on silver look with red links. All on superior downstream of 300 bps – Pinke Helga Feb 13 '19 at 10:41
  • @Quasimodo'sclone haha you are right.. exempt me tho, i'm originally from the philippines.. we hardly afford to buy computer :(.. luckily bank accepted me(still cant afford to buy pc with 500 euro/ salary computer was soooo expensive back then lol) and luckily got hired here in Germany. :D i hated javascript before, now i love it :S – Joe Lorthemier Rauzes Feb 13 '19 at 10:47
  • Hey you're in Germany? Do you speak German? We should find some chatroom where we could better talk. – Pinke Helga Feb 13 '19 at 10:50
  • @Quasimodo'sclone natürlich :).. yes i speak german everyday with my work mates. :) and hi from Düsseldorf... love you all guys... for rep :( craving for it.. i actually thought the whole world hates me :( – Joe Lorthemier Rauzes Feb 13 '19 at 10:52
0

An example of how to do both methods - traditional form submission and ajax.

<?php

    ob_clean();
    $payload=array();

    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['submit'] ) ){

        /* for ajax & standard form submissions */
        $args=array(
            'name'      =>  FILTER_SANITIZE_STRING,
            'email'     =>  FILTER_SANITIZE_EMAIL,
            'message'   =>  FILTER_SANITIZE_STRING
        );
        $_POST=filter_input_array( INPUT_POST, $args );

        /* Have any additional fields been injected into the POST request? */
        foreach( $_POST as $field => $value ){
            if( !in_array( $field, array_keys( $args ) ) )exit( sprintf( 'unknown parameter "%s"', $field ) );
        }

        /* Are all the required fields in the POST array? */
        foreach( array_keys( $args ) as $field ){
            if( !in_array( $field, array_keys( $_POST ) ) )exit( sprintf('Empty or missing parameter "%s"',$field ) );
        }

        /* assign fields to variables */
        extract( $_POST );

        /* 
            check the validity of the email address - 
            doesn't actually determine if this is a genuine email though
        */
        $email = filter_var( $email, FILTER_VALIDATE_EMAIL );




        if( $email ){
            $to = 'xx@gmail.com';
            $from = $email;
            $subject = 'Message sent from website';
            $headers = sprintf( 'From: %s<%s>', $name, $email );

            $status=@mail( $to, $subject, $message, $headers );
            $payload['email']=$email;
            $payload['status']=$status;
            $payload['message']=$message;
            $payload['method']='FORM';
        }



        if( !empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && $_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest' ){
            header('Content-Type: application/json');
            $payload['method']='AJAX';
            exit( json_encode( $payload ) );
        }
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>PHP & Javascript - send email</title>
        <script>
            const ajax=function(url,params,callback){
                let xhr=new XMLHttpRequest();
                xhr.onload=function(){
                    if( this.status==200 && this.readyState==4 )callback.call( this, this.response )
                };
                xhr.onerror=function(e){
                    alert(e)
                };
                xhr.open( 'POST', url, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
                xhr.send( buildparams( params ) );
            };
            const buildparams=function(p){
                if( p && typeof( p )==='object' ){
                    p=Object.keys( p ).map(function( k ){
                        return typeof( p[ k ] )=='object' ? buildparams( p[ k ] ) : [ encodeURIComponent( k ), encodeURIComponent( p[ k ] ) ].join('=')
                    }).join('&');
                }
                return p;
            };



            document.addEventListener('DOMContentLoaded',function(){
                let bttn=document.querySelector('input[type="button"][name="ajax-submit"]');
                bttn.addEventListener( 'click', function(e){

                    let params={
                        submit:'submit',
                        name:document.querySelector('input[name="name"]').value,
                        email:document.querySelector('input[name="email"]').value,
                        message:document.querySelector('textarea[name="message"]').value
                    };
                    let callback=function(r){
                        let json=JSON.parse( r );
                        alert( r.status ? 'Yay - message sent!' : 'Boo - message sending failed' );
                        document.querySelector('form > pre').innerText=r;
                    };
                    ajax.call( this, location.href, params, callback )
                },false );
            },false );
        </script>
        <style>
            form{width:60%;padding:1rem;box-sizing:border-box;margin:2rem auto 0 auto;float:none;border:1px solid black}
            input,button{padding:1rem;margin:0.25rem auto}
            textarea{padding:1rem;width:100%;resize:none;margin:0.5rem auto}
            [type='text'], [type='email'], textarea{width:calc(100% - 2rem);}
            [type='button'], button{width:100%;}
            pre{width:100%;float:none;margin:auto;color:green;}
        </style>
    </head>
    <body>
        <form method='post'>
            <input class='w3-input w3-border' type='text' id='name' name='name' placeholder='Name' required name='Name'>
            <input class='w3-input w3-border' type='email' id='email' name='email' placeholder='Email' required name='Email'>
            <textarea id='message' type='text' name='message' required placeholder='Message' rows='6' cols='30' ></textarea>

            <button class='w3-button w3-black' type='submit' name='submit' value='submit'>
                <i class='fa fa-paper-plane'>Sende Nachricht</i>
            </button>

            <input type='button' name='ajax-submit' value='Send Email using ajax' />
            <?php
                if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $payload ) ){
                    printf('<pre>%s</pre>',print_r( $payload,true ) );
                } else {
                    echo '<pre></pre>';
                }
            ?>          
        </form>
    </body>
</html>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • thank you! that looks quite promising. i really appreciate you efforts. now i try figuring out which parts of the code relate to which method XD – user7618897 Feb 13 '19 at 10:44
  • i cant differentiate between both methods, lol. which part of the code is traditional - which one is ajax? plus is this safe/secured against php hacks? – user7618897 Feb 13 '19 at 11:03
  • the button with `Send Email using ajax` has the javascript event listener assigned to it. The event listener will send the ajax request. The other button will submit the form in the traditional manner - both send the POST request to the same place ( top of script in this case ) so either method can be processed by the same script. The ajax method of course means that the page will NOT reload and you can use the callback function to inform the user (alert,modal,siren etc etc ) It is tested to the point of actually sending the mail - my mailserver needs configuration changes just now – Professor Abronsius Feb 13 '19 at 11:31
  • when i tried to implement it, it opens a new page with the same name; email; message form and the two buttons as you described it. do i have to alter the code / delete the method i dont want to implement from the .php file to get it work? i noticed that you already coded the alert function + alert message when clicking submit button – user7618897 Feb 13 '19 at 11:44
  • I'd suggest copying the entire code, create a new php page and paste it all - save it and run in the browser... should work – Professor Abronsius Feb 13 '19 at 11:56
  • i did so. but still, opens a new page with the same exact form but two buttons below and code: "Array ( [email] => mal@gmail.com [status] => 1 [message] => de [method] => FORM) – user7618897 Feb 13 '19 at 12:35
  • What you see below the buttons is only for debugging - the `status=>1` suggests the mail was sent OK. It will not open a new page - it should be the same page - ajax will NOT reload the page but traditional `submit` will. – Professor Abronsius Feb 13 '19 at 13:56
  • it still doesnt work. how can i hide the debugging? i have 2 buttons on my webpage. the first is the traditional one, by clicking it, it will send a message AND opens a new site with the name;mail;send message form again. clicking send message via ajax - nothing happens – user7618897 Feb 13 '19 at 18:09
  • what I posted above is not intended to be the, excuse the phrase, "Final solution" - it shows how you CAN/COULD implement both methods. From your comments I supplied a mechanism that will work for either method ( form submit or ajax ) - edit to suit your needs but please dont say "it doesn't work" ~ if you want to hide the "debugging" messages then delete those portions of code – Professor Abronsius Feb 13 '19 at 19:19