1

誰かが私を助けてくれるのではないかと思います。

まず、これが非常に基本的な質問であると感じるかもしれない経験豊富な開発者に謝罪しますが、これは私の最初の試みですので、ご容赦ください.

しばらくの間、フォームの送信時に成功と失敗のメッセージを組み込んだ AJAX フォームの例を見つけようとしてきました。

この記事を見つけました。現在、データをmySQLデータベースに保存するように適応しようとしていますが、これを機能させるのに苦労しています。

チュートリアルには基本的に 2 つのファイルがあり、1 つは HTML フォーム、もう 1 つは PHP スクリプトです。

示されている例から HTML を変更していませんが、以下に投稿しました。

<!doctype html>
<html lang="en">
<head>

<title>A Slick Ajax Contact Form with jQuery and PHP</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">

<style type="text/css">


/* Add some margin to the page and set a default font and colour */

body {
  margin: 30px;
  font-family: "Georgia", serif;
  line-height: 1.8em;
  color: #333;
}


/* Set the content dimensions */

#content {
  width: 800px;
  padding: 50px;
  margin: 0 auto;
  display: block;
  font-size: 1.2em;
}

#content h2 {
  line-height: 1.5em;
}


/* Add curved borders to various elements */

#contactForm, .statusMessage, input[type="submit"], input[type="button"] {
  -moz-border-radius: 10px;
  -webkit-border-radius: 10px;  
  border-radius: 10px;
}


/* Style for the contact form and status messages */

#contactForm, .statusMessage {
  color: #666;
  background-color: #ebedf2;
  background: -webkit-gradient( linear, left bottom, left top, color-stop(0,#dfe1e5), color-stop(1, #ebedf2) );
  background: -moz-linear-gradient( center bottom, #dfe1e5 0%, #ebedf2 100% );  
  border: 1px solid #aaa;
  -moz-box-shadow: 0 0 1em rgba(0, 0, 0, .5);
  -webkit-box-shadow: 0 0 1em rgba(0, 0, 0, .5);
  box-shadow: 0 0 1em rgba(0, 0, 0, .5);
  opacity: .95;
}


/* The form dimensions */

#contactForm {
  width: 40em;
  height: 33em;
  padding: 0 1.5em 1.5em 1.5em;
  margin: 0 auto;
}


/* Position the form in the middle of the window (if JavaScript is enabled) */

#contactForm.positioned {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin-top: auto;
  margin-bottom: auto;
}


/* Dimensions and position of the status messages */

.statusMessage {
  display: none;
  margin: auto;
  width: 30em;
  height: 2em;
  padding: 1.5em;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

.statusMessage p {
  text-align: center;
  margin: 0;
  padding: 0;
}


/* The header at the top of the form */

#contactForm h2 {
  font-size: 2em;
  font-style: italic;
  letter-spacing: .05em;
  margin: 0 0 1em -.75em;
  padding: 1em;
  width: 19.5em;  
  color: #aeb6aa;
  background: #dfe0e5 url('images/stamp.jpg') no-repeat 15em -3em; /* http://morguefile.com/archive/display/606433 */
  border-bottom: 1px solid #aaa;
  -moz-border-radius: 10px 10px 0 0;
  -webkit-border-radius: 10px 10px 0 0;  
  border-radius: 10px 10px 0 0;
}


/* Give form elements consistent margin, padding and line height */

#contactForm ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

#contactForm ul li {
  margin: .9em 0 0 0;
  padding: 0;
}

#contactForm input, #contactForm label {
  line-height: 1em;
}


/* The field labels */

label {
  display: block;
  float: left;
  clear: left;
  text-align: right;
  width: 28%;
  padding: .4em 0 0 0;
  margin: .15em .5em 0 0;
  font-weight: bold;
}


/* The fields */

input, textarea {
  display: block;
  margin: 0;
  padding: .4em;
  width: 67%;
  font-family: "Georgia", serif;
  font-size: 1em;
  border: 1px solid #aaa;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;    
  border-radius: 5px;
  -moz-box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
  -webkit-box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
  box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
  background: #fff;
}

textarea {
  height: 13em;
  line-height: 1.5em;
  resize: none;
}


/* Place a border around focused fields, and hide the inner shadow */

#contactForm *:focus {
  border: 1px solid #66f;
  outline: none;
  box-shadow: none;
  -moz-box-shadow: none;
  -webkit-box-shadow: none;
}


/* Display correctly filled-in fields with a green background */

input:valid, textarea:valid {
  background: #dfd;
}


/* The Send and Cancel buttons */

input[type="submit"], input[type="button"] {
  float: right;
  margin: 2em 1em 0 1em;
  width: 10em;
  padding: .5em;
  border: 1px solid #666;
  -moz-border-radius: 10px;
  -webkit-border-radius: 10px;  
  border-radius: 10px;
  -moz-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
  -webkit-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
  box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
  color: #fff;
  background: #0a0;
  font-size: 1em;
  line-height: 1em;
  font-weight: bold;
  opacity: .7;
  -webkit-appearance: none;
  -moz-transition: opacity .5s;
  -webkit-transition: opacity .5s;
  -o-transition: opacity .5s;
  transition: opacity .5s;
}

input[type="submit"]:hover,
input[type="submit"]:active,
input[type="button"]:hover,
input[type="button"]:active {
  cursor: pointer;
  opacity: 1;
}

input[type="submit"]:active, input[type="button"]:active {
  color: #333;
  background: #eee;
  -moz-box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
  -webkit-box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
  box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
}

input[type="button"] {
  background: #f33;
}


/* Header/footer boxes */

.wideBox {
  clear: both;
  text-align: center;
  margin: 70px;
  padding: 10px;
  background: #ebedf2;
  border: 1px solid #333;
}

.wideBox h1 {
  font-weight: bold;
  margin: 20px;
  color: #666;
  font-size: 1.5em;
}

</style>

<!-- Some IE7 hacks and workarounds -->

<!--[if lt IE 8]>
<style>

/* IE7 needs the fields to be floated as well as the labels */

input, textarea {
  float: right;
}

#formButtons {
  clear: both;
}

/*
  IE7 needs an ickier approach to vertical/horizontal centring with fixed positioning.
  The negative margins are half the element's width/height.
*/

#contactForm.positioned, .statusMessage {
  left: 50%;
  top: 50%;
}

#contactForm.positioned {
  margin-left: -20em;
  margin-top: -16.5em;
}

.statusMessage {
  margin-left: -15em;
  margin-top: -1em;
}

</style>
<![endif]-->


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">

var messageDelay = 2000;  // How long to display status messages (in milliseconds)

// Init the form once the document is ready
$( init );


// Initialize the form

function init() {

  // Hide the form initially.
  // Make submitForm() the form's submit handler.
  // Position the form so it sits in the centre of the browser window.
  $('#contactForm').hide().submit( submitForm ).addClass( 'positioned' );

  // When the "Send us an email" link is clicked:
  // 1. Fade the content out
  // 2. Display the form
  // 3. Move focus to the first field
  // 4. Prevent the link being followed

  $('a[href="#contactForm"]').click( function() {
    $('#content').fadeTo( 'slow', .2 );
    $('#contactForm').fadeIn( 'slow', function() {
      $('#senderName').focus();
    } )

    return false;
  } );

  // When the "Cancel" button is clicked, close the form
  $('#cancel').click( function() { 
    $('#contactForm').fadeOut();
    $('#content').fadeTo( 'slow', 1 );
  } );  

  // When the "Escape" key is pressed, close the form
  $('#contactForm').keydown( function( event ) {
    if ( event.which == 27 ) {
      $('#contactForm').fadeOut();
      $('#content').fadeTo( 'slow', 1 );
    }
  } );

}


// Submit the form via Ajax

function submitForm() {
  var contactForm = $(this);

  // Are all the fields filled in?

  if ( !$('#senderName').val() || !$('#senderEmail').val() || !$('#message').val() ) {

    // No; display a warning message and return to the form
    $('#incompleteMessage').fadeIn().delay(messageDelay).fadeOut();
    contactForm.fadeOut().delay(messageDelay).fadeIn();

  } else {

    // Yes; submit the form to the PHP script via Ajax

    $('#sendingMessage').fadeIn();
    contactForm.fadeOut();

    $.ajax( {
      url: contactForm.attr( 'action' ) + "?ajax=true",
      type: contactForm.attr( 'method' ),
      data: contactForm.serialize(),
      success: submitFinished
    } );
  }

  // Prevent the default form submission occurring
  return false;
}


// Handle the Ajax response

function submitFinished( response ) {
  response = $.trim( response );
  $('#sendingMessage').fadeOut();

  if ( response == "success" ) {

    // Form submitted successfully:
    // 1. Display the success message
    // 2. Clear the form fields
    // 3. Fade the content back in

    $('#successMessage').fadeIn().delay(messageDelay).fadeOut();
    $('#senderName').val( "" );
    $('#senderEmail').val( "" );
    $('#message').val( "" );

    $('#content').delay(messageDelay+500).fadeTo( 'slow', 1 );

  } else {

    // Form submission failed: Display the failure message,
    // then redisplay the form
    $('#failureMessage').fadeIn().delay(messageDelay).fadeOut();
    $('#contactForm').delay(messageDelay+500).fadeIn();
  }
}

</script>

</head>
<body>

<div class="wideBox">
  <h1>A Slick Ajax Contact Form with jQuery and PHP</h1>
  <h2>Click one of the "Send us an email" links...</h2>
</div>

<div id="content">

  <p style="padding-bottom: 50px; font-weight: bold; text-align: center;"><a href="#contactForm">~ Send us an email ~</a></p>

  <h1>Aircraft and Submarines</h1>
  <h2>The Story of the Invention, Development, and Present-Day Uses of War's Newest Weapons</h2>
  <h3>By Willis J. Abbot</h3>
  <h4>Preface</h4>

  <img class="inline" style="width: 300px; height: 373px; float: left; margin-right: 20px;" src="images/fighting-by-sea-and-sky.jpg" alt="Fighting by Sea and Sky" />

  <p>Not since gunpowder was first employed in warfare has so
  revolutionary a contribution to the science of slaughtering men been
  made as by the perfection of aircraft and submarines. The former
  have had their first employment in this world-wide war of the
  nations. The latter, though in the experimental stage as far back as
  the American Revolution, have in this bitter contest been for the
  first time brought to so practical a stage of development as to
  exert a really appreciable influence on the outcome of the struggle.</p>

  <p>Comparatively few people appreciate how the thought of navigating
  the air's dizziest heights and the sea's gloomiest depths has
  obsessed the minds of inventors. From the earliest days of history
  men have grappled with the problem, yet it is only within two
  hundred years for aircraft and one hundred for submarines that any
  really intelligent start has been made upon its solution. The men
  who really gave practical effect to the vague theories which others
  set up&mdash;in aircraft the Wrights, Santos-Dumont, and Count Zeppelin;
  in submarines Lake and Holland&mdash;are either still living, or have
  died so recently that their memory is still fresh in the minds of
  all.</p>

  <p style="padding-top: 50px; font-weight: bold; text-align: center;"><a href="#contactForm">~ Send us an email ~</a></p>

</div>

<form id="contactForm" action="processForm.php" method="post">

  <h2>Send us an email...</h2>

  <ul>

    <li>
      <label for="senderName">Your Name</label>
      <input type="text" name="senderName" id="senderName" placeholder="Please type your name" required="required" maxlength="40" />
    </li>

    <li>
      <label for="senderEmail">Your Email Address</label>
      <input type="email" name="senderEmail" id="senderEmail" placeholder="Please type your email address" required="required" maxlength="50" />
    </li>

    <li>
      <label for="message" style="padding-top: .5em;">Your Message</label>
      <textarea name="message" id="message" placeholder="Please type your message" required="required" cols="80" rows="10" maxlength="10000"></textarea>
    </li>

  </ul>

  <div id="formButtons">
    <input type="submit" id="sendMessage" name="sendMessage" value="Send Email" />
    <input type="button" id="cancel" name="cancel" value="Cancel" />
  </div>

</form>

<div id="sendingMessage" class="statusMessage"><p>Sending your message. Please wait...</p></div>
<div id="successMessage" class="statusMessage"><p>Thanks for sending your message! We'll get back to you shortly.</p></div>
<div id="failureMessage" class="statusMessage"><p>There was a problem sending your message. Please try again.</p></div>
<div id="incompleteMessage" class="statusMessage"><p>Please complete all the fields in the form before sending.</p></div>

<div class="wideBox">
  <p>&copy; Elated.com | <a href="http://www.elated.com/articles/slick-ajax-contact-form-jquery-php/">Back to Tutorial</a></p>
  <p style="font-size: .8em; line-height: 1.5em;"><a rel="license" href="http://creativecommons.org/licenses/by/3.0/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/3.0/88x31.png" /></a><br />This <span xmlns:dc="http://purl.org/dc/elements/1.1/" href="http://purl.org/dc/dcmitype/Text" rel="dc:type">work</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="http://www.elated.com/" property="cc:attributionName" rel="cc:attributionURL">http://www.elated.com/</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 Unported License</a>.</p>
</div>

</body>
</html>

ただし、PHP スクリプトを次のように変更しました。

<?php

    include("admin/link.php");
    include("admin/opendb.php");

$senderName = isset( $_POST['senderName'] );
$senderEmail = isset( $_POST['senderEmail'] );
$message = isset( $_POST['message'] );

// If all values exist, send the email
if ( $senderName && $senderEmail && $message ) {
$query = "INSERT INTO `contact` (senderName, senderEmail, message) VALUES ('$senderName', '$senderEmail', '$message')";  
$result = mysql_query($query);  //query executes  
}

// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
  echo $success ? "success" : "error";
} else {
?>
<html>
  <head>
    <title>Thanks!</title>
  </head>
  <body>
  <?php if ( $success ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
  <?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
  <p>Click your browser's Back button to return to the page.</p>
  </body>
</html>
<?php
}

私が抱えている問題は2つあります。

  • [メールを送信] ボタンをクリックするとsending、問題が発生したと通知される前に、メッセージが一瞬届きます。このため、フォーム フィールドは例のようにクリアされず、フォームはフェードアウトせずに表示されたままになります。

  • 私が抱えている2番目の問題は、入力した実際のテキストが保存されるのではなく、データをデータベースに投稿することはできますが、各フィールドに値が表示されることです1

冒頭で述べたように、私は Ajax と jQuery に非常に慣れていませんが、誰かがこれを見て、どこが間違っているのか教えてくれるのではないかと思いました。

多くの感謝と親切な敬意

4

1 に答える 1

0

私は他人のコードを読むのが苦手なので、form.serialize() も利用するサンプルを作成しました。

<form id="form1" method="post" action="submit.php">
    <input type="text" name="boom" value="yoh"/>
    <input type="text" name="zoom" value="zoh"/>
    <input type="submit"/>
</form>
    <script>
    $('#form1').submit(function(e){
    e.preventDefault();
    $.post('submit.php', $('#form1').serialize(), function(data){console.log(data);});
    });
    </script>

他の人のコードを読むのも苦手な場合は、スクリプトで間違っている可能性があるものを次に示します。まず、フォームを送信しようとするコードが表示されません。次のようになります。

$('#form1').submit(function(e){ //form1 is the id that you gave to your form
e.preventDefault(); //this prevents page refresh
});

次に、HTML コードの下に JavaScript コードを含めて、ページ全体が読み込まれる前に JavaScript コードが実行されないようにします。これを行うと、パフォーマンス上の利点もあります。

<form>...</form>
<script>
</script>
于 2012-06-28T13:21:20.303 に答える