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

问题描述 投票:0回答:2

Web开发新手所以请耐心等待。在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数据库函数将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>";
}
?>
php html ajax wordpress
2个回答
2
投票

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

页面的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


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,并以your_custom_action的名称触发ajax动作钩子

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.
}
© www.soinside.com 2019 - 2024. All rights reserved.