Javascript to JSON to PHP (and back)

5:25 pm Internet

I was working on a little project that involved having a javascript client talk to a PHP backend using the JSON format. Of course, the first thing I did was to google for a simple example of this. Unfortunately, the info was scattered across several sites so it required some detective work to stitch together all the different data to get a working example.

To hopefully save you the time, I will provide a working example of how to get Javascript to talk to PHP using JSON. I will follow the time-honored tradition of providing a Hello World example. Even though it is very boring, it does demonstrate the bare essentials of the code.

Below is the Hello World PHP server script (let us call it “hello.php”). It parses a JSON-formatted post body and responds in kind.

<?php

// Retrieve the request body
// The request body is expected to look like:
// {
//   "firstName" : "John",
//   "lastName" : "Doe"
// }
$reqBodyJSON = @file_get_contents('php://input');
$reqObj = json_decode($reqBodyJSON);

// Retrieve the first and last name
$firstName = $reqObj->firstName;
$lastName = $reqObj->lastName;

// Construct our json response which will be an array
// of two possible replies
$response = array(
   "friend" => "Hi, ".$firstName."!  I'm glad to see you!",
   "foe" => "Goodbye, Mr. ".$lastName."!  Go away, please!"
);

// Output json response header and body
header('Content-type: application/json');
echo json_encode($response);

?>

Below is the Hello World HTML and Javascript client (let us call it “hello.html”). It will call the PHP server and display one of the two returned responses (selected randomly). The client uses a lightweight javascript framework called Prototype to facilitate the Ajax call to the server; we will need the “prototype.js” to be placed on the server for retrieval by the javascript client.

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Hello World!</title>

<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">

function sayHello() {
  // Retrieve the values from the form
  var first = document.getElementById("firstName").value;
  var last = document.getElementById("lastName").value;

  // Construct request object
  var reqObj = {
    firstName : first,
    lastName : last
  };

  // Call the server
  new Ajax.Request('hello.php', {
    method : 'post',
    contentType : 'application/json',
    postBody : Object.toJSON(reqObj),
    requestHeaders : {Accept: 'application/json'},
    onSuccess : function (response) {
      // Get the response object
      var respObj = response.responseJSON;
      // Make our response random
      var isFoe = Math.floor(Math.random()*2+1); // 1 or 2
      var replyText;
      if (isFoe == 1) {
        replyText = respObj.foe;
      } else {
        replyText = respObj.friend;
      }
      document.getElementById("reply").value = replyText;
    },
    onFailure : function() {
      alert('Ajax call failed');
    }
  });
};

</script>
</head>

<body>
<h3>Hello World!</h3>

Please input your first and last name:
<form>
  First Name: <input id="firstName" type="textbox" value="George"><br>
  Last Name: <input id="lastName" type="textbox" value="Washington"><br>
  <input type="button" value="Say Hello" onclick="sayHello()">
  <br><br>
  Response: <input id="reply" type="textbox" readonly size="50"
             value="Press button for response!">
</form>
</body>
</html>

I hope that this example will help you in your explorations of web programming.

One Response
  1. DAvid :

    Date: December 3, 2015 @ 9:44 pm

    Thanks buddy, In a world of fools who keep complicating life needlessly, you are the only one who has explained the concept in way meant for humans. Keep up the good work

Leave a Comment

Your comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.