PHP, JSON and JavaScript in Web2.0 Applications

As Web 2.0 design trends are gradually becoming de-facto standard for all of the new web applications, PHP developers need to pay attention. Comfortable server-side PHP programming, dynamic generation of the HTML output for the entire page, handling of the Post requests from HTML forms and server-side validation are not going to cut it anymore. Customers demand rich web based Graphic User Interface, desktop like behavior of the web applications and with that demands comes a number of all too familiar names: JavaScript and Ajax, asynchronous requests, event driven programming and of course JSON(JavaScript Object Notation). The good news is that PHP is not going anywhere of course and the client applications cannot do much without the server support. Using JavaScript with JSON and PHP on the back end provides a very powerful tool for PHP developers writing Web 2.0 applications. It also brings about the challenge of debugging of PHP application designed to respond to XHR (XMLHttpRequest- used in Ajax) calls. As you can guess, traditional print and echo based debugging is not very useful when the developer can not see the output of the PHP script. The time might be here when even the most hard-core PHP developer should give PHP Editor and PHP IDE another thought, similar to the way we did it in this article describing Debugging PHP, JSON and JavaScript with PHP Debugger.



Sending requests to PHP with Dynamic Script Injection



JSON(JavaScript Object Notation) is a lightweight data-interchange format. You can learn everything about JSON at www.json.org. JSON is:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence
The idea of transferring the data from the server to JavaScript in JSON formatted strings is very attractive, because JavaScript receives these strings automatically converted to native JavaScript Objects. It doesn’t need to parse it or massage it in any other way. Instead it can simply use the dot notation to immediately access the elements inside the object. For example, if PHP script produces the line like this:
{ "Order" : {"item_name":"PHP IDE", "item_price":"199"} };
JavaScript will get the object Order with the data members item_name and item_price. Calling alert (Order.item_name) will display "PHP IDE" and alert (Order.item_price) will show 199.
JSON has become very popular on the web and many web services, such as Yahoo are now providing output in JSON format. But what really makes JSON shine in Web 2.0 applications is the method of Dynamic script injection to retrieve JSON data. The idea of Dynamic Script Injection is quite simple:
  • JavaScript is a dynamic language. You can add a <script> element to your document on the fly. All you need to do is set the source of the script to be the URL of your server side script (PHP script in our case) and the result will be a request sent to this script when you add this script element to the document. For example, here is a simple HTML file with embedded JavaScript making use of Dynamic Script Injection:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Really Cool Cars</title>
      
      <script language="javascript">
          /**
         * Requests the ad object using a cross domain call.
         * This function is to be called on page load to get the JSON text with the Ad    
         */
          function getAd() {
          
                //shamelessly hard code the url of the request
                var request = "http://localhost/GiveAd.php?clientId=really_cool_cars&callback=showAd";

                //Construct script node and add it to the document, causing the Get request
                //to the PHP script
                
                //Check for the existing script node
                var oScript = document.getElementById("dynamic_script_injection_node");

              // Get the script tag, if it exists
                  var head = document.getElementsByTagName("head").item(0);
               // Remove the tag, if it exists to avoid the increase in size
              if (oScript) {
                    
                    head.removeChild(oScript);
              }

                script = document.createElement("script");
                script.setAttribute("id", "dynamic_script_injection_node");
                script.setAttribute("type", "text/javascript");
                script.setAttribute("src", request);
                // all set, add the script
                head.appendChild(script);
          }
          /*
           * THis function is called when the JSON string is returned from GiveAd.php
           */
          function showAd(Ad) {
           
           // Find the div where the ad will be displayed
           var divElem = document.getElementById ("addDisplay");
           
           //Using dot notation collect the data from Ad object sent by GiveAd.php
           var title = "<h1 align='center'>"+Ad.Title+"</h1><br>";
           var punchLine = "<p align='center'>"+Ad.Ad_Body.Punch_line+"<br>";
           var url = "<a href='http://"+Ad.Ad_Body.URL+"'>"+Ad.Ad_Body.URL+"</a></p>";

            //put the content of the ad into div
            divElem.innerHTML = title+punchLine+url;       
           
           
          
          }
       </script>
    </head>

    <body  onload="javascript:getAd()">

     <div id="addDisplay" style="width:400px; height:400px; border:solid;">
     
     </div>

    </body>
    </html>


  • Contnue to Part 2 of PHP, JSON and JavaScript in Web2.0 Applications
© Copyright 2003-2014 www.php-editors.com. The ultimate PHP Editor and PHP IDE site.