Publishing AJAX and PHP - part 7 pptx

10 272 0
Publishing AJAX and PHP - part 7 pptx

Đang tải... (xem toàn văn)

Thông tin tài liệu

Client-Side Techniques with Smarter JavaScript 60 Open the Firefox JavaScript console from Tools | JavaScript Console. Please see Appendix B at http://ajaxphp.packtpub.com for more details about the JavaScript Console and other excellent tools that help with debugging. Figure 2.8: The Firefox JavaScript Console is Very Useful What's really nasty is that all tested browsers except Internet Explorer (all versions) don't catch the error using the try/catch mechanism that exists in place for exactly this kind of errors. Just like Firefox, Mozilla 1.7 doesn't throw any errors, and to make things even worse, it doesn't say anything even in its JavaScript console. It simply ignores everything and behaves like nothing bad happened, as shown in Figure 2.9 (the output is similar to Firefox's). Figure 2.9: Mozilla Keeps the Problem Secret Opera, on the other hand, is friendlier (if you're the developer, at least). While it completely ignores the try/catch blocks that were supposed to catch the error, it displays a very detailed error message. While this is good for development, for certain you don't want your visitors to see anything like that: Chapter 2 Figure 2.10: Opera Displays the Most Helpful Error Message For some reason, at the time of writing, Internet Explorer seems to be the only browser where our catch block intercepts the exception, and displays an error message (not a very helpful one, though): Figure 2.11: Exception Caught by Internet Explorer Either by design or by default, web browsers don't do very a good job at trapping your errors as we would expect them to. Since certain kinds of errors are not trappable by normal try/catch mechanisms, it is important to find alternative solutions (because, the good news is, there are solutions). You can fix your XML reading code by updating the handleServerResponse function like this: // handles the response received from the server function handleServerResponse() { // read the message from the server var xmlResponse = xmlHttp.responseXML; // catching potential errors with IE and Opera if (!xmlResponse || !xmlResponse.documentElement) throw("Invalid XML structure:\n" + xmlHttp.responseText); // catching potential errors with Firefox var rootNodeName = xmlResponse.documentElement.nodeName; if (rootNodeName == "parsererror") throw("Invalid XML structure:\n" + xmlHttp.responseText); // obtain the XML's document element 61 Client-Side Techniques with Smarter JavaScript 62 xmlRoot = xmlResponse.documentElement; // obtain arrays with book titles and ISBNs titleArray = xmlRoot.getElementsByTagName("title"); isbnArray = xmlRoot.getElementsByTagName("isbn"); // generate HTML output var html = ""; // iterate through the arrays and create an HTML structure for (var i=0; i<titleArray.length; i++) html += titleArray.item(i).firstChild.data + ", " + isbnArray.item(i).firstChild.data + "<br/>"; // obtain a reference to the <div> element on the page myDiv = document.getElementById("myDivElement"); // display the HTML output myDiv.innerHTML = "Server says: <br />" + html; } With Internet Explorer and Opera, the documentElement property of xmlResponse object will be null if the underlying XML document is not valid. With Firefox, the XML document will be perfectly valid, but the document itself will be replaced by one containing the error details (yes, an interesting way to report errors); in such cases the document element will be called parsererror. When we find out there's something wrong with the received XML document, we throw an exception. Throwing an exception means generating a custom-made exception, and is done using the throw keyword in JavaScript. This exception will be caught by the catch block in handleServerResponse, and will get displayed to the visitor: Figure 2.12: Error Message that Gets Displayed by All Tested Browsers Chapter 2 I admit that the following piece of code may have puzzled you: if (!xmlResponse || !xmlResponse.documentElement) throw("Invalid XML structure:\n" + xmlHttp.responseText); Apparently, if xmlResponse is void, we risk generating another error when trying to read its documentElement property. In practice, the JavaScript interpreter only evaluates logical expressions when necessary, and it does so from left to right. In our particular case, if (!xmlResponse) is true, the second expression isn't evaluated at all, because the end result is true anyway. This feature, which is implemented in JavaScript and other languages, is called short-circuit evaluation and you can read more about it here: http://www.webreference.com/javascript/reference/ core/expr.html . Creating XML Structures XML and DOM are everywhere. In this chapter, you used the DOM to create HTML elements on the existing DOM object called document, and you also learned how to read XML documents received from the server. An important detail that we didn't cover was creating brand new XML documents using JavaScript's DOM. You may need to perform this kind of functionality if you want to create XML documents on the client, and send them for reading on the server. We won't go through more examples, but we will only show you the missing bits. The trick with creating a brand new XML document is creating the XML document itself. When adding elements to the HTML output, you used the implicit document object, but this is not an option when you need to create a new document. When creating a new DOM object with JavaScript, we're facing the same problem as with creating XMLHttpRequest objects; the method of creating the object depends on the browser. The following function is a universal function that returns a new instance of a DOM object: function createDomObject() { // will store reference to the DOM object var xmlDoc; // create XML document if (document.implementation && document.implementation.createDocument) { xmlDoc = document.implementation.createDocument("", "", null); } // works for Internet Explorer else if (window.ActiveXObject) { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); } // returns the created object or displays an error message if (!xmlDoc) alert("Error creating the DOM object."); else return xmlDoc; } After executing this function, you can use the created DOM object to perform whatever actions you want. For more details about creating the DOM object check the following link: http://www.webreference.com/programming/javascript/domwrapper/index.html. For details of using the DOM object, refer to the DOM articles mentioned earlier in this chapter. 63 Client-Side Techniques with Smarter JavaScript 64 Summary This chapter walked you through many fields. Working with HTML, JavaScript, CSS, the DOM, XML, and XMLHttpRequest is certainly not easy to start with, especially if some of these technologies are new to you. Where you don't feel confident enough, have a look at the aforementioned resources. When you feel ready, proceed to Chapter 3, where you will learn how to use PHP and MySQL on the server, and make them interact nicely with the AJAX-enabled client. 3 Server-Side Techniques with PHP and MySQL If AJAX is mainly about building smarter clients, then the servers these clients talk to must be equally smart, otherwise they won't get along very well for too long. In Chapter 2, you only read static text or XML files from the server. In this chapter, we start putting the server side to work, with PHP to generate dynamic output, and MySQL to manipulate and store the back-end data. In this chapter, you will learn how to: • Use PHP to perform functionality on the server side • Let clients communicate with the server by passing parameters • Use XML on the client and the server • Use PHP scripts to avoid potential JavaScript security problems • Perform repetitive tasks in your client • Work with MySQL databases • Optimize your application's architecture PHP and DOM In Chapter 2, you read data asynchronously from the server. While the mechanism is pretty standard and you will use the same routines many times in this book, what's unusual is that the data passed back from the server was a static file (either text or XML). In most real-world situations, you will need the server to do some processing, and generate some dynamic output. In this book, we will use PHP to do the server-side part of the job. If your background in PHP isn't strong, an online search for "php tutorial" will generate lots of interesting resources, including the official PHP tutorial at http://php.net/tut.php. If you enjoy learning by practicing, you may want to check out one of Cristian Darie and Mihai Bucica's e-commerce books, such as Beginning PHP 5 and MySQL E-Commerce: From Novice to Professional. You can even use the Suggest and Autocomplete application that you will build in Chapter 6, which finds the help page of the PHP functions for you. You will find the application at http://ajaxphp.packtpub.com/ajax/suggest/. Server-Side Techniques with PHP and MySQL 66 In the first exercise for this chapter, you will write a PHP script that uses the PHP's DOM functions to create XML output that will be read by the client. PHP's DOM functionality is similar to JavaScript's DOM functionality, and its official documentation can be found at http://www.php.net/manual/en/ref.dom.php. The XML document you will create on the server will be almost the same as the XML document you saved as a static XML file in Chapter 2, but this time it will be generated dynamically: <response> <books> <book> <title>Building Reponsive Web Applications with AJAX and PHP</title> <isbn>1-904811-82-5</isbn> </book> </books> </response> Time for Action—Doing AJAX with PHP 1. In the foundations folder create a subfolder called php. 2. In the php folder create a file named phptest.html, and add the following text to it: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>Practical AJAX: Using the PHP DOM</title> <script type="text/javascript" src="phptest.js"></script> </head> <body onload="process()"> The AJAX book of 2006 is: <br /> <div id="myDivElement" /> </body> </html> 3. The client-side code, phptest.js, is almost identical to books.js from the XML exercise in Chapter 2. The changed bits are highlighted: // holds an instance of XMLHttpRequest var xmlHttp = createXmlHttpRequestObject(); // creates an XMLHttpRequest instance function createXmlHttpRequestObject() { // will store the reference to the XMLHttpRequest object var xmlHttp; // this should work for all browsers except IE6 and older try { // try to create XMLHttpRequest object xmlHttp = new XMLHttpRequest(); } catch(e) { // assume IE6 or older var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"); // try every prog id until one works Chapter 3 for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) { try { // try to create XMLHttpRequest object xmlHttp = new ActiveXObject(XmlHttpVersions[i]); } catch (e) {} } } // return the created object or display an error message if (!xmlHttp) alert("Error creating the XMLHttpRequest object."); else return xmlHttp; } // read a file from the server function process() { // only continue if xmlHttp isn't void if (xmlHttp) { // try to connect to the server try { // initiate reading a file from the server xmlHttp.open("GET", "phptest.php", true); xmlHttp.onreadystatechange = handleRequestStateChange; xmlHttp.send(null); } // display the error in case of failure catch (e) { alert("Can't connect to server:\n" + e.toString()); } } } // function called when the state of the HTTP request changes function handleRequestStateChange() { // when readyState is 4, we are ready to read the server response if (xmlHttp.readyState == 4) { // continue only if HTTP status is "OK" if (xmlHttp.status == 200) { try { // do something with the response from the server handleServerResponse(); } catch(e) { // display error message alert("Error reading the response: " + e.toString()); } } else { // display status message alert("There was a problem retrieving the data:\n" + xmlHttp.statusText); 67 Server-Side Techniques with PHP and MySQL 68 } } } // handles the response received from the server function handleServerResponse() { // read the message from the server var xmlResponse = xmlHttp.responseXML; // catching potential errors with IE and Opera if (!xmlResponse || !xmlResponse.documentElement) throw("Invalid XML structure:\n" + xmlHttp.responseText); // catching potential errors with Firefox var rootNodeName = xmlResponse.documentElement.nodeName; if (rootNodeName == "parsererror") throw("Invalid XML structure"); // obtain the XML's document element xmlRoot = xmlResponse.documentElement; // obtain arrays with book titles and ISBNs titleArray = xmlRoot.getElementsByTagName("title"); isbnArray = xmlRoot.getElementsByTagName("isbn"); // generate HTML output var html = ""; // iterate through the arrays and create an HTML structure for (var i=0; i<titleArray.length; i++) html += titleArray.item(i).firstChild.data + ", " + isbnArray.item(i).firstChild.data + "<br/>"; // obtain a reference to the <div> element on the page myDiv = document.getElementById("myDivElement"); // display the HTML output myDiv.innerHTML = html; } 4. And finally, the phptest.php file: <?php // set the output content type as xml header('Content-Type: text/xml'); // create the new XML document $dom = new DOMDocument(); // create the root <response> element $response = $dom->createElement('response'); $dom->appendChild($response); // create the <books> element and append it as a child of <response> $books = $dom->createElement('books'); $response->appendChild($books); // create the title element for the book $title = $dom->createElement('title'); $titleText = $dom->createTextNode ('Building Reponsive Web Applications with AJAX and PHP'); $title->appendChild($titleText); // create the isbn element for the book $isbn = $dom->createElement('isbn'); $isbnText = $dom->createTextNode('1-904811-82-5'); $isbn->appendChild($isbnText); Chapter 3 // create the <book> element $book = $dom->createElement('book'); $book->appendChild($title); $book->appendChild($isbn); // append <book> as a child of <books> $books->appendChild($book); // build the XML structure in a string variable $xmlString = $dom->saveXML(); // output the XML string echo $xmlString; ?> 5. First let's do a simple test to see what phptest.php returns. Load http://localhost/ajax/foundations/php/phptest.php in your web browser to ensure it generates a well-formed XML structure: Figure 3.1: Simple XML Structure Generated by PHP If you don't get the expected result, be sure to check not only the code, but also your PHP installation. See Appendix A for details about how to correctly set up your machine. 69 . you will learn how to use PHP and MySQL on the server, and make them interact nicely with the AJAX- enabled client. 3 Server-Side Techniques with PHP and MySQL If AJAX is mainly about building. Web Applications with AJAX and PHP& lt;/title> <isbn> 1-9 0481 1-8 2-5 </isbn> </book> </books> </response> Time for Action—Doing AJAX with PHP 1. In the foundations. which finds the help page of the PHP functions for you. You will find the application at http://ajaxphp.packtpub.com /ajax/ suggest/. Server-Side Techniques with PHP and MySQL 66 In the first

Ngày đăng: 04/07/2014, 17:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan