首页 > 解决方案 > 如何通过按钮表单提交或使用 Ajax 的 onClick 运行简单的 PHP 函数?

问题描述

网络开发新手,请多多包涵。在 wordpress 中,我有一个 functions.php 文件,其中包含一个生成图表并将 2 个日期作为输入的函数。

在我的 page-template.php 中,我将输入 2 个日期并单击生成以重新生成图表而无需重新加载页面。我有一个在页面加载时运行的没有参数的函数,该按钮将加载备用函数,该函数在按钮单击时获取两个日期。

Ajax 似乎是答案,但大多数教程让我感到困惑,因为他们的示例需要连接到数据库或只专注于它。不会通过wordpress函数调用我的函数来处理它吗?有没有一种简单的方法可以在传递两个表单值 date1、date2 时按原样调用我的函数?截断的代码希望可读。

感谢帮助。

page-template.php:第一个函数是加载默认范围的函数(来自functions.php 文件),然后是日期选择器和按钮。

<?php
lineChartAll_Generate();

echo "<form>
    Select Date Range:
    <input type='date' name='date1'>
    <input type='date' name='date2'>
    </form>";
?>

functions.php:使用 WP 数据库函数将选择运行到变量中,然后运行生成图表视觉效果的 javascript 代码。

<?php
add_action('wp_enqueue_scripts','enqueue_parent_styles');

function enqueue_parent_styles(){
    wp_enqueue_style('parent-style', get_template_directory_uri().'/style.css');
}

function lineChartCustom_Generate($date1,$date2){

    //Database queries
    global $wpdb;        
    $overallenergyResults = $wpdb->get_results
    (
    "SELECT QUERY GOES HERE"
    );

    // Line chart code
    echo "
    <div class='lineChartAll'>
    <canvas id='myChart' width='400' height='200'></canvas>
    <script>
          //Chart javascript code goes here using $overallenergyResults variable
    </script></div>";
}
?>

标签: phphtmlajaxwordpress

解决方案


这是一个简单且有效的ajax 程序,检查它以了解该过程,然后以您想要的方式自定义它。
该程序从带有的表单中获取两个日期(date1,date2)id="my-form"并将它们显示到带有 的 div 中id="display"

页面模板.php

<?php
    echo "<script> const ajaxurl = '". admin_url('admin-ajax.php') ."' </script>"; // stores the ajaxurl into a js constant to be accissable in front-end page
?>

<form id='my-form'>
    Select Dates: <br>
    Date1: <input type='date' name='date1'><br>
    Date2: <input type='date' name='date2'><br>
    <button id='submit'> submit </button>
</form>


<div id='display' style="border: 1px solid; width: 200px; height: 100px;">
    <em>submit the form to see dates here: </em>
</div>


<script type="text/javascript">
    jQuery('#submit').on('click', function(event) {

        event.preventDefault();
        let date1 = jQuery('input[name="date1"]').val();
        let date2 = jQuery('input[name="date2"]').val();
        let formData = [date1, date2]; // prepare the form data as an array

        jQuery.ajax({
                url: ajaxurl, // ajaxurl defined at the top of the codes
                type: 'POST',
                data: {
                    action: 'your_custom_action', // use this action to handle the event
                    dataForPHP: formData // this is your form's data that is going to be submitted to PHP function by the name of dataForPHP
                },
                success: function(response) {
                    // show the response into dispaly div
                    jQuery('#display').html(response);
                },
                error: function(error) {
                  // show an oops! message
                  alert('oops! request failed.');

                }
        });
    });
</script>

函数.php

    // ajax actions in wordpress must be handled by two actions: one with the prefex 'wp_ajax_' and another with the prefix 'wp_ajax_nopriv_'
    add_action('wp_ajax_your_custom_action', 'your_custom_function'); 
    add_action('wp_ajax_nopriv_your_custom_action', 'your_custom_function');

    function your_custom_function() {
        if ( isset( $_POST['dataForPHP'] ) ) {

         // do anything you want with the submitted data, ex: running database query
         $date1 = $_POST['dataForPHP'][0];
         $date2 = $_POST['dataForPHP'][1];

        }

        echo "date 1: $date1 <br> date 2: $date2"; // send the response back to the client.
        die();
    }

注意:此函数必须对 Ajax 有响应。响应可以是 JSON 对象或任何字符串,如果您想返回 HTML 字体,只需将它们作为字符串回显即可。

更多关于 WP AJAX 的信息:https ://codex.wordpress.org/AJAX_in_Plugins


推荐阅读