How do I set the url to make an ajax request for a html document?

I have a javacript file that uses ajax to load an html document, but WordPress changes the url. Is there a way to set the url so that WordPress doesn’t change it?

var file =  ‘test/file.html’;

WordPress appends the file to /wp-admin/ and sets the path to
http://localhost/wordpress/wp-admin/test/file.html

When I change the file path to http://localhost/wordpress/wp-content/plugings/test/file.html, WordPress still uses the ajaxurl global variables and sets the path to the wp-admin directory. Here’s the code:

return $.ajax({
    type: 'get',
    dataType: 'html',
    url: file,   
    success: function (resp) {
        alert(‘Success’);
    },
    error: function (jqXHR) {
        alert('Error ‘);
    }
});

1 Answer
1

Yes, there is such way: you should pass absolute path in there…

Let’s say your JS file is enqueued like this:

wp_enqueue_script( 'my-script', 'path-to-js-file.js'... );

Then you should use wp_localize_script and pass the value in there:

wp_localize_script( 'my-script', 'MyScriptData', array( 'ajax_url' => site_url('/test/file.html') ) );

Then you can access this value in your JS file this way:

return $.ajax({
    type: 'get',
    dataType: 'html',
    url: MyScriptData.ajax_url, // <-- here you get that value...
    success: function (resp) {
        alert(‘Success’);
    },
    error: function (jqXHR) {
        alert('Error ‘);
    }
});

BUT…

You should know, that you SHOULD process AJAX requests using proper actions and not with some external file. Here you can read more about dealing with AJAX in WordPress: AJAX in Plugins

Leave a Comment