0

Hoping There is an easy way to do this/I am doing something horridly wrong: I'm trying to simply display a list of post titles. When a user clicks on the title it will display that said title's content into a previously empty div on the same page with ajax.

however it won't work correctly if I switch around the permalinks etc or have a post that's url is a few directories deeps (ie: site.com/dir1/dir2/dir3/page, or site.com/dir1/page). It will ONLY work if I have site.com?p=23

BECAUSE of this relative url in my ajax request:

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

//whenever a title is clicked on: run this request
$('.get_post').click(function(e){

    e.preventDefault();

    $portfolioPostId = $(this).data('postid');  

    $.ajax({
        type: 'GET',
        url: '../wp-admin/admin-ajax.php',  //WON'T LOAD on any url that ISN'T like this format: site.com/?p=123
        data: {
            action: 'my_post',
            postid: $portfolioPostId
        },
        success: function(data){

            $('#well').html(' ');
            $('#well').html(data);




        },
        error: function(XMLHttpRequest, textStatus, errorThrown){

            console.log(errorThrown) + '\n';

        }

    });


});


});

So INSTEAD of having url: '/wp-admin/admin-ajax.php', how could I instead use an ABSOLUTE URL? Or is there something better that could be done?

EDIT: SOLUTION TO MY ISSUE:

Thanks to Rarst's answer I was able to find a way to pass the absolute URL.

On my php file where I enqueue my script, I also sent through an object called psAjax_object that contained the absolute URL to admin-ajax.php

function frontend_js(){

    wp_enqueue_script('shuffle_ajax', plugins_url( NAME . '/public/js/portfolio_grid_ajax.js'), array('jquery'), '', true );

    //creates the property for the 'psAjax_object'
    $localizedArray = array('ajax_url' => admin_url('admin-ajax.php'));

    //allows my portfolio_grid_ajax.js file to access 'psAjax_object'
    wp_localize_script('shuffle_ajax', 'psAjax_object', $localizedArray);

}
add_action('wp_enqueue_scripts', 'frontend_js');

and then in my js file i can access the absolute url by typing psAjax_object.ajax_url

  • You'll need to localize your script.. after you enqueue it to the frontend. Pass the admin_ajax() url in a javascript variable.. then access it in your ajax request. – josh Dec 22 '14 at 15:29
0

The normal practice is to generate URL on PHP side ( admin_url() ) and provide it to your script via localization functionality ( wp_localize_script() ). It is documented in Codex under Ajax on the Viewer-Facing Side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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