0

Can you please let me know how I can pass a template directory instead of

http://localhost:8080/WP/wp-content/themes/twentyseventeen/data.php

into the URL option of an ajax call like below

var request = $.ajax({
    type: "POST",
    url: "http://localhost:8080/WP/wp-content/themes/twentyseventeen/data.php",
    cache: false,
    dataType: "HTML",
    success: function() {}
});
1
  • Can you be more specific about what you mean by a template directory? Keep in mind that calling files in your theme directly is a security risk and can cause a lot of problems. WP already provides the REST API for making requests, and there's the old WP Admin AJAX. You should never have to make requests directly to a theme. Additionally, look into child theming so your edits aren't deleted when twentyseventeen gets updated
    – Tom J Nowell
    May 17, 2018 at 22:09

1 Answer 1

1

I suspect you don't want to hardcode your URL to data.php, but using a standalone file to handle requests in a theme or plugin is a major security problem.

Instead, using a REST API endpoint.

For example, lets register a data endpoint:

add_action( 'rest_api_init', function () {
        register_rest_route( 'monacoder/v1', '/data/', array(
                'methods' => 'POST',
                'callback' => 'monacoder_data'
        ) );
} );
function monacoder_data( $request ) {
    return "response";
}

Now we can see that if we POST a request to http://localhost:8080/WP/wp-json/monacoder/v1/data/ in javascript, that it responds with the value "response". The code can go in your functions.php or a plugin, just make sure to have permalinks turned on.

Additionally, we can enqueue the wp-api library:

wp_enqueue_script( 'wp-api' );

Now you have the URL available in javascript at wpApiSettings.root, so you can do this:

jQuery.ajax({
    type: "POST",
    url: wpApiSettings.root + "monacoder/v1/data",
    success: function() {
        // do something
    }
});

You can also use the wp-api library to fetch posts, e.g:

var postsCollection = new wp.api.collections.Posts();
postsCollection.fetch();
postsCollection.forEach(function( post ) {
    console.log( post );
});

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.