0

i am new to php.I try to build a simple server with a get and post request method. The php server just need to take a json- data and save it(POST) and give it back to the user (get).

But for the beginning i try this:

PHP-code

    <?php
/*
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if ($_POST) {
    echo 'test post'; 
  } else {
    echo 'test post fehler'; 
  }
}
*/

  if ($_POST) {
    echo 'test post'; 
  } else {
    echo 'test post fehler'; 
  }

if ($_SERVER["REQUEST_METHOD"] == "GET") {
  if ($_GET) {
    echo 'test get'; 
  } else {
    echo 'test post get'; 
  }
}


?>

How can i make a methode in php to handle json array ?

JavaScript

<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="robots" content="noindex" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="../kern/esa.css" />
<script>
  window.onload = function () {
    //if (top["bib"]) { top.bib.dl({ doc: document, id: 'DL1', show_idx: [ ] }); } 
  };

  function btn0() {
    alert("test");
    var username = document.getElementsByName('username')[0].value;
    var antwort1 = document.getElementsByName('frag1')[0].value;
    var antwort2 = document.getElementsByName('frag2')[0].value;
    var antwort3 = document.getElementsByName('frag3')[0].value;
    //alert(username+" "+antwort1+" "+antwort2+" "+antwort3);
    //JSON
    var jsondata = {"data" :[
    {"name": username},
    {"antwort1":antwort1},
    {"antwort2":antwort2},
    {"antwort3":antwort3}]};
    //alert(jsondata.data[0].name);

    var url = "https://.../apps/server.php";
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "POST", url, true ); 
    xmlHttp.send(JSON.stringify(jsondata));
    alert(xmlHttp.responseText);

  };

</script>

Have i do everyhing correct?

thanks in advance

  • See also: http://stackoverflow.com/questions/8599595/send-json-data-from-javascript-to-php – Progrock Jun 15 '16 at 17:07
  • one thing that wont work is alerting the response, because that request is asynchronous, so you will not have any response there yet. – Jeff Jun 15 '16 at 17:07

1 Answers1

1
  <?php $json_data = json_decode($_POST["data"]);?>

As mentioned above, your request/alert is not written properly. responseText will not have your data yet.

ksealey
  • 1,698
  • 1
  • 17
  • 16
  • But i dont undertand how to make a methode. for example i try to post a date. get the post funktion the information of the client? i find somthing like this but i do not understand how it work : $rawdata = file_get_contents('php://input'); what is the ''php://input''. Or how can i check that the post methode was activated. – thenewOne1234567890 Jun 15 '16 at 17:15