Site icon Hip-Hop Website Design and Development

Cannot successfully execute AJAX script to call function.php specific function. Using XAMPP localhost to test

I’ve been trying to grasp AJAX for the past 12 hours and i’m slowly losing it. How can I simply pass two basic input dates via form or any other means, not refresh the page, and have it execute the PHP function which contains a JS script?

Before I even pass the values to the script I just wanna echo the array of data I’m passing to see if…well ajax is working. The form button just refreshes the page regardless, so I don’t think AJAX is even kicking in at all. I’m trying on the https://localhost for xampp. I don’t know what’s missing to stop the refresh and kick in the ajax script over the button.

Appreciate any insight.

functions.php

<?php
add_action('wp_enqueue_scripts','enqueue_parent_styles');
add_action('wp_ajax_nopriv_lineChartCustom', 'lineChartCustomCreate');
add_action('wp_ajax_lineChartCustom', 'lineChartCustomCreate');

function lineChartCustomCreate(){

    if ( isset( $_POST['dataForPHP'])){
        //echo data array
    echo $dataForPHP;
    //<script>Some chart generating script using the data array</script>
    }
}
?>

page-template.php

<?php
    echo "<form id='my-form'>
        Select Date Range:
        <input type='date' name='date1'>
        <input type='date' name='date2'>
        <input type='submit' id='submit' value='submit'>
        </form>";
?>
<script>
        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: 'lineChartCustom', // 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                
                 });
             });
         });
</script>