Ajax:JSON数据第1行第1列的意外字符

I'm new to AJAX. I've looked at previous postings and see this is a common question. The usual answer is that the data isn't actually in JSON format. This is certainly true in my case - the correct response is preceded by other data from earlier echo output, like this:

<button type="button" id="dotest" name="dotest" >SAVE</button>{"foo":"bar"} 

This is the test code that creates this output:

HTML

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script src="../js/jquery-3.3.1.min.js"></script>
</head>
<body>
<?php include "../php/bin/test-bin.php"; ?>
<script src="../js/test.js"></script>
</body>
</html>

JS

$('#dotest').click(function(){testCode()});
function testCode()
{
    $.ajax({
      type: 'POST',
      dataType: 'json',
      data: {testvar:true},
      url:'../php/bin/test-bin.php',
      success: function(formdata) {
       alert(formdata['foo']);
      },
      error: function(xhr, status, error) {
        alert(xhr.responseText);
      },
    });
}

PHP

<?php
echo '<button type="button" id="dotest" name="dotest" >SAVE</button>';
if(filter_has_var(INPUT_POST, 'testvar'))
{
  $myArr = array("foo" => "bar");
  $json = json_encode($myArr);
  return;
}

If I move the echo button statement to the end of the PHP code, the unwanted text doesn't appear in the response.

Have I some error in my code? Or is there some way to flush the PHP output after echo calls? I've tried flush() but it doesn't work.

Any help you can give would be good for my blood pressure!

EDIT

I've done what's suggested and put the Ajax call in a separate file. I get the same problem. In testing I've removed almost all the code, leaving this (the requires and defines do nothing at this point):

<?php

// include global constants etc
require_once(__DIR__.'/../inc/config.php');
require_once(__DIR__.'/../inc/errorhandler.php');
require_once(__DIR__.'/../inc/common.php');

// fl_data
@define('FL_PREVVAL', 0);
@define('FL_CURRVAL', 1);

$data = array('animal' => 'horse', 'vehicle' => 'cart');
$json = json_encode($data);
echo $json;

The Ajax response is an error, but xhr.responseText contains correctly formatted JSON.

If I remove the two define statements, the response is success with the same data. Putting back any code preceding the echo produces the same error situation.

What am I doing wrong!