php 페이지에서 버튼을 눌렀을 때

ant01의 이미지

php 페이지에서 버튼을 눌렀을 때 페이지 내부에서 어떤 action이 일어나게 하려면
어떻게 해야 하는 지 알려 주시면 감사하겠습니다.

hiseob의 이미지

php 와는 상관 없고 AJAX 등을 쓰면 됩니다.

noblepylon의 이미지

jQuery는 http://jquery.com/ 에서 받으실 수 있습니다.
AJAX를 구현하는데 이것만큼 편한 물건을 보지 못했습니다.

예제: 게시판에서 덧글달기 버튼을 눌렀을때 페이지를 새로고침하지않고도 새 덧글이 바로 보이게 하기.

덧글 폼

...
<table id="comment-table">
    <tr id="comment-form">
        <td><img src="uploads/1_profile.gif" /></td> <!-- 프로필 사진 -->
        <td>
            <input id="mid" type="hidden" value="1" /> <!-- 게시글 id -->
            <label for="comment-area">덧글:</label>
            <textarea cols="40" rows="8" name="textarea" id="comment-area" placeholder="덧글은 여기에 달아주세요"></textarea>
            <input id="comment-submit" type="button" value="덧글 달기" />
        </td>
    </tr>
</table>
...

custom.js

$("#comment-submit").click(function() {
    var _comment = $("#comment-area").val(); // comment-area의 내용을 긁어온다
    var _mid = $("#mid").val(); // 게시글 id를 긁어온다.
    if(_comment.length == 0) {
        alert("덧글 내용이 없습니다.");
    } else { // commentajax.php로 덧글 내용 전송
        $.ajax({
            type: "POST",
            url: "commentajax.php", 
            timeout: 10000,
            data: ({comment: _comment, mid: _mid}),
            cache: false,
            dataType: "text",
            success: function(html) { // 전송이 성공하면 새 덧글을 지정된 위치에 넣는다.
                $("#comment-form").before(html);
                $("#comment-table .new").fadeIn(400);
            },
            error: function(xhr, textStatus, errorThrown) { // 전송 실패
                alert("한글/영어 외의 외국문자와 일부 특수문자는 허용되지 않습니다.");
            }
        }); 
    }       
    return false;
});

commentajax.php: 덧글 내용과 게시글 id를 POST로 받아서 데이터베이스에 입력하고, 그 내용을 html로 가공하여 리턴한다.

<?php
require_once "./DBConnection.php"; // DB연결을 담당하는 클래스
require_once "./NCComments.php"; // 덧글을 관리하는 클래스
require_once "./MemberProfile.php"; // 회원정보를 관리하는 클래스
require_once "./NCIncludes/verify.inc"; // 폼 내용에 취약점 제거
 
$db = DBConnection::getInstance(); // DB에 이미 연결이 되어있지 않으면 연결한다.
if($_POST) {
    $comment = $db->escape_string($_POST["comment"]); // DBConnection클래스에는 SQL 인젝션 공격을 막기 위한 메소드가 있다.
    if(!verify_int($_POST["mid"])) // mid 변수가 정수가 아니면 예외처리
        trigger_error("여기가 어디 안전이라고 덤비는 것이오!", E_USER_ERROR);
    if(!verify_text($comment))
    // 덧글 내용에 들어가면 안될 것이 들어가면 예외처리 -- 한글, 영어, 숫자외의 수상한 문자는 모두 거부한다. 
        trigger_error("여기가 어디 안전이라고 덤비는 것이오!", E_USER_ERROR);
 
    $mid = intval($_POST["mid"]);
    $comm = new NCComments();
    $comm->addComment($mid, $comment); // 덧글을 DB에 쓴다.
 
    $comment = htmlspecialchars($comment); // html 특수문자를 안전하게 처리
    $comment = str_replace('\n', '<br />', $comment); // 엔터를 줄바꿈으로 치환
    $mem = new MemberProfile(); // 회원 정보를 불러온다.
    if($mem->getStatus() == "nonmember") // 비회원이 부정한 방법으로 덧글을 달려고 하면 예외처리
        trigger_error("아니 어디서 감히!", E_USER_ERROR);
    $name = $mem->getName();
    $profile_pic = $mem->getProfilePic();
    if($profile_pic == NULL) $profile_pic = "default.png";
 
    // 덧글이 성공적으로 데이터베이스에 전송되면 html태그를 리턴한다.
    echo <<<EOD
    <tr class="new" style="display:none">
    <td><img src="$profile_pic" /></td>
    <td>
        <p><strong>$name</strong></p>
        <p>$comment<br />
        </p>
    </td>
    </tr>
EOD;
}
?>

---
“내게 능력주시는 자 안에서 내가 모든 것을 할 수 있느니라.”(빌립보서 4:13)

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.