1

hey guys, weird situation... I'm trying to use wp_ajax() for the first time. I'm normally using a normal jQuery ajax request but in my current case I get a lot of bugs so I thought about trying wp_ajax().

I don't get it though!

The following piece of code...

// embed the javascript file that makes the AJAX request
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js' );

// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

ends in...

<script type="text/javascript" src="http://example.com/wordpress/wp-content/plugins/myajax/js/ajax.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
var MyAjax = {
    ajaxurl: "http://example.com/wordpress/wp-admin/admin-ajax.php"
};
/* ]]> */

However I don't have a plugin or anything that should use this, but my whole page has to do this ajax request. Therefore the entire first line with wp_enqueue_script() doesn't make sens. I don't need to load a specific js-file for this because I have already my entire script.js file manually embedded in my <head> section. This is where the ajax request gets fired. However once I leave this line out (//wp_enqueue_script()...) the second part doesn't work.

So there will no

<script type="text/javascript">
/* <![CDATA[ */
var MyAjax = {
    ajaxurl: "http://example.com/wordpress/wp-admin/admin-ajax.php"
};
/* ]]> */

be printed into my section of my page. What am I getting wrong here? I really need to be able to fire a ajax request from within my normal script.js file.

Any ideas?

update: my script.js file (manually emebedded in my should call a an ajax request:

var response;
            $.post(
                // see tip #1 for how we declare global javascript variables
                MyAjax.ajaxurl,
                {
                    // here we declare the parameters to send along with the request
                    // this means the following action hooks will be fired:
                    // wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
                    action : 'wp_ajax_nopriv_searchmap',
                },
                function( response ) {
                    $sr.html(response);

the function in my functions.php file I want to call looks like this:

// embed the javascript file that makes the AJAX request
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js' );

// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

// this hook is fired if the current viewer is not logged in
if (isset($_GET['action'])) {
    do_action( 'wp_ajax_nopriv_' . $_GET['action'] );
}
// if logged in:
if (isset($_POST['action'])) {
    do_action( 'wp_ajax_' . $_POST['action'] );
}
if(is_admin()) {
    add_action( 'wp_ajax_searchmap', 'my_searchmap_function' );
} else {
    add_action( 'wp_ajax_nopriv_searchmap', 'my_searchmap_function' );
}

function my_searchmap_function() {

// Start output buffer
ob_start();
?>
div>
    <h3>Pages</h3>
        <ul>
            <?php wp_list_pages('title_li=&depth=0&exclude='); ?>
        </ul>
    <h3>Posts</h3>
        <?php $first = 0;?>
        <ul>
        <?php
        $myposts = get_posts('numberposts=-1&offset=$first');
        foreach($myposts as $post) :
        ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php endforeach; ?>
        </ul>
    <h3>Categories</h3>
        <ul>
            <?php wp_list_categories('title_li=&orderby=name'); ?>
        </ul>
</div>  
<?php 

    $output = ob_get_contents();

    // Stop output buffer
    ob_end_clean();
    $response = json_encode($output);

    // response output
    header( "Content-Type: application/json" );
    echo $response;

    // IMPORTANT: don't forget to "exit"
    exit;
}

What do I missunderstand here? I simply want to be able to request data via ajax from within my normal javascript file. I need to process the html that comes back in my javascript file.

Any idea what I'm doing wrong or better, what I have to do in order to make this work?

2 Answers 2

10

Ok, firstly let me just break it down a little, so you understand the purpose of these functions.

  • wp_enqueue_script()

    Description:
    A safe way of adding javascripts to a WordPress generated page. Basically, include the script if it hasn't already been included, and load the one that WordPress ships.

  • wp_localize_script()

    Description:
    Localizes a script, but only if script has already been added. Can also be used to include arbitrary Javascript data in a page.

When you localize a script, all you're doing is setting up an action that prints out Javascript vars into the page, but these vars are tied to the script you register them to, it's the first parameter you pass to wp_localize_script and is otherwise known as the script handle.

wp_enqueue_script is for queuing a javascript file, and wp_localize_script is designed to accompany scripts loaded via the enqueue system. You cannot localize nothing, so if you're not enqueuing, wp_localize_script is of no use to you here.

Typically you'd likely use the two like this..

$myvars = array( 
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'somevar1' => $somevar_from_somewhere,
    'somevar2' => $somevar_from_elsewhere
);
wp_enqueue_script( 'my-ajax-request', plugins_url( '/path/to/somefile.js', __FILE__ ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', $myvars );

Which then produces the following output in your page..

<script type="text/javascript" src="path/to/somefile.js"></script>

<script type="text/javascript">
/* <![CDATA[ */
var MyAjax = {
    ajaxurl: "http://example.com/wordpress/wp-admin/admin-ajax.php",
    somevar1: "somevalue",
    somevar2: "someothervalue"
};
/* ]]> */
</script>

Which you can then reference in your script, eg.

jQuery(document).ready( function($) {

    alert( MyAjax.somevar1 ); // Produces somevalue
    alert( MyAjax.somevar2 ); // Produces someothervalue

});

Throwing this all together, your code could go a little something like this..

// Setup the ajax callback for the "searchmap" action 
add_action( 'wp_ajax_searchmap', 'my_searchmap_function' );
add_action( 'wp_ajax_nopriv_searchmap', 'my_searchmap_function' );

// The callback function for the "searchmap" action
function my_searchmap_function() {
    $myposts = get_posts('numberposts=-1&offset=$first');
?>
<div> 
    <h3>Pages</h3>
    <ul>
        <?php wp_list_pages('title_li=&depth=0&exclude='); ?>
    </ul>

    <h3>Posts</h3>
    <ul>
        <?php foreach( $myposts as $post ) : setup_postdata( $post ); ?>

        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

        <?php endforeach; ?>
        <?php wp_reset_postdata(); ?>
    </ul>

    <h3>Categories</h3>
    <ul>
    <?php wp_list_categories('title_li=&orderby=name'); ?>
    </ul>
</div>  
<?php 
    die;
}

The JS .. (assuming it was enqueued and localized)

jQuery(document).ready(function($) {
    $('a.myajax').click(function(){
        var data = {
            action: 'searchmap' // <--- this is the correct action name
        };
        $.post( MyAjax.ajaxurl, data, function(response) {
            $('#myresult').html(response);
        });
        return false;
    });
});

And then the actual HTML needed in the page to trigger the action..

<a class="myajax" href="#">Click me to fetch ajax content</a>
<div id="myresult"></div>

Actual Answer

With regard to needing to do your own thing, and get vars printed out for your script, i'd suggest doing something like this...

add_action( 'wp_head', 'my_js_vars', 1000 );

function my_js_vars() {

    // If it's not a specific page, stop here
    if( !is_page( 'my-page-with-ajax' ) )
        return;
    ?>
    <script type="text/javascript">
    /* <![CDATA[ */
    var MyAjax = {
        ajaxurl: '<?php admin_url('admin-ajax.php'); ?>',
            somevar: 'somevalue',
            someothervar: 'someothervalue'
    };
    /* ]]> */
    </script>
    <?php
    /*
       NOTE: 
       Make sure not to leave a comma after the last item 
       in the JS array, else IE(Internet Explorer) will choke on the JS.
    */
}

I left code that i previously posted for the sake of others reading.

10
  • thank you. so how can I then call a function inside of my function.php via ajax? I updated my question. I would really appreciate your help with that! Commented Mar 28, 2011 at 12:57
  • Updated answer, see above. :)
    – t31os
    Commented Mar 28, 2011 at 13:09
  • thank you, how about the wp_enqueue_script(); and the wp_localize_script() line? Do I have to keep them? Should wp_enqueue_script() point to the same directory as my normal js file (where I want to call the ajax)? Because otherwise I cannot use MyAjax.ajaxurl, { action : 'wp_ajax_nopriv_searchmap', } in order to call the script - because MyAjax doesn't exist if I don't use the localize_script thingy? What would my javascript look like to call this function? Commented Mar 28, 2011 at 13:16
  • @mathiregister: thats right you have to keep them, if you don't use p_enqueue_script(); to enqueue it in the WordPress way then you cant use wp_localize_script() since that script is not known to WordPress, you can print out the script and define the the ajax url in php but that would be bad practice. and last your action : 'wp_ajax_nopriv_searchmap' should be action : 'searchmap' the hook prifix is done for you.
    – Bainternet
    Commented Mar 28, 2011 at 13:49
  • @mathiregister - Have updated my answer again for you.
    – t31os
    Commented Mar 28, 2011 at 13:56
1

This tutorial in the codex gives a straightforward overview of the process:

http://codex.wordpress.org/AJAX_in_Plugins

Note that the ajaxurl variable is already defined by WP core, but only in the admin area. To add it in the front-end, use:

<?php
function pluginname_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
add_action('wp_head','pluginname_ajaxurl');
3
  • Ah, but there's a catch, it's not always defined, i got caught out when i tried using that... At least it wasn't always available in my testing, and not for guest users.
    – t31os
    Commented Mar 28, 2011 at 14:32
  • Indeed, added clarification.
    – scribu
    Commented Mar 28, 2011 at 16:48
  • 1
    Otto with a code snippet how to define the variable in the frontend - wordpress.org/support/topic/… Commented Oct 7, 2012 at 14:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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