FiddlingAway
FiddlingAway

Reputation: 2253

AJAX response in WordPress administration empty but the browser response is not empty

I've added a custom page in wp-admin. The page, among other things, has this script:

  <script>
    (function ($) {
      $(document).ready(function() {
        $("#mybtn").on("click",function(e) {
          $.ajax({
            'url': '<?=get_home_url()?>/myscript.php',
            'data': {'admin':1},
            'datatype': 'json',
            'type': 'POST',
            'cache': false,
            success:function(data) {
              console.log(data);
            },
            error: function (desc, err) {
              alert("Details: " + JSON.stringify(desc) + "\nError: " + JSON.stringify(err));
            }
          });
        });
      });
    })(jQuery);
  </script>

The response of the script, when viewed in the Network tab of the browser's inspector is not empty - depending on what happens in the background (server), its contents may vary, but it's always a JSON, and never empty.

However, the console.log(data) bit shows up as undefined. I'm obviously doing something wrong, but I have no idea what. The WP site in question has no caching plugins, WP administration is accessed through different browsers and computers, and it's always the same - browser sees the server response, AJAX's console.log doesn't.

I've also tried replacing $ with jQuery, but the results were the same. Adding async:true and async:false also did nothing.

I've also replaced the entire contents of myscript.php with this:

<?php
    echo json_encode(["error"=>1,"message"=>"Failed to update!","start"=>$start,"end"=>date("Y-m-d H:i:s")],JSON_UNESCAPED_UNICODE);
    die();
?>

and still had the same results - browser's inspector's response is fine, console.log() is undefined.

What am I doing wrong?

Upvotes: 0

Views: 254

Answers (1)

Hems
Hems

Reputation: 289

  1. the 'datatype' option you have specified should be 'dataType' (case-sensitive I believe)

  2. try using the 'contentType' option as so:

    contentType: "application/json; charset=utf-8"

Upvotes: 2

Related Questions