WordPress.org

Support

Support » Plugins and Hacks » Hacks » adding a ajax hook not working in shortcode?

adding a ajax hook not working in shortcode?

  • here is how it set up:
    add_shortcode(‘abc_abc’,’shortfun’);

    function shortfun()
    {
    include ‘ajax_res.php’;
    }

    —————————-in ajax_res.php:——————————————–
    add_action(‘wp_ajax_ex_abc’,’ex_abc’);
    function ex_abc()
    {
    echo ‘here!’;
    die();
    }

    ——————————-js call——————————-
    jQuery.ajax({
    type : “post”,
    url : myAjax.ajaxurl,
    data : {action: “ex_abc”},
    success: function(response) {
    alert(response);
    }
    }

    why is the output always 0. and it looks like the function hooked onto the ajax call “ex_abc” is never called.
    Blog url:

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    @bcworkz

    When a shortcode is encountered, it is simply replaced by the value returned by the shortcode’s callback function. Since your callback returns nothing, the shortcode is replaced by nothing.

    I’ve no idea what happens to a function defined in a callback, I would think it’s private to the callback and cannot be called with AJAX.

    Think about how you would set this up in HTML without shortcodes. That is what your callback should return. Everything else is done via regular jQuery and PHP, shortcodes do not play into it.

    I think your action that handles the AJAX request should not be called from within the shortcode output.
    add_action(‘wp_ajax_ex_abc’,’ex_abc’);

    That should be called early to intercept the AJAX request if one is made, before the page renders.

    I think Ben was right about that being called at a wrong place.

    i was able to have the ajax response by doing the following.

    I place the add_action and the function to be called within a plugin php.
    it looks like to me. it works perfect with the codes above IF and ONLY IF I don’t use include. meaning if i don’t have the plugin load the php file when processing the ajax call.

    this is very wired.

    why it works only when i have include the php file under the plugin but when i use the same code. which is include ‘ajax_res.php’; it will never work when under shortcode function.

    so in short. is it impossible to register ajax function and have that function called if we use include to load the php file within shortcode.

    this symptom is just really wired. somewhere alone the code. there must be something not called.

    WPWebs

    @vipuljariwala-1

    hi there,

    it may be jquery init problem.

    add the same js code in footer and you should make your jquery code with onload ready so it will ready after related element is exist in the html code and as your js is in footer so it should work.

    Thanks

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘adding a ajax hook not working in shortcode?’ is closed to new replies.
Skip to toolbar