Jump to content

Recommended Posts

Hello.

A couple of weeks ago I concluded a couple of front end development courses and we only touched upon php coding. Since we didn't do much of it I used w3schools.com to learn some basics. I used the tutorial to make a contact form but I have a little problem. Currently the form is set (or rather was until I removed some code) to show anything that was entered in to the form on the site (basically like in this tutorial: https://www.w3schools.com/php/php_forms.asp). What I want the form to do is send the entered information to a predefined email address. But that's not all. It's going to be used on a singlepage website layout. I want the form to also show a prompt box that warns the user that either something went wrong or that the message was sent and reload the page back to the same position (I realise I need to use index#pageposition to do this but I don't know how to implement the link).

Currently this only warns the user of what he did wrong (but not in a prompt box that something wrong happened) and reloads the page to the top. I'm a PHP noob (big noob), and I would appreciate if someone can help me out with this. Thank you :).

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Vpiši ime!";
  } else {
    $name = test_input($_POST["name"]);
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
          $nameErr = "Dovoljene so samo črke in presledki!"; 
        }
  }
  
  if (empty($_POST["email"])) {
    $emailErr = "Vpiši email naslov!";
  } else {
    $email = test_input($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Vpišite veljaven email naslov!"; 
        }
  }
    
  if (empty($_POST["subject"])) {
    $subjectErr = "Vpiši naslov sporočila!";
  } else {
    $subject = test_input($_POST["subject"]);
  }

  if (empty($_POST["message"])) {
    $messageErr = "Vpiši sporočilo!";
  } else {
    $message = test_input($_POST["message"]);
  }
    
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

?>

<!DOCTYPE html>

<html>

        <link rel="stylesheet" href="style.css" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
        <meta name="kontakt">

<head>


</head>

<body>

        <div class="col-md-12">

                <div class="form-area">  
                    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                    <br style="clear:both">
                                <h3>Piši nam</h3>
                                <div class="form-group">
                                    <input type="text" class="form-control" name="name" placeholder="Ime">
                                    <span class="error">* <?php echo $nameErr;?></span>
                                </div>
                                <div class="form-group">
                                    <input type="text" class="form-control" name="email" placeholder="Email">
                                    <span class="error">* <?php echo $emailErr;?></span>
                                </div>
                                <div class="form-group">
                                    <input type="text" class="form-control" name="subject" placeholder="Naslov">
                                    <span class="error">* <?php echo $subjectErr;?></span>
                                </div>
                                <div class="form-group">
                                    <textarea class="form-control" type="textarea" placeholder="Sporočilo" name=message rows="8"></textarea>
                                    <span class="error">* <?php echo $messageErr;?></span>
                                </div>

                        <input type="submit" class="btn btn-primary" name="submit" value="Submit">  

                    <!--<button type="button" name="submit" class="btn btn-primary pull-right" value="Submit">Pošlji</button>-->
                    </form>
                </div>

        </div> 

</body>

 

Link to post
Share on other sites

May I suggest that you limit your issues to one at a time and only post the code necessary to illustrate the particular issue in question.

It would greatly encourage other users to respond to your questions -- well, at least me, at any rate.

I do not want to pretend to speak for everyone.

Roddy

 

Link to post
Share on other sites

If you want the form error handling to be smooth and user friendly, isuggest you use javascript/ajax  check this js/ajax .

for the mailing part check this : https://www.w3schools.com/php/func_mail_mail.asp .(if you are working on a local environement the mail will probably fail,you would have to tweek your php.ini but still the email received might be considered as spam) .

Good luck.

Link to post
Share on other sites

you can split the page into 2 pages for example

index.php :

<!DOCTYPE html>

<html>

        <link rel="stylesheet" href="style.css" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
        <meta name="kontakt">
		

<head>


</head>

<body>

        <div class="col-md-12">

                <div class="form-area">  
				<div id="error" style="color:#FF6633"></div>
                    <form method="post" action="#" onsubmit="sendmail()">
                    <br style="clear:both">
                                <h3>Piši nam</h3>
                                <div class="form-group">
                                    <input type="text" class="form-control" name="fname" placeholder="Ime" id="idname">
                                    <span class="error">* </span>
                                </div>
                                <div class="form-group">
                                    <input type="text" class="form-control" name="email" placeholder="Email" id="idemail">
                                    <span class="error">* </span>
                                </div>
                                <div class="form-group">
                                    <input type="text" class="form-control" name="subject" placeholder="Naslov" id="idsubject">
                                    <span class="error">* </span>
                                </div>
                                <div class="form-group">
                                    <textarea class="form-control" type="textarea" placeholder="Sporočilo" id="idmessage" name="message" rows="8"></textarea>
                                    <span class="error">* </span>
                                </div>

                        <input type="submit" class="btn btn-primary" name="submit" value="Submit">  

                    <!--<button type="button" name="submit" class="btn btn-primary pull-right" value="Submit">Pošlji</button>-->
                    </form>
                </div>

        </div> 
<script>
		document.getElementById("error").display="none";
		function sendmail()
		{
		 event.preventDefault();
		 fname=document.getElementById("idname").value;
		 email=document.getElementById("idemail").value;
		 subject=document.getElementById("idsubject").value;
		 message=document.getElementById("idmessage").value;
		 //alert(fname);
		 
		  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

						
					 	document.getElementById("error").innerHTML = this.responseText;
						
						

			
					  	 
					
    }
  };
  xhttp.open("POST", "./verify.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("fname=" + fname + "&email=" + email + "&subject=" + subject +"&message=" + message);
		 
		 
		}
		</script>
</body>
</html>

and a seconf page that handles the the inputs for eg : verify.php

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["fname"])) {
    echo "Vpiši ime!";
	die();
  } else {
    $name = test_input($_POST["fname"]);
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
          echo "Dovoljene so samo črke in presledki!"; 
		  die();
        }
  }
  
  if (empty($_POST["email"])) {
    echo "Vpiši email naslov!";
	die();
  } else {
    $email = test_input($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Vpišite veljaven email naslov!"; 
		die();
        }
  }
    
  if (empty($_POST["subject"])) {
    echo "Vpiši naslov sporočila!";
	die();
  } else {
    $subject = test_input($_POST["subject"]);
  }

  if (empty($_POST["message"])) {
    echo "Vpiši sporočilo!";
	die();
  } else {
    $message = test_input($_POST["message"]);
  }
    
	// email Stuff goes here here
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

?>

 

Link to post
Share on other sites
20 hours ago, john_jack said:

If you want the form error handling to be smooth and user friendly, isuggest you use javascript/ajax  check this js/ajax .

for the mailing part check this : https://www.w3schools.com/php/func_mail_mail.asp .(if you are working on a local environement the mail will probably fail,you would have to tweek your php.ini but still the email received might be considered as spam) .

Good luck.

Ok... I'll be honest, I didn't understand half of what you said :P. I don't have a php.ini. All I have is a single index.php site because it's a single page site that scrolls up and down. This contact form is the only missing piece. The site is located here: http://viki.si/demosites/postaniskavt/index.php

All I really understand up until now with php is how the form that I've created thus far is verified. I fail to understand how splitting the file in to 2 would make it function like it should. I understand that splitting the site in two would make it more menagable in the background but that's not really my concern for now. For now all I want is for the form that I've created up until now (with all the verification) to check if everything is entered correctly and send the email and send it only if everything is enetered correctly. I'll deal with the alert windows later when the form is functioning as it should. That's probably just a simple add on to the "if" statement anyway if I understand correctly. But I'm lost on how to form the if sentence to make the form check if every single information was entered correctly in to the form.

Link to post
Share on other sites

All PHP servers have an INI file which contains various settings and options, whether or not you have access to that file.  If you don't have access to that file there are still several options you can change other ways:

http://php.net/manual/en/configuration.php

As far as handling the form, you should really look into using ajax to submit the form information so that the entire page doesn't need to refresh when they submit the form.  With a 1-page site like that, people would probably not expect the entire thing to refresh when they submit the form.  If you want to go that route then you'll need to use Javascript to gather the form data and send an ajax request to PHP to validate and send the email.  That PHP script would be a different file than your index page, its only job would be to validate and send the email, and return any success or error messages back to Javascript.  That's the example that was shown above, one page with the HTML form and some Javascript to handle it, and a PHP script with the code to validate and process the form.

Regardless of which path you decide to do, I would recommend using something like PHPMailer instead of the built-in mail function.

Link to post
Share on other sites
On 4. 4. 2017 at 8:55 PM, justsomeguy said:

All PHP servers have an INI file which contains various settings and options, whether or not you have access to that file.  If you don't have access to that file there are still several options you can change other ways:

http://php.net/manual/en/configuration.php

As far as handling the form, you should really look into using ajax to submit the form information so that the entire page doesn't need to refresh when they submit the form.  With a 1-page site like that, people would probably not expect the entire thing to refresh when they submit the form.  If you want to go that route then you'll need to use Javascript to gather the form data and send an ajax request to PHP to validate and send the email.  That PHP script would be a different file than your index page, its only job would be to validate and send the email, and return any success or error messages back to Javascript.  That's the example that was shown above, one page with the HTML form and some Javascript to handle it, and a PHP script with the code to validate and process the form.

Regardless of which path you decide to do, I would recommend using something like PHPMailer instead of the built-in mail function.

Thanks for the info. I'll look in to PHP mailer and maybe take a look at some tutorials.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...