2017-09-26 12 views
0

私のSQLデータベースにリンクしている投稿フォームフォームをAJAX経由で同じページに表示します。私はW3Cの学校といくつかのステップバイステップガイドを試しましたが、まだ苦労しています。これまでは、HTML for and Validationを作成し、SQLデータベースに接続しました。しかし、私は次のステップが何であるかはわかりません。私は...あなたは$コメント、$名など入れて、また、あなたのデータベース名、パスワード、およびデータベーステーブルを設定私のSQLデータベースにリンクしているフォーム(連絡フォーム)を送信し、AJAX経由で同じページのメッセージを送信フォームに置き換えます。

<?php 
// define variables and set to empty values 
$nameErr = $emailErr = $phoneErr = ""; 
$name = $email = $phone = $comment = ""; 

if ($_SERVER["REQUEST_METHOD"] == "POST") { 
    if (empty($_POST["name"])) { 
    $nameErr = "Name is required"; 
    } else { 
    $name = test_input($_POST["name"]); 
    // check if name only contains letters and whitespace 
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) { 
     $nameErr = "Only letters and white space allowed"; 
    } 
    } 

    if (empty($_POST["email"])) { 
    $emailErr = "Email is required"; 
    } else { 
    $email = test_input($_POST["email"]); 
    // check if e-mail address is well-formed 
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
     $emailErr = "Invalid email format"; 
    } 
    } 
    if (empty($_POST["phone"])) { 
    $phoneErr = "Telephone is required"; 
    } else { 
    $phone = test_input($_POST["phone"]); 
    } 

    if (empty($_POST["comment"])) { 
    $comment = ""; 
    } else { 
    $comment = test_input($_POST["comment"]); 
    } 

} 

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

?> 

<div id="form"> 
<form method="post" action="<?php echo htmlspecialchars($_SERVER["register.php"])?>"> 
    <fieldset> 
    Name: <input type="text" name="name" value="<?php echo $name;?>"> 
    <span class="error">* <?php echo $nameErr;?></span> 
    <br><br> 
    E-mail: <input type="text" name="email" value="<?php echo $email;?>"> 
    <span class="error">* <?php echo $emailErr;?></span> 
    <br><br> 
    Phone: <input type="tel" name="phone" value="<?php echo $phone;?>"> 
    <span class="error">* <?php echo $phoneErr;?></span> 
    <br><br> 
    Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea> 
    <br><br> 
    <button type="submit"> Submit</button> 
    </fieldset> 
</form> 
</div> 
+2

あなたのajaxコードはどこですか? –

答えて

0
$servername = "localhost"; 
$username = "username"; 
$password = "password"; 
$dbname = "myDB"; 
// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection 
if ($conn->connect_error){ 
    die("Connection failed:".$conn->connect_error); 
} 
$sql = "INSERT INTO MyGuests (name, email, phonenumber,comment) 
VALUES ($name , $email ,$phone,$comment)"; 
if ($conn->query($sql) === TRUE) { 
    echo "New record created successfully"; 
} else { 
    echo "Error: ".$sql."<br>".$conn->error; 
} 
$conn->close(); 

次に何をすべきかわからコーディングせずに新たなんです。

0

私はこのように、単純にそれを行います。

は、フォームのフィールドセットの前に空のdivを作成します。メールが送信され

このようなPHPの印刷メッセージで
<div class="col-xs-12 col-sm-9 col-md-8 col-lg-8 conForm"> 
     <h4>Shoot a message!</h4> 
     **<div id="message"></div>** 
     <form method="post" action="php/contact.php" name="cform" id="cform"> 
      <input name="name" id="name" type="text" class="col-xs-12 col-sm-6 col-md-6 col-lg-6" placeholder="Your name..." > 
      <input name="email" id="email" type="email" class=" col-xs-12 col-sm-6 col-md-6 col-lg-6 noMarr" placeholder="Your email..." > 
      <textarea name="comments" id="comments" cols="" rows="" class="col-xs-12 col-sm-12 col-md-12 col-lg-12" placeholder="Your message..."></textarea> 
      <input type="submit" id="submit" name="submit" class="submitBnt" value="Send message"> 
      <div id="simple-msg"></div> 
     </form> 
     </div> 

後:あなたのよう

if(mail($address, $e_subject, $msg, $headers)) { 

    // Email has sent successfully, echo a success page. 

    echo "<fieldset>"; 
    echo "<div id='success_page'>"; 
    echo "<h3>Email Sent Successfully.</h3>"; 
    echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>"; 
    echo "</div>"; 
    echo "</fieldset>"; 

} else { 

    echo 'ERROR!'; 

} 
0

尋ねられた、私はあなたがコーディングworld.soで全く新しいと思うので、私は1ページに完全なコードを書く。 .PHPファイルを作成し、このコードをあなたのデータベースに

<html> 
<head> 
    <script type="text/javascript"> 
    function validateName() { 
    var name = document.getElementById('contact-name').value; 
    if(name.length == 0) { 
    producePrompt('Name is required', 'name-error' , 'red') 
    return false; } 
    if (!name.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) { 
    producePrompt('First and last name, please.','name-error', 'red'); 
    return false; } 
    producePrompt('Valid', 'name-error', 'green'); 
    return true;} 

function validatePhone() { 
    var phone = document.getElementById('contact-phone').value; 
    if(phone.length == 0) { 
     producePrompt('Phone number is required.', 'phone-error', 'red'); 
     return false; } 
    if(phone.length != 10) { 
     producePrompt('Include area code.', 'phone-error', 'red'); 
     return false; } 
    if(!phone.match(/^[0-9]{10}$/)) { 
     producePrompt('Only digits, please.' ,'phone-error', 'red'); 
     return false; } 
    producePrompt('Valid', 'phone-error', 'green'); 
    return true;} 

function validateEmail() { 
    var email = document.getElementById('contact-email').value; 
    if(email.length == 0) { 
    producePrompt('Email Invalid','email-error', 'red'); 
    return false; } 
    if(!email.match(/^[A-Za-z\._\-[0-9]*[@][A-Za-z]*[\.][a-z]{2,4}$/)) { 
    producePrompt('Email Invalid', 'email-error', 'red'); 
    return false; } 
    producePrompt('Valid', 'email-error', 'green'); 
    return true;} 

function validateMessage() { 
    var message = document.getElementById('contact-message').value; 
    var required = 10; 
    var left = required - message.length; 
    if (left > 0) { 
    producePrompt(left + ' more characters required','message-error','red'); 
    return false; } 
    producePrompt('Valid', 'message-error', 'green'); 
    return true;} 

function validateForm() { 
    if (!validateName() || !validatePhone() || !validateEmail() || !validateMessage()) { 
    jsShow('submit-error'); 
    producePrompt('Please fix errors to submit.', 'submit-error', 'red'); 
    setTimeout(function(){jsHide('submit-error');}, 2000); 
     return false; } else { } 
} 

function jsShow(id) { 
    document.getElementById(id).style.display = 'block'; } 

function jsHide(id) { 
    document.getElementById(id).style.display = 'none';} 

function producePrompt(message, promptLocation, color) { 
    document.getElementById(promptLocation).innerHTML = message; 
    document.getElementById(promptLocation).style.color = color;} 
    </script> 
</head> 
<form action="" method="POST"> 
      <div class="form-group"> 
      <label for="contact-name">Name</label> 
      <input type="text" class="form-control" id="contact-name" name="name"  placeholder="Enter your name.." onkeyup='validateName()'> 
      <span class='error-message' id='name-error'></span> 
      </div> 

      <div class="form-group"> 
      <label for="contact-phone">Phone Number</label> 
      <input type="tel" class="form-control" id="contact-phone" name="phone" placeholder="Ex: 1231231234" onkeyup='validatePhone()'> 
      <span class='error-message' id='phone-error'></span> 
      </div> 

      <div class="form-group"> 
      <label for="contact-email">Email address</label> 
      <input type="email" class="form-control" id="contact-email" name="email" placeholder="Enter Email" onkeyup='validateEmail()'> 
      <span class='error-message' id='email-error'></span> 
      </div> 

      <div class="form-group"> 
      <label for='contactMessage'>Your Message</label> 
      <textarea class="form-control" rows="5" id='contact-message' name='message' placeholder="Enter a brief message" onkeyup='validateMessage()'></textarea> 
      <span class='error-message' id='message-error'></span> 
      </div> 

     <button onclick='return validateForm()' name="submit" value="submit" class="btn btn-default">Submit</button> 
     <span class='error-message' id='submit-error'></span> 
     <span class='success-message' id='submit-success'></span> 

<?php 
if (isset($_POST['submit']) && (!empty($_POST['submit']))) { 

$servername = "localhost"; 
$username = "root"; //change this to your username 
$password = ""; //change this to your database password 
$dbname = "db"; //change this to your database name 
$name = "$_POST[name]"; 
$phone = "$_POST[phone]"; 
$email = "$_POST[email]"; 
$message = "$_POST[message]"; 

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection 
if ($conn->connect_error){ 
    die("Connection failed:".$conn->connect_error);} 
//insert data into table named guestbook 
$sql = "INSERT INTO guestbook (name, email, phone, message) VALUES ('$name', '$email', '$phone', '$message')"; 
if ($conn->query($sql) === TRUE) { 
    echo "<br/><font color=green>Your Comment Successfully Sent</font>"; 
} else { 
    echo "Error updating record: " . $conn->error; } 
$conn->close();} 
?> 
</form> 
</body> 
</html> 

を貼り付ける、という名前が、=「」PHPファイル$ DBNAMEに変更することを忘れていけないものは何でもデータベースを作成します。これらのコードを使用してテーブルを作成してください:

CREATE TABLE guestbook 
(
id int NOT NULL AUTO_INCREMENT, 
name varchar(255), 
email varchar(255), 
phone varchar(255), 
message varchar(255), 
PRIMARY KEY (id) 
); 
関連する問題