在onClick HTML事件之后调用PHP函数 [英] Call a PHP function after onClick HTML event

查看:131
本文介绍了在onClick HTML事件之后调用PHP函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目的:
调用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添加联系人按钮。如果需要,我们可以重新加载页面。 FYI,我也在页面中使用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:

// process.php

// 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

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>

这篇关于在onClick HTML事件之后调用PHP函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆