Search code examples
phpjqueryajaxwordpressshortcode

Edit shortcode by select in JQuery/php


I have a table shortcode that should be edited depending on the values in a select box, but I cannot get it to work. I've come this far:

Shortcode syntax: [table id=tableID filter="filterstring" \] where the filter-part may be left out.

html:

<div>
<select class="filter-products">
<option value="all">All</option>
<option value="product1">product1</option>
<option value="product2">product2</option>
</select>
<div class="filter-table-doc">[table id=Doc /]</div>
</div>

jquery:

var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";

jQuery(".filter-products").on( "change", function() {

    var productTypeNew = jQuery(".filter-products").attr("value");

    jQuery.ajax({
        url: ajaxurl,
        data: {
            'action':'get_table_doc_shortcode',
            'product' : productTypeNew
        },
        success:function(data) {
            jQuery(".filter-table-doc").html(data);

        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });
});

php:

function get_table_doc_shortcode(){
    if ( isset($_REQUEST) ) {

        $product = $_REQUEST['product'];

        if ( $product == 'all' ) {
            $product = '[table id=Doc /]';
        }
        else {
            $product = '[table id=Doc filter="' + $product + '" /]';
        }

        return $product;
    }
   die();
} 
add_action('wp_ajax_get_table_doc_shortcode', 'get_table_doc_shortcode');
add_action('wp_ajax_nopriv_get_table_doc_shortcode', 'get_table_doc_shortcode');

This generates an error in the log; GET http://www.myurl.com/%3C?php%20echo%20admin_u…n-ajax.php%27);%20?%3E&action=get_table_doc_shortcode&product=product1 404 (Not Found).

Now I feel completely stuck and have wasted too much time on this already. Any ideas?


Solution

  • It would appear your Javascript is being called from within a .js file instead of a .php file. This means that the PHP functionality you're using wont work. The error you're seeing is because JS is reading the string value of "<?php echo admin_url('admin-ajax.php'); ?>" instead of the ajax url you intended. If you're trying to access the url for admin-ajax.php, as per the docs:

    Since Version 2.8, The JavaScript global variable ajaxurl can be used in case you want to separate your JavaScript code from php files into JavaScript only files. This is true on the administration side only.

    So simply remove the line var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"; from your code as ajaxurl is already defined globally.