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

admin2025-01-07  11

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>

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>
Share Improve this question asked Apr 14, 2019 at 19:42 DennisioDennisio 151 silver badge5 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

You should add wp_die(); at the end of your php function.

But you could also send the response with wp_send_json, wp_send_json_error or wp_send_json_success. These functions also terminate the function execution.

The page is refreshed because you are sending the form synchronously (traditionally). To send the form using ajax your function hooked to onclick must return false or call .preventDefault() on submit event.

jQuery( "#my-form" ).submit(function( event ) {
    event.preventDefault();
    //
    // your code...
});

// --- or --- 

jQuery('#submit').on('click', function() {
    // ....
    return false;
});

Edit:

Move your javascript code to separate file (e.g. myscript.js). include that file on page using wp_enqueue_scripts() (hook). in the code you used ajaxurl but you have not defined it anywhere. wp_localize_script() is used to pass values from php to javascript, this way you will set the address for ajax in ajx_url variable.

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>";
?>

myscript.js:

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

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

    jQuery.ajax({
        url: ajax_object.ajax_url, // 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                
        }
    }).done(function( msg ) {
        alert( msg );
    });
    return false;
});

functions.php

add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {

    wp_enqueue_script( 'my-javascript', get_stylesheet_directory_uri(). '/myscript.js',  array('jquery'), '', true );

    // in JavaScript, object properties are accessed as ajax_object.ajax_url
    wp_localize_script( 'my-javascript', 'ajax_object',
            array( 'ajax_url' => admin_url('admin-ajax.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
        print_r($_POST['dataForPHP']);
    }
    die();
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736256156a339.html

最新回复(0)