title: Ajax to php and then php to Ajax
body: <p>I have index.php with html form, user enters data, submits form (with ajax/jquery), server calls REST service with form params, parses response and sends result (array as json) to javascript on that same index.php. The part that <strong>is not working in my code is sending response back to javascript.</strong> It sends hardcoded array json for testing purpose but fails with dinamic response from REST. REST itself is ok and return correct data with var_dump().</p>
  
  <p>index.php</p>
  
  <pre><code>&lt;?php
  
  //index.php
  
  ...
  
  //submiting form
  
  &lt;script language ="javascript" type = "text/javascript" &gt;
  
      function submitForm()
      {
         $("#gl_forma").submit();
      }
  
  &lt;/script&gt;
  
  ...
  
  if(!empty($params['arg1']) )
  {
      $result = call_rest_service($connection, $params);//its ok
  
      //send POST to ajax.php that is just for echoing to javascript
      $response = sendPost('http://127.0.0.1/mysite/ajax.php', $result);
  }
  //function to send POST
  function sendPost($url, $data)
  {   
      $options = array(
          'http' =&gt; array(
          'method'  =&gt; 'POST',
          'content' =&gt; json_encode($data),// here encodes it
          'header'=&gt;  "Content-Type: application/json\r\n" .
          "Accept: application/json\r\n"
          )
      );
  
      $context  = stream_context_create( $options );
      $result = file_get_contents( $url, false, $context );
      return $response = json_decode($result);        
  }
  
  ...
  
  &lt;script language ="javascript" type = "text/javascript" &gt;
  //get back data from php to js
  
  //#search_button the same button that submited form
  
  $(document).ready( function() {
      $('#search_button').click(function() {
            $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: 'id=testdata',
            dataType: 'json',
            cache: false,
            success: function(result) {
              alert(JSON.stringify(result));//alerts the hardcoded array for testing, but wont real results
            },
            });
      });
  });
   &lt;/script&gt;
  </code></pre>
  
  <p>ajax.php - just for echoing results to javascript</p>
  
  <pre><code>&lt;?php
  
      //ajax.php
  
      $data = file_get_contents('php://input');//catch POST
      $_REQUEST = array();    
      file_put_contents('file.txt', $data, FILE_APPEND );//it writes, just for debuging...
      echo $data;//its encoded already
  </code></pre>