Using Ajax call in jQuery doesn’t work in widget

So I’m in the midst of creating a new conversion widget and I’m having some trouble getting the Ajax call to work in my widget. (works perfectly outside of WordPress).

The problem at the moment is that it outputs the whole homepage in the #results div rather than just the results figure:

Related posts

Leave a Reply

2 comments

  1. If your AJAX Url is conversion.php it will most likely point to yourdomain.com/conversion.php.
    Is your file in that location?

    Looks like not, and I guess you don’t have a 404.php, and in that case your request gets directed to your index.php, that’s why you get the contents of your homepage.

    If your file is in your theme folder, you would have to change the URL to wp-content/themes/yourtheme/conversion.php

    But the much easier and recommended way is to use WP built in AJAX functionality:
    See this codex page for more informations:
    http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

    EDIT: Most posts on this topic are for AJAX on the WordPress backend but it’s possible to use it on the frontend as well.

  2. I’m sorry, but some of ungestaltbar’s comments are not fully correct.

    Couldn’t comment above anymore, but it’s almost an answer.

    When using admin-ajax.php for the front-end …

    One needs to hook BOTH, wp_ajax_(action) & wp_ajax_nopriv_(action) on front- AND back-end, else it won’t work.

    The reason why you get the whole page returned might be that the XHR call is being intercepted by rewrite rules – WP is a single point of access application.

    The syntax is about like that:

    add_action('wp_ajax_nopriv_conversion', array(&$this, 'do_conversion'));
    add_action('wp_ajax_conversion', array(&$this, 'do_conversion'));
    

    This might sound not too logical, but I’m pretty sure with that (recently used in a project).