Why Ajax Doesn’t Work?

Question

Good day!

I have a separate page at the root of WordPress, for processing certain data, with the "wp-load.php" file connected to it.

<?php

  require_once( dirname(__FILE__) . '/wp-load.php' );
  require_once( dirname(__FILE__) . '/wp-admin/includes/admin.php' );

  add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
  add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );

  function example_ajax_request() {
    if ( isset( $_REQUEST ) ) {
      $postID = $_REQUEST['postID'];
      print $postID;
    }
    wp_die();
  }

?><!doctype html>
<html lang="ru" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Outside page</title>

  <script src="https://yastatic.net/jquery/3.3.1/jquery.min.js"></script>

  <script>
    var ajaxurl = "<?php print admin_url( 'admin-ajax.php' ); ?>";
  </script>

  <script type="text/javascript">
    jQuery( document ).ready( function( $ ) {
      $( '#our-work a' ).click( function( e ) {
        e.preventDefault();

        var postID = $( this ).attr( 'data-id' );

        $.ajax({
          url: './wp-admin/admin-ajax.php',
          data: {
            'action' : 'example_ajax_request',
            'postID' : postID
          },
          success : function( data ) {
            $( '#hero' ).append( 'Well this seems to work' + data );
          },
          error : function(errorThrown){
            console.log( 'This has thrown an error:' + errorThrown );
          }
        });
        return false;
      });
    });
  </script>

</head>

<body>

  <p id="our-work">
    <a data-id="123" href=".">Get and push!</a>
  </p>

  <div id="hero"></div>

</body>

</html>

Unfortunately I am getting the error:

enter image description here

Why isn’t the Ajax code working here?

Do you need to connect any other file?

Thank you!

0
DokaPavel 7 months 2020-12-24T02:10:20-05:00 0 Answers 5 views 0

Leave an answer

Browse
Browse