• Resolved yessoftmk

    (@yessoftmk)


    Hi, I successfully make a ajax post request from frontend:

    <script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function() {
    var ajaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";

    document.getElementById('myButton').addEventListener('click', function(e) {
    e.preventDefault();

    var message = document.getElementById('ai-input-title').value;

    var data = new FormData();
    data.append('action', 'send_request_to_backend');
    data.append('message', message);

    fetch(ajaxUrl, {
    method: 'POST',
    body: data
    })
    .then(response => response.text())
    .then(response => {
    alert('answer: ' + response);
    })
    .catch(error => console.error('err:', error));
    });
    });
    </script>

    But I need run this code in WP backend (while post add / edit). When I run this code in post add / edit screen, I have 404 error…. In error message I see:

    <?php%20echo%20admin_url(%27admin-ajax.php%27);%20?>

    How fix this problem? Thanks

Viewing 2 replies - 1 through 2 (of 2 total)
  • To fix the 404 error when making AJAX requests from the WordPress backend, use wp_ajax_url() instead of admin_url('admin-ajax.php'). Alternatively, enqueue a script specifically for the backend and use the ajaxurl global variable. This ensures the correct AJAX URL is used, resolving the issue.

    Thread Starter yessoftmk

    (@yessoftmk)

    thanks. work

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.