如何通过按钮表单提交或Ajax onClick运行简单的PHP函数?

时间:2019-04-14 07:24:49

标签: php html ajax wordpress

对于Web开发人员来说是新手,所以请多多包涵。在wordpress中,我有一个functions.php文件,其中包含一个函数,该函数会生成图表并以2个日期作为输入。

在我的page-template.php中,我将输入2个日期,然后单击“生成”以使图表重新生成而无需重新加载页面。我有一个不带参数的函数,该函数在页面加载时运行,该按钮将加载另一个函数,该函数在单击按钮时需要两个日期。

Ajax似乎是答案,但是大多数教程使我感到困惑,因为它们的示例要求连接到DB或仅专注于DB。不会通过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数据库函数将select运行到一个变量中,然后运行生成我的图表外观的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>";
}
?>

2 个答案:

答案 0 :(得分:2)

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

page-template.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>

functions.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

答案 1 :(得分:0)

是的,Ajax是解决此问题的方法,这是使用Ajax的代码版本:

表格:

<?php
lineChartAll_Generate();

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


JavaScript / jQuery:
通过单击提交按钮,jQuery会将表单数据收集到一个数组中,并将其存储在formData变量中,然后将其提交给名称为dataForPHP的PHP,并触发该名称的ajax操作钩子的your_custom_action

jQuery('#submit').on('click', function() {

   let formData = jQuery('#my-form').serializeArray(); // retrieves the form's data as an array

  jQuery.ajax({
            url: ajaxurl, // default ajax url of wordpress
            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 by the name of dataForPHP
            },
            success: function( response ) {
                // do what you want with the response echoed from PHP

            },
            error: function( error ) {
              // show an oops! message
            }
        });
    });
});

PHP:
PHP使用jQuery触发的ajax操作来运行函数,因此add_action('wp_ajax_your_custom_action', 'your_custom_function');意味着触发your_custom_action时,运行your_custom_function

add_action('wp_ajax_your_custom_action', 'your_custom_function'); // ajax actions in wordpress must have the prefex 'wp_ajax_'

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

     // do staffs with submitted data from the html form...

  }

  echo 'what you want to receive as a response in jQuery.ajax() success function'; // ignore this line if you don't want to receive any response.
}