0

I'm trying to generate & replace Wordpress shortcodes with AJAX based on the user's chosen <select> option.

I've posted my progress to date below - whilst the shortcodes are currently being replaced on form POST, it's not with AJAX - the full page is reloading. I've tried to keep the question as general as possible to (hopefully) help others too, but I've very little experience with AJAX, so any advice as to where I've messed up would be massively appreciated.

PHP

For context in terms of implementation; [table_generator] is the parent shortcode which houses both the form and generated 'child' shortcodes. When the user selects a provider from the dropdown and hits the submit button, a shortcode is generated below which displays a table of data relative to that provider. If the user then changes the provider in the <select> input and submits again, a new appropriate table is generated.

function table_generator() {

    // Set product providers
    $providers = array(
        'Provider 1',
        'Provider 2',
        'Provider 3',
    );

    // Build provider selection form
    $output .= '<form id="submitProvider" action="" method="POST">';
    $output .= '<select name="provider_list">';
    $output .= '<option value="default" selected disabled hidden>Select a provider...</option>';

    // Loop through '$providers' array, creating <select> options
    foreach ($providers as $provider) {
        $output .= '<option value="' . $provider . '">' . $provider . '</option>';
    }

    $output .= '</select>';
    $output .= '<button type="submit">Submit</button>';
    $output .= '</form>';

    // Generate shortcode based on selected provider
    if (isset($_POST['provider_list'])) {
        $selected_provider = $_POST['provider_list'];
        $output .= '<div class="table-container">';
        $output .= do_shortcode( '[child-shortcode table="'. $selected_provider . '"]' );
        $output .= '</div>';
    }   

    // Initially, only display 'submitProvider' form
    return $output;

    // AJAX: Generate/update table
    add_action('wp_ajax_updateTable', 'updateTable');
    add_action('wp_ajax_nopriv_updateTable', 'updateTable');

    // Return output on POST with updated 'child-shortcode'
    function updateTable() {
        return $output;   
        die();
    }

}

add_shortcode( 'table_generator', 'table_generator' );

JS

$('#submitProvider').submit(function(e){
    $.ajax({ 
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'updateTable', 
        },
        error: function() {
            console.log("Error");            
        },
        success: function(data){ 
            console.log("Success");
        },
    });
});
1

In order to change the shortcode value by leveraging ajax, you need to modify the PHP code and jQuery as mentioned below:

function table_generator() {
    // Set product providers
    $providers = array(
        'Provider 1',
        'Provider 2',
        'Provider 3',
    );
    // Build provider selection form
    $output .= '<form id="submitProvider" action="" method="POST">';
    $output .= '<select name="provider_list">';
    $output .= '<option value="default" selected disabled hidden>Select a provider...</option>';
    // Loop through '$providers' array, creating <select> options
    foreach ($providers as $provider) {
        $output .= '<option value="' . $provider . '">' . $provider . '</option>';
    }
    $output .= '</select>';
    $output .= '<button type="submit">Submit</button>';
    $output .= '</form>';
    return $output;
}
// AJAX: Generate/update table
add_action('wp_ajax_updateTable', 'updateTable');
add_action('wp_ajax_nopriv_updateTable', 'updateTable');
// Return output on POST with updated 'child-shortcode'
function updateTable() {
    if (isset($_POST['provider_list'])) {
        $selected_provider = sanitize_text_field($_POST['provider_list']);
        $output .= '<div class="table-container">';
        $output .= do_shortcode( '[child-shortcode table="'. $selected_provider . '"]' );
        $output .= '</div>';
        wp_send_json(array('status' => 'success', 'html' => $output));
    }
    wp_send_json(array('status' => 'fail'));
}
add_shortcode( 'table_generator', 'table_generator' );

and change your javascript code as following:

$('#submitProvider').submit(function(e){
    e.preventDefault();
    $.ajax({ 
        url: ajaxurl,
        type: 'POST',
        data: {
            'action': 'updateTable',
            'provider_list': $("[name='provider_list']").val()
        },
        error: function() {
            console.log("Error");            
        },
        success: function(data){
            if(data.status == 'success'){
                console.log(data.html);
            }
        },
    });
});

Based on the ajax response you can show the html output.

  • Hey Faham - thanks for your response. Unfortunately, the shortcode switch doesn't work at all now, and the page is still performing a hard reload. I appreciate it's a very open question, but is there anything else I may have missed? I've seen a couple posts from users with issues using ajaxurl, but that's a total stab in the dark. – Graeme Bryson Jun 29 at 18:09
  • Got it - I had to localize ajaxurl. Thanks for your help Faham! Will update with a final solution shortly. – Graeme Bryson Jun 29 at 22:20
  • 1
    @GraemeBryson I was under the assumption that you had already localized the script since you were using ajaxurl. Sorry my bad mate!! – Faham Shaikh Jun 30 at 2:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.