1

New to web dev so bear with me. In wordpress I have a functions.php file with a function that generates a chart and would take 2 dates as an input.

In my page-template.php I would take 2 date inputs and click generate to make a chart re-generate without reloading the page. I have a function with no arguments that runs on page load, and the button would load the alternate function that takes the two dates on button click.

Ajax seems to be the answer but most tutorials confuse me as their example require connecting to the DB or is focused on it exclusively. Wouldn't calling my function that does it already via wordpress functions handle that on their own? Is there a simple way to get my function called as it is while passing the two form values date1,date2? Truncated code to be hopefully readable.

Appreciate the help.

page-template.php: The first function is the one on load with default range (from functions.php file), then the date picker and button.

<?php
lineChartAll_Generate();

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

functions.php: Using WP database function to run a select into a variable, then run the javascript code that generates the visuals of my chart.

<?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 Answers 2

2

Here is a simple and working ajax program, check it to understand the process then customize it in the way you want.
The program gets two dates (date1, date2) from a form with id="my-form" and displays them into a div with id="display".

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();
    }

Note: This function must have a response for the Ajax. the response can be JSON object or any string, if you would like to return HTML typography, just echo them as a string.

More about WP AJAX here: https://codex.wordpress.org/AJAX_in_Plugins

Sign up to request clarification or add additional context in comments.

7 Comments

Hey appreciate you posting a working example, but there must be something i'm missing here. I copied this exactly as displayed and it's still refreshing the page and nothing is happening. I thought maybe a typo where "your_custom_action" should match the name in the php, so I renamed your_custom_function to match it. But no dice. Page still refreshes and display is not updated at all
Says jquery is not defined in the console, which I don't know how to fix here.
You must have jQuery included in your page. Here is how to do this: w3schools.com/jquery/jquery_get_started.asp
Finally works...thank you so much for your continued patience. I've loaded the jquery via CDN because i'm having trouble doing the integrated wordpress way but at least just seeing the code example in action helps me tremendously. Now I can reverse engineer to do whatever I was trying to do. Thanks again!
My only remaining question about the code logic. How does it know that "your_custom_action" is the function called "your_custom_function" in the php file? Like it's working as is, but to me that makes no sense since nowhere else than then JQuery has that action name passed.
|
0

Yeah, Ajax is the solution for this issue, Here is the Ajax-using version of your code:

Form:

<?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:
By clicking the submit button the jQuery collects the form data into an array and stores them in the formData variable, then submits it to the PHP with the name of dataForPHP and fires an ajax action hook by the name of 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 uses the fired ajax action by jQuery to run a function, so, add_action('wp_ajax_your_custom_action', 'your_custom_function'); means when the your_custom_action fired, run the 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.
}

9 Comments

I'm confused about the part of handling the response. Am i really expecting a response? I'm basically telling it to execute a function, so am I supposed to handle the response differently because it's via ajax?
Yeah this isn't really clear or working out at all for me. What value am i supposed to pass in action? Right now clicking on the submit form still refreshes the browser so I don't even know if it's going through the JQuery. Are the values i'm passing to it really supposed to be "#submit' and "#my-form' with the hastag? I'm doing this on XAMPP localhost if this changes anythiing,
Handling the response is optional, you can ignore it. If you don't want to receive any response, don't echo anything from PHP side.
"What value am i supposed to pass in action?" this creates and action hook you can use it to run your function. actually this action happens if you click on the submit button. it's value can be any string.
" Are the values i'm passing to it really supposed to be "#submit' and "#my-form' with the hastag?" These are just the IDs of submit button and your form element. you can use any other selectors as well.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.