【问题标题】:AJAX Form Submission To MySQL DatabaseAJAX 表单提交到 MySQL 数据库
【发布时间】:2012-06-28 21:21:20
【问题描述】:

我想知道是否有人可以帮助我。

首先,我向经验丰富的开发人员道歉,他们可能觉得这是一个非常基本的问题,但这是我的第一次尝试,所以请多多包涵。

一段时间以来,我一直试图找到一个 AJAX 表单示例,该表单在提交表单时包含成功和失败消息。

我找到了 this 文章,我现在正在尝试调整它,以便将数据保存到 mySQL 数据库中,但我在让它工作时遇到了一些困难。

教程基本上有两个文件,一个是HTML表单,另一个是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
}

我遇到的问题有两个:

  • 当我单击“发送邮件”按钮时,我会暂时收到sending 消息,然后才被告知有问题。因此,不会按照示例清除表单字段,并且表单保持在视图中而不是淡出。

  • 我遇到的第二个问题是,虽然我可以将数据发布到我的数据库,而不是保存我输入的实际文本,但每个字段都显示值 1

正如我一开始所说,我对 Ajax 和 jQuery 很陌生,但我只是想知道是否有人可以看看这个并让我知道我哪里出错了。

非常感谢和亲切的问候

【问题讨论】:

  • 所以你没有得到你在表单中输入的值,而是得到每个值 1 对吗?
  • 嗨@Kyokasuigetsu,感谢您抽出宝贵时间回复我的帖子。是的,没错,正在输入的值没有被保存。亲切的问候
  • 您可以编辑您的帖子并包含您用来提交数据的 jquery 代码吗?这样我就可以看看它是否有问题。以 $.ajax({
  • 嗨@Kyokasuigetsu,我已将表单代码添加到我的原始帖子中。亲切的问候和感谢。
  • 发帖时只需要包含相关代码即可。只需要支持您在帖子中描述的代码,您不需要包含 css 代码,因为您对样式没有任何问题。似乎您只是兴高采烈地阅读了这篇文章,却没有理解某些代码在做什么。我建议你在 nettuts 阅读这篇文章,这样你就会得到启发:net.tutsplus.com/tutorials/javascript-ajax/…

标签: php jquery form-submit


【解决方案1】:

我不擅长阅读其他人的代码,所以我创建了一个同样使用 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>

【讨论】:

  • 嗨@Kyokasuigetsu 感谢您抽出时间帮助我解决这个问题。如果有帮助,示例中的表单提交从这里开始:function submitForm() { var contactForm = $(this); // Are all the fields filled in? if ( !$('#senderName').val() || !$('#senderEmail').val() || !$('#message').val() ) {亲切的问候
猜你喜欢
  • 2014-05-25
  • 1970-01-01
  • 2023-03-15
  • 2018-03-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2016-05-22
相关资源
最近更新 更多