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.

Cross-Origin Read Blocking (CORB)-Resolved

Each... You can listen, but not everyone is worth talking to.
Arthur Schendhauer

When you try to send a jQuery JSON request from another domain, you receive an error:

Access to XMLHttpRequest at ‘ http://* ‘ from Origin ‘ http://* ‘ has been blocked by CORS policy: No ‘ Access-Control-Allow-Origin ‘ header is present on the requested resource.

jquery. js? ver = *: 4 Cross-Origin Read Blocking (CORB) blocked cross-origin response * with MIME type application/JSON. See https://www.chromestatus.com/feature/5629709824032768 for more details. 

This means that sharing resources between different sources (CORS) is not allowed.

In order to allow CORS, it is necessary at the beginning of the PHP script, which processes the request, to add the generation of server response headers indicating that CORS is allowed.

<?php
switch ($ _server['HTTP_ORIGIN']) {
  Case 'http://remote.domain': Case 'https://remote.domain':
  Header ('Access-Control-Allow-Origin: '. $_server['HTTP_ORIGIN']);
  Header ('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
  Header ('Access-Control-Max-Age: 1000');
  Header ('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
  break;
}
?>
  • http://remote.domain-the URL of the site from which the request may occur.

On the client side, you need to specify crossDomain: true:

<script>
jQuery.ajax({
  crossDomain: true,
  dataType: "json",
  method: "POST",
  url: "http://main.domain/script.php",
  data: { key: "some text" }
  }).done(function( msg ) {
  // answer
});
</script>

So, to pass a request from one site to another, you need to specify the server headers that allow requests from a certain remote domain in the receiving site. And on the remote site, write a key that indicates that this query will work between different domains.