Matteo Serpentoni
Matteo Serpentoni

Reputation: 573

Wordpress Ajax returns a 404 error

I want to develop a Wordpress plugin. So, I want to call Ajax function when I click on button in my php code.

This is my php code:

function unilang_translation_page() {

            echo '<div class="wrap"><h1>Translations of strings</h1> </div>'; 

            $unilang_table_strings = new Unilang_Table_Strings;
            $unilang_table_strings->prepare_items(); 
            $unilang_table_strings->display();

            $_SESSION['store_table_strings'] = serialize( $unilang_table_strings );

            echo "<a type='button' class=\"button button-primary\" onClick=\"Utility.saveStringTranslations();\">Submit Changes</a>";
} 

And this is my javascript file:

var Utility = {

    saveStringTranslations: function() {
        $.ajax({
            type: "POST",
            url: "/unilang/php/unilang-save-string-translations.php",
            success: function(data) {
                alert(data);
            },
            error: function(error) {
                alert(error);
            }
        })
    }
}

When I click on the button the browser console returns this: enter image description here

I tried to change path but it doesn't works. How can I set my plugin path in the URL?

Upvotes: 0

Views: 416

Answers (1)

Outsource WordPress
Outsource WordPress

Reputation: 3799

Try declaring a JavaScript variable in your plugin PHP file like below

<script> var plugin_url = '<?php echo plugins_url( '/unilang/php/unilang-save-string-translations.php', __FILE__ ) ?>'; </script>

and call the plugin_url variable in the AJAX URL path - url: plugin_url + "/unilang/php/unilang-save-string-translations.php".

Hope this helps and you can read more here - https://codex.wordpress.org/Function_Reference/plugins_url.

Upvotes: 1

Related Questions