1

I am trying to receive and print json with this php code:

<?php

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

?>

I am not receiving or printing any data. But if i use this ajax:

<script    src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">    </script>
<script>
(function($){
    function processForm( e ){
        $.ajax({
               url:'http://mydyndns:8010/has/input_parameters_startReg.php',
            dataType: 'json',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ DeviceID: 23, ForceReg: 0, StartTime: "10/06/2015 17:45"}),
             success: function (data) {
        },
        error: function (e) {
            alert(e.responseText);
        },
    });

        e.preventDefault();
    }

    $('#my-form').submit( processForm );
})(jQuery);

it is working, and i get the posted data printed in my browser. How can i alter my php so the direct hitting from browser will give me the result the ajax gives?

heinst
  • 8,520
  • 7
  • 41
  • 77
Martin k
  • 181
  • 15
  • Do you pass any parameters to the first script ? I mean, do you run it like test.php?a=123 ? If you don't send any input to it, it won't output anything – m_pro_m Jun 10 '15 at 17:30
  • yes i am running it like this: http://mydyndns/has/input_parameters_startReg.php?StartTime=10/06/2015%2017:50&ForceReg=0&DeviceID=23 but i get nothing – Martin k Jun 10 '15 at 17:34
  • 1
    It looks like php://input reads only POST data [as written here](http://stackoverflow.com/a/2731431/4177605) – m_pro_m Jun 10 '15 at 17:41
  • SO is there a way or another function that wil work with GET method? – Martin k Jun 10 '15 at 17:44
  • [this](http://stackoverflow.com/questions/8893574/php-php-input-vs-post) might help to understand what's going on – Laurent S. Jun 10 '15 at 18:07

2 Answers2

2

Function parse_str will do the job in combination with $_SERVER['QUERY_STRING']

<?php
 parse_str($_SERVER['QUERY_STRING'], $output);
 $json = json_encode($output);
 echo $json;
?>
m_pro_m
  • 340
  • 4
  • 11
  • Just wondering if using parse_str with QUERY_STRING is a better method than using $_GET ? – Phil Jun 10 '15 at 18:22
  • Good point, $_GET is actually the $output in this case so using $_GET would save that one step – m_pro_m Jun 10 '15 at 18:27
0

I don't think you'll be able to fetch it using GET because php://input seems to only read POST data. If you want to be able to use the GET data, you can refer to the $_GET global:

print_r($_GET);

Note that you can also use $_POST in place of php://input, but here's a question/answer on here that talks about that some:

PHP "php://input" vs $_POST

EDIT: Oops, I see this was answered while I was taking my sweet time.

Community
  • 1
  • 1