2012-06-28 4 views
1

나는 누군가가 나를 도울 수 있는지 궁금해.MySQL 데이터베이스에 AJAX 양식 제출

첫 번째로 느낄 수있는 노련한 개발자에게 사과하는 것은 매우 기본적인 질문이지만, 이것이 첫 번째 시도이기 때문에 나와 함께하시기 바랍니다.

나는 양식 제출시 성공 및 실패 메시지를 통합하는 AJAX 양식의 예를 찾으려고 노력 해왔다.

this 문서를 찾았습니다. 이제는 데이터를 mySQL 데이터베이스에 저장하도록 조정 중이지만 제대로 작동 시키려면 약간의 어려움이 있습니다.

이 튜토리얼은 기본적으로 두 개의 파일, 하나는 HTML 양식, 다른 하나는 PHP 스크립트입니다.

<!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 스크립트를 변경했습니다 : 나는 예제의 HTML을 변경하지 적이 있지만

표시 나는이 아래에 게시 한

<?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를 아주 새로운 해요,하지만 누군가가 아마도 이것 좀 봐 내가 잘못된거야 어디 알려 수 있는지 난 그냥 궁금.

많은 감사와 안부

+0

그래서 양식에 입력 한 값을 얻지 못하고 각각 대신에 1의 값을 얻습니다. –

+0

안녕하세요 @ 키요 카스이 게츠, 내 게시물에 답장하는 시간을내어 주셔서 감사합니다. 네, 맞습니다. 입력중인 값이 저장되지 않습니다.감사합니다 – IRHM

+0

게시물을 편집하고 데이터 제출에 사용하는 jquery 코드를 포함시킬 수 있습니까? 그래서 뭔가 잘못 됐는지 알 수있었습니다. $ .ajax ({ –

답변

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 코드 아래에 자바 스크립트 코드를 포함하려고,이 일에서 성능 이점도있다 :

<form>...</form> 
<script> 
</script> 
+0

안녕하세요. @Kyokasuigetsu이 시간을내어 도와 주셔서 감사합니다. 도움이된다면 예제의 양식 제출은 여기에서 시작됩니다 : 'function submitForm() { var contactForm = $ (this); // 모든 필드가 채워져 있습니까? if (! $ ('# senderName') .Val() ||! $ ('# senderEmail') .Val() ||! $ ('# message'). 문안 인사 – IRHM