2012-04-12 5 views
10

목적 : 파일에서 데이터를 읽고 다시 쓰는 PHP 함수를 호출하십시오. 필자는이 목적으로 만 PHP를 사용했습니다 - FileIO - 저는 PHP를 처음 사용합니다.onClick HTML 이벤트 후 PHP 함수 호출

솔루션? 많은 포럼을 통해 정상적인 방법으로 얻을 수 없다는 것을 알았습니다 : onClick 이벤트> 호출 기능. 우리는 어떻게 그것을 할 수 있습니까? 다른 경우, 특히 제 경우에는 있습니까? 내 HTML 코드와 PHP 코드가 같은 페이지에 있습니다 : Admin.php. 이것은 HTML의 일부입니다

function saveContact() 
{ 
    $datafile = fopen ("data/data.json", "a+"); 
    if(!$datafile){ 
     echo "<script>alert('Data not existed!')</script>"; 
    } 
    else{ 
     ... 
     $contact_list = $contact_list . addNewContact(); 
     ... 
     file_put_contents("data/data.json", $contact_list); 
    } 

    fclose($datafile); 
} 

function addNewContact() 
{ 
    $new = '{'; 
    $new = $new . '"fullname":"' . $_GET['fullname'] . '",'; 
    $new = $new . '"email":"' . $_GET['email'] . '",'; 
    $new = $new . '"phone":"' . $_GET['phone'] . '",'; 
    $new = $new . '}'; 
    return $new; 
} 

가 나는 사람들이 연락처 추가 버튼을 클릭하면 saveContact을 호출 할이 코드를 살펴 유무 :

<form> 
    <fieldset> 
     <legend>Add New Contact</legend> 
     <input type="text" name="fullname" placeholder="First name and last name" required /> <br /> 
     <input type="email" name="email" placeholder="[email protected]" required /> <br /> 
     <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br /> 
     <input type="submit" name="submit" class="button" value="Add Contact" onClick="" /> 
     <input type="button" name="cancel" class="button" value="Reset" /> 
    </fieldset> 
</form> 

이것은 PHP 부분입니다. 필요한 경우 페이지를 새로 고침 할 수 있습니다. 참고로 JQuery, HTML5를 페이지에서도 사용합니다. 감사합니다.

+2

u는 AJAX를 사용하는 것 루프 동안, 자바 스크립트는 PHP 안에. 당신은 클라이언트 사이드 이벤트 핸들러에 의해 호출 된 서버 측 함수를 수행 할 수 없습니다. –

+2

자바 스크립트는 어디에 있습니까 ??? 당신은 onClick과 같은 PHP 폼 HTML 이벤트를 호출 할 수 없습니다 ... – Baba

+0

Yah는 동의하지만 AJAX 하나 옆에 또 다른 해결책을 찾고 싶습니다. 아래를 보아라. 그러면 당신은 시험 할만한 가치가있는 것을 발견 할 수있다 :) @RPM – Shinigamae

답변

9

두 가지 방법이 있습니다. 첫 번째는 완전히 AJAX를 사용하는 것이 일반적인 양식 제출을

//your_page.php 

<?php 

$saveSuccess = null; 
$saveMessage = null; 

if($_SERVER['REQUEST_METHOD'] == 'POST') { 
    // if form has been posted process data 

    // you dont need the addContact function you jsut need to put it in a new array 
    // and it doesnt make sense in this context so jsut do it here 
    // then used json_decode and json_decode to read/save your json in 
    // saveContact() 
    $data = array(
    'fullname' = $_POST['fullname'], 
    'email' => $_POST['email'], 
    'phone' => $_POST['phone'] 
); 

    // always return true if you save the contact data ok or false if it fails 
    if(($saveSuccess = saveContact($data)) { 
    $saveMessage = 'Your submission has been saved!';  
    } else { 
    $saveMessage = 'There was a problem saving your submission.'; 
    } 
} 
?> 

<!-- your other html --> 

<?php if($saveSuccess !== null): ?> 
    <p class="flash_message"><?php echo $saveMessage ?></p> 
<?php endif; ?> 

<form action="your_page.php" method="post"> 
    <fieldset> 
     <legend>Add New Contact</legend> 
     <input type="text" name="fullname" placeholder="First name and last name" required /> <br /> 
     <input type="email" name="email" placeholder="[email protected]" required /> <br /> 
     <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br /> 
     <input type="submit" name="submit" class="button" value="Add Contact" onClick="" /> 
     <input type="button" name="cancel" class="button" value="Reset" /> 
    </fieldset> 
</form> 

<!-- the rest of your HTML --> 

두 번째 방법을 사용하여 페이지를 새로 고침하는 것입니다.

// process.php

$response = array(); 

if($_SERVER['REQUEST_METHOD'] == 'POST') { 
    // if form has been posted process data 

    // you dont need the addContact function you jsut need to put it in a new array 
    // and it doesnt make sense in this context so jsut do it here 
    // then used json_decode and json_decode to read/save your json in 
    // saveContact() 
    $data = array(
    'fullname' => $_POST['fullname'], 
    'email' => $_POST['email'], 
    'phone' => $_POST['phone'] 
); 

    // always return true if you save the contact data ok or false if it fails 
    $response['status'] = saveContact($data) ? 'success' : 'error'; 
    $response['message'] = $response['status'] 
     ? 'Your submission has been saved!' 
     : 'There was a problem saving your submission.'; 

    header('Content-type: application/json'); 
    echo json_encode($response); 
    exit; 
} 
?> 

그리고 당신의 HTML에서/JS

<form id="add_contact" action="process.php" method="post"> 
     <fieldset> 
      <legend>Add New Contact</legend> 
      <input type="text" name="fullname" placeholder="First name and last name" required /> <br /> 
      <input type="email" name="email" placeholder="[email protected]" required /> <br /> 
      <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br /> 
      <input id="add_contact_submit" type="submit" name="submit" class="button" value="Add Contact" onClick="" /> 
      <input type="button" name="cancel" class="button" value="Reset" /> 
     </fieldset> 
    </form> 
    <script type="text/javascript"> 
    $(function(){ 
     $('#add_contact_submit').click(function(e){ 
      e.preventDefault(); 
      $form = $(this).closest('form'); 

      // if you need to then wrap this ajax call in conditional logic 

      $.ajax({ 
       url: $form.attr('action'), 
       type: $form.attr('method'), 
       dataType: 'json', 
       success: function(responseJson) { 
       $form.before("<p>"+responseJson.message+"</p>"); 
       }, 
       error: function() { 
       $form.before("<p>There was an error processing your request.</p>"); 
       } 
      }); 
     });   
    }); 
    </script> 
+1

... 그리고 다른 AJAX 호출을 사용하는 것입니다. – inhan

+1

'action = ""' –

+0

@Lawrence : 프로덕션 코드가 아니었지만 XSS를 변경했습니다 :-) – prodigitalson

3

당신은하지 : 완전히 별도의 파일로 폼 처리를 seprate 알면 원하는해야 할 일 그렇게하려면 자바 스크립트가 필요합니다. 그냥 온 클릭을 삭제하고 PHP는이 같은 Admin.php 파일 쓰기 :

<!-- HTML STARTS--> 
<?php 
//If all the required fields are filled 
if (!empty($GET_['fullname'])&&!empty($GET_['email'])&&!empty($GET_['name'])) 
{ 
function addNewContact() 
    { 
    $new = '{'; 
    $new .= '"fullname":"' . $_GET['fullname'] . '",'; 
    $new .= '"email":"' . $_GET['email'] . '",'; 
    $new .= '"phone":"' . $_GET['phone'] . '",'; 
    $new .= '}'; 
    return $new; 
    } 

function saveContact() 
    { 
    $datafile = fopen ("data/data.json", "a+"); 
    if(!$datafile){ 
     echo "<script>alert('Data not existed!')</script>"; 
     } 
    else{ 
     $contact_list = $contact_list . addNewContact(); 
     file_put_contents("data/data.json", $contact_list); 
     } 
    fclose($datafile); 
    } 

// Call the function saveContact() 
saveContact(); 
echo "Thank you for joining us"; 
} 
else //If the form is not submited or not all the required fields are filled 

{ ?> 

<form> 
    <fieldset> 
     <legend>Add New Contact</legend> 
     <input type="text" name="fullname" placeholder="First name and last name" required /> <br /> 
     <input type="email" name="email" placeholder="[email protected]" required /> <br /> 
     <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br /> 
     <input type="submit" name="submit" class="button" value="Add Contact"/> 
     <input type="button" name="cancel" class="button" value="Reset" /> 
    </fieldset> 
</form> 
<?php } 
?> 
<!-- HTML ENDS --> 

생각 나는 PHP 비트를 싫어합니다. 연락처 파일을 정말로 만들고 싶습니까? 그것은 MUCH mysql 데이터베이스를 사용하는 것이 더 좋을 것입니다. 또한, 그 파일에 약간의 휴식을 추가하는 것도 좋을 것입니다 ...

다른 생각, IE는 자리 표시자를 지원하지 않습니다. 그 매력처럼 작동

+0

나. 내 webiste에서 서버 측 언어를 사용해야한다면 ASP.NET을 사용해 보겠습니다. 그러나 이것은 간단한 데모이기 때문에 간단한 환경 (XAMPP, Dreamweavaer, done)으로 PHP를 선택합니다. 나는 한판 승부 MySQL을 전혀 몰라. 당신의 아이디어에 감사드립니다, @ 프랭크 Presencia Fandos, 나는 종종 코드에 휴식을 추가하는 것을 잊지. 현재 Chrome/Firefox에서만 테스트/데모가 더 나은 HTML5 지원을 위해 :) – Shinigamae

+0

mysql에 대한 기본 사항을 배우는 것이 좋습니다. 주변에서 가장 많이 사용되며 기초를 배우는 것은 정말 쉽습니다. 구현할 때 사이트의 mysql은 [this] (http://www.w3schools.com/php/php_mysql_insert.asp), 두 번째 예제처럼 쉽습니다. –

+0

다시 한번 감사드립니다, 프랭크 프레 센시아 판도스, 나는 그것을 배울 것입니다. – Shinigamae

6
<div id="sample"></div> 
<form> 
     <fieldset> 
      <legend>Add New Contact</legend> 
      <input type="text" name="fullname" placeholder="First name and last name" required /> <br /> 
      <input type="email" name="email" placeholder="[email protected]" required /> <br /> 
      <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br /> 
      <input type="submit" name="submit" id= "submitButton" class="button" value="Add Contact" onClick="" /> 
      <input type="button" name="cancel" class="button" value="Reset" /> 
     </fieldset> 
    </form> 

<script> 

    $(document).ready(function(){ 
     $("#submitButton").click(function(){ 
      $("#sample").load(filenameofyourfunction?the the variable you need); 
     }); 
    }); 

</script> 
+0

간단하고 깨끗한, 감사합니다 @ Ketherine, 먼저 해보겠습니다 :) – Shinigamae

1
cell1.innerHTML="<?php echo $customerDESC; ?>"; 
cell2.innerHTML="<?php echo $comm; ?>"; 
cell3.innerHTML="<?php echo $expressFEE; ?>"; 
cell4.innerHTML="<?php echo $totao_unit_price; ?>"; 

+0

$ customerDESC, @comm 등의 기능을 호출하고 셀은 버튼과 같은 발신자 요소입니까? – Shinigamae