AJAX PHP JQUERY Transfer POST Request

In order to send a POST request to PHP script via JQUERY AJAX, create 2 files:

jqtest.htm – in which will be the request form and JavaScript code to generate and send the request;

jqtest.php – for receiving and sending the answer.

Listing of the file jqtest.htm:

<div>
<label for="request">Request:  </label>
<input id="request">
<input type="submit" value="Send" onclick="send();">
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
  function send()
  {
    jQuery.ajax({
      dataType: "json",
      method: "POST",
      url: "jqtest.php",
      data: { msg: jQuery('#request').val()}
    }).done(function( msg ) {
      alert(msg['answer']);
    });
  }
</script>

Listing of the file jqtest.php:

<?php
$q = ($_POST['msg']);
$ans= array(
  'answer' => 'You send: '.$q,
);
echo json_encode($ans);
?>

JQUERY query passes the MSG key in JSON format, and PHP code generates a JSON response and returns it in the answer key.