Я пытаюсь создать контактную форму PHP, используя PHP и jQuery Validate.min.js ( http://jqueryvalidation.org/ )
Я пытался вытащить все коды, которые мне нужны как для jQuery, так и для PHP, но по какой-то причине его возвращающие значения в верхней части.
Смотрите мои коды ниже:
<?php $hasError = false; $sent = false; if(issent($_POST['submitform'])){ $name = trim(htmlspecialchars($_POST['name'], ENT_QUOTES)); $email = trim($_POST['email']); $message = trim(htmlspecialchars($_POST['message'], ENT_QUOTES)); $fieldsArray = array( 'name' => $name, 'email' => $email, 'message' => $message ); $errorArray = array(); foreach($fieldsArray as $key => $val){ switch ($key){ case 'name': case 'message': if(empty($val)){ $hasError = true; $errorArray[$key] = ucfirst($key) = " field was left empty."; } break; case 'email': if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ $hasError = true; $errorArray[$key] = "Invalid Email Address entered"; }else{ $email = filter_var($email, FILTER_SANITIZE_EMAIL); } break; } } if($hasError !== true){ $to = "samuelnico.norton@gmail.com"; $subject = "Message from Contact Form"; $msgcontents = "Name: $name<br/> Email : $email<br/> Message: $message"; $headers = "MIME-Version: 1.0 \r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1 \r\n"; $headers .= "From: $name <$email> \r\n"; $mailsent = mail($to, $subject, $msgcontents, $headers); if($mailsent){ $sent = true; unset($name); unset($email); unset($message); } } } ?> <!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=no"> <!-- Page title --> <title>TEST FILE</title> <!-- Styles --> <link rel="stylesheet" href="css/slides.css" name="main-styles"> <!-- Scripts --> <script src="http://code.jquery.com/jquery-1.11.3.min.js" name="jquery"></script> <script src="js/plugins.js" type="text/javascript" name="plugins"></script> <script src="js/slides.js" type="text/javascript" name="main-scripts"></script> <!-- Added Script for Contact Form --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js" type="text/javascript" name="main-scripts"></script> <script type = "text/javascript"> jQuery(document).ready(function($) { $("#contactform").validate { rules: { name: { required: true, minlength: 2 }, email: { required: true, email: true }, message { required: true, minlength: 50 } }, messages: { name: { required: "Please enter your name", minlength: "Your name seems a bit short doesn't it?" }, email: { required: "Please enter your email address", email: "Please enter a valid email address" }, message { required: "Please enter your message", minlength: "Your message seems a bit short doesn't it? Please enter atleast 50 characters" } } }); }); </script> </head> <body class="slides animated"> <!-- Sidebar --> <nav class="sidebar deepPurple" data-sidebar-id="1"> <div class="close"><svg><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#close"></use></svg></div> <div class="content"> <a href="#" class="logo"><svg width="120" height="50"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#logo"></use></svg></a> <ul class="mainMenu uppercase"> <li><a href="#">Tour</a></li> <li><a href="#">Upgrade</a></li> <li><a href="#">Help</a></li> <li><a href="#">Explore</a></li> </ul> <ul class="social"> <li><a href="#"><svg><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#twitter"></use></svg></a></li> <li><a href="#"><svg><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#facebook"></use></svg></a></li> <li><a href="#"><svg><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#googlePlus"></use></svg></a></li> <li><a href="#"><svg><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#pinterest"></use></svg></a></li> </ul> </div> </nav> <!-- Slide #55 --> <section class="slide fade kenBurns"> <div class="content"> <div class="container"> <div class="wrap"> <div class="fix-6-12 box-55"> <div class="pad shadow selected ae-3"> <form class="wide center" id="contactform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" novalidate> <?php if($sent === true){ echo "<h2 class='success'> Thanks, your message has been sent successfully</h2>"; } elseif($hasError === true){ echo '<ul clas="errorlist">'; foreach($errorArray as $key => $val){ echo "<li>". ucfirst($key). " field error - $val</li>"; } echo '</ul>'; } ?> <label class="uppercase ae-4" for="name37">Your name</label> <input class="stroke round ae-5 wide" id="name37" type="name" name="name" value="<?php echo (isset($name) ? $name : ""); ?>" placeholder="Name" required/> <label class="uppercase ae-6" for="email37">Email</label> <input class="stroke round ae-7 wide" id="email37" type="email" name="email" value="<?php echo (isset($email) ? $email : ""); ?>" placeholder="Email" required/> <label class="uppercase ae-8" for="message37">Message</label> <textarea class="stroke round left ae-9 sourceSans" id="message37" type="email" placeholder="Message" required><?php echo (isset($message) ? $message : ""); ?></textarea> <input class="button wide pink round uppercase ae-10 button-55" type="submit" value="Send message" name="submitform"/> </form> </div> </div> </div> </div> </div> </section> </body> </html>
Как вы можете видеть, я вытащил коды в верхней части моего html-файла. Теперь я хочу показать ошибки ниже каждого текстового поля.
Вы можете увидеть, как это происходит: http://snowboardflowbindings.com/testing/testfile.php
Неустранимая ошибка: нельзя использовать возвращаемое значение функции в контексте записи в /home/olymnews/public_html/snowboardflowbindings.com/testing/testfile.php в строке 25
У вас есть что-то не так из таких вещей, как issent()
в вашем php, чтобы отсутствовать ()
и :
в вашем jQuery … Попробуйте разбить свой код на более управляемые части и попытаться сохранить столько логики, сколько вы можете отделить от Посмотреть:
<?php function validate_input($var = false,$opt = false) { $var = trim($var, ENT_QUOTES); return ($opt != 'email')? htmlspecialchars($var) : filter_var($var, FILTER_VALIDATE_EMAIL); } function error_codes($code = false) { $valid['name'] = "Enter your name"; $valid['subject'] = "Write a subject"; $valid['email'] = "Invalid email"; $valid['message'] = "Write your comments"; return (isset($valid[$code]))? $valid[$code] : false; } function send_email($settings = false) { $to = (!empty($settings['to']))? $settings['to']:false; $from = (!empty($settings['from']))? "From:".$settings['from'].PHP_EOL:"no-replay@test.com"; $subject = (!empty($settings['subject']))? $settings['subject']:"This is a great subject"; $message = (!empty($settings['message']))? $settings['message']:false; $headers = (!empty($settings['headers']))? $settings['headers']:false; if(in_array(false, $settings) === true) return false; return (mail($to,$subject,$message,$headers)); } // ISSET not ISSENT if(isset($_POST['submitform'])){ $payload['name'] = validate_input($_POST['name']); $payload['email'] = validate_input($_POST['email'],'email'); $payload['message'] = validate_input($_POST['message']); print_r($payload); print_r($_POST); if(in_array(false,$payload) === true) { foreach($payload as $key => $err) $errors[$key] = error_codes($key); } if(empty($errors)){ $to = "samuelnico.norton@gmail.com"; $subject = "Message from Contact Form"; $msgcontents = "Name: ".$payload['name']."<br/> Email : ".$payload['email']."<br/> Message: ".$payload['message']; $headers = "MIME-Version: 1.0 \r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1 \r\n"; $headers .= "From: ".$payload['name']." <".$payload['email']."> \r\n"; $success = (send_email(array("to"=>$to,"subject"=>$subject,"message"=>$msgcontents, "headers"=>$headers))); } } print_r($errors); ?><!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=no"> <!-- Page title --> <title>TEST FILE</title> <!-- Styles --> <link rel="stylesheet" href="css/slides.css" name="main-styles"> <!-- Scripts --> <script src="http://code.jquery.com/jquery-1.11.3.min.js" name="jquery"></script> <script src="js/plugins.js" type="text/javascript" name="plugins"></script> <script src="js/slides.js" type="text/javascript" name="main-scripts"></script> <!-- Added Script for Contact Form --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js" type="text/javascript" name="main-scripts"></script> <script type = "text/javascript"> jQuery(document).ready(function($) { $("#contactform").validate({ rules: { name: { required: true, minlength: 2 }, email: { required: true, email: true }, message: { required: true, minlength: 50 } }, messages: { name: { required: "Please enter your name", minlength: "Your name seems a bit short doesn't it?" }, email: { required: "Please enter your email address", email: "Please enter a valid email address" }, message: { required: "Please enter your message", minlength: "Your message seems a bit short doesn't it? Please enter atleast 50 characters" } } }); }); </script> </head> <body class="slides animated"> <!-- Sidebar --> <nav class="sidebar deepPurple" data-sidebar-id="1"> <div class="close"> <svg> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#close"></use> </svg> </div> <div class="content"> <a href="#" class="logo"> <svg width="120" height="50"> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#logo"></use> </svg> </a> <ul class="mainMenu uppercase"> <li><a href="#">Tour</a></li> <li><a href="#">Upgrade</a></li> <li><a href="#">Help</a></li> <li><a href="#">Explore</a></li> </ul> <ul class="social"> <li><a href="#"> <svg> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#twitter"></use> </svg> </a> </li> <li><a href="#"> <svg> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#facebook"></use> </svg> </a> </li> <li><a href="#"> <svg> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#googlePlus"></use> </svg> </a> </li> <li><a href="#"> <svg> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#pinterest"></use> </svg> </a> </li> </ul> </div> </nav> <!-- Slide #55 --> <section class="slide fade kenBurns"> <div class="content"> <div class="container"> <div class="wrap"> <div class="fix-6-12 box-55"> <div class="pad shadow selected ae-3"> <?php if(empty($success)) { ?> <form class="wide center" id="contactform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" novalidate> <?php if(!empty($success)) echo "<h2 class='success'> Thanks, your message has been sent successfully</h2>"; if(!empty($errors)) { echo '<ul clas="errorlist">'; echo "<li>".implode("</li>".PHP_EOL."<li>",$errors)."</li>"; echo '</ul>'; } ?> <label class="uppercase ae-4" for="name37">Your name</label> <input class="stroke round ae-5 wide" id="name37" type="name" name="name" value="" placeholder="Name" required/> <label class="uppercase ae-6" for="email37">Email</label> <input class="stroke round ae-7 wide" id="email37" type="email" name="email" value="" placeholder="Email" required/> <label class="uppercase ae-8" for="message37">Message</label> <textarea class="stroke round left ae-9 sourceSans" id="message37" placeholder="Message" name="message" required></textarea> <input class="button wide pink round uppercase ae-10 button-55" type="submit" value="Send message" name="submitform"/> </form> <?php } else { ?> SENT! <?php } ?> </div> </div> </div> </div> </div> </section> </body> </html>