2

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 ‘);
    }
});
2
  • 1
    WordPress won't interfere with your front end scripts like that. Can you please include the full context of where you're setting the URL in the script, relative to the rest of the script that you've included. Keep in mind that ‘test/file.html’; is a relative URL, and will be appended to whatever the current URL is. You should include the full URL to the file to avoid this. Commented Jul 30, 2018 at 16:03
  • Whether I used a relative path or url it didn't matter. WordPress appends both to the $ajaxurl. Commented Aug 1, 2018 at 4:52

1 Answer 1

0

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

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.