0

I'm trying to pass a JS variable to PHP via ajax but keep getting a 400 error. https://www.youtube.com/watch?v=DXK9XDN9puY

MAMP on MacOS

    <script type="text/javascript">
      jQuery(document).ready(function() {
        var test = '667'
        //console.log(test)

        jQuery.ajax({
          url: '/wp-admin/admin-ajax.php',
          data: {
            'action': 'php_tutorial',
            'php_test': test
          },
          success: function(data) {
            console.log("Happy")
          }
        });

      });
    </script>

    <?php
    function our_tutorial()
    {
      if (isset($_REQUEST)) {
        $testing = $_REQUEST['php_test'];

        echo 'This is our JS Variable :' . $testing;
      }
      die();
    }
    add_action('wp_ajax_php_tutorial', 'our_tutorial');

I must be missing something, somewhere...

Errors: POST https://ezy-rebuild:8890/wp-admin/admin-ajax.php Status 400 Bad Request VersionHTTP/1.1 Transferred519 B (1 B size) Referrer Policystrict-origin-when-cross-origin DNS ResolutionSystem

Cache-Control no-cache, must-revalidate, max-age=0 Connection close Content-Type text/html; charset=UTF-8 Date Fri, 25 Aug 2023 05:35:50 GMT Expires Wed, 11 Jan 1984 05:00:00 GMT Referrer-Policy strict-origin-when-cross-origin Server Apache/2.4.54 (Unix) mod_fastcgi/mod_fastcgi-SNAP-0910052141 OpenSSL/1.0.2u mod_wsgi/3.5 Python/2.7.18 Transfer-Encoding chunked X-Content-Type-Options nosniff X-Frame-Options SAMEORIGIN X-Powered-By PHP/7.4.33 X-Robots-Tag
Accept / Accept-Encoding gzip, deflate, br Accept-Language en,en-US;q=0.5 Connection keep-alive Content-Length 32 Content-Type application/x-www-form-urlencoded; charset=UTF-8

Host ezy-rebuild:8890 Origin https://ezy-rebuild:8890 Referer https://ezy-rebuild:8890/testie/

Vel
  • 9,027
  • 6
  • 34
  • 66
  • Not sure how you could get a CORS issue, when you appear to be making a request to a relative URL? (`base` element with a different origin than the one you are on, perhaps?) Please quote the error message verbatim. – CBroe Aug 25 '23 at 05:49
  • updated with error message – Peter Williamson Aug 25 '23 at 06:47
  • 1
    That is not a CORS error. You simply got a 400 Bad Request response. Could perhaps be as simple as https://stackoverflow.com/a/68120609/1427878 - you need to add an `wp_ajax_nopriv` action as well, if this is supposed to work for not logged-in frontend users. – CBroe Aug 25 '23 at 06:53

0 Answers0