Home > OS >  ajax call inside shortcode
ajax call inside shortcode

Time:10-19

I am currently despairing of including an ajax call in a shortcode.

The admin-ajax is called but my main problem is, that the post data in the actual ajax call is always empty although I actually pass the variables with the wp_localize_script function. Since a similar ajax call works in another place ( but without shortcode), I suspect that ajax calls in shortcodes need to be built and structured differently. I just have no idea how...

In my plugin I use the following code:

plugin.php

<?php

/**
 *  Plugin Name: Test Plugin
 *  Description: Test
 *  Version: 0.1
 *  Author: Cool name
 *  Author URI: https://www.xyz.de
 */

add_shortcode("oc_product_widget","oc_product_widget");

function oc_product_widget() {

    $var1 = "var1";
    $var2 = "var2";

    wp_enqueue_script('products_price_page_ajax_js', plugins_url('js/price_page_ajax.js', __FILE__));

    wp_localize_script('products_price_page_ajax_js', 'products_price_page_ajax_js', array(
        'ajaxurl'       => admin_url('admin-ajax.php'),
        'var1'          => $var1,
        'var2'          => $var2,
    ));

}

add_action("wp_ajax_get_price_page", "get_price_page");
add_action("wp_ajax_nopriv_get_price_page", "get_price_page" );

function get_price_page(){
    include_once (plugins_url("ajax/get_price.php", __FILE__));
    wp_die();
}

?>

price_page_ajax.js

(function($) {

    $(document).ready(function () {

        var ajaxurl = products_price_page_ajax_js.ajaxurl;
        var var1 = products_price_page_ajax_js.var1
        var var2 = products_price_page_ajax_js.var2

        $.ajax({ // Ajax call
            url: ajaxurl, // Ajax site
            data: {
                var1: var1,
                var2: var2,
                action:"get_price_page"
            },
            type: 'post'
        }).done(function (responseData) {

            var resultObject = JSON.parse(responseData);

        }).fail(function () {

            console.log('AJAX call failed');

        });

    })

})( jQuery );

get_price.php

<?php

$var1 = $_POST["var1"];
$var2 = $_POST["var2"];
...
...

// admin-ajax.php is throwing
// Warning: Undefined array key "var1" in ...get_price.php on line ...
// &
// Warning: Undefined array key "var2" in ...get_price.php on line ...

?>

CodePudding user response:

The problem was that the post parameters was discarded after the include_once. Why exactly this happens I don't know exactly yet. Maybe someone can clarify this.

In detail:

Wrong

function get_price_page(){
    include_once (plugins_url("ajax/get_price.php", __FILE__));
    wp_die();
}

Correct

function get_price_page(){
    $var1 = $_POST["var1"];
    $var2 = $_POST["var2"];
    ...
    ...
    wp_die();
}
  • Related