在 onClick HTML 事件之后调用 PHP 函数

2022-01-09 00:00:00 function events onclick php html

目的:调用 PHP 函数从文件中读取数据并重写它.我仅将 PHP 用于此目的 - FileIO - 我是 PHP 新手.

Purpose: Call a PHP function to read data from a file and rewrite it. I used PHP only for this purpose - FileIO - and I'm new to PHP.

解决方案?我尝试了很多论坛,知道我们无法正常实现:onClick事件>调用函数.我们该怎么做,还有其他方法吗,尤其是在我的情况下?我的 HTML 代码和 PHP 代码在同一页面上:Admin.php.这是 HTML 部分:

Solution? I tried through many forums and knew that we cannot achieve it normal way: onClick event > call function. How can we do it, are there other ways, particularly in my case? My HTML code and PHP code is on the same page: Admin.php. This is HTML part:

<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="etc@company.com" 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 部分:

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.如果需要,我们可以重新加载页面.仅供参考,我也在页面中使用 JQuery、HTML5.谢谢,

Have a look at these code, I want to call saveContact when people click on Add Contact button. We can reload page if need so. FYI, I use JQuery, HTML5 in page as well. Thanks,

推荐答案

有两种方法.第一种是使用典型的表单提交来完全刷新页面

There are two ways. the first is to completely refresh the page using typical form submission

//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="etc@company.com" 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 -->

第二种方法是使用 AJAX.为此,您需要将表单处理完全分离到一个单独的文件中:

The second way would be to use AJAX. to do that youll want to completely seprate the form processing into a separate file:

//进程.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 中

And then in your 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="etc@company.com" 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>

相关文章