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

2
  • See also: stackoverflow.com/questions/8599595/… Commented Jun 15, 2016 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. Commented Jun 15, 2016 at 17:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.