1. Trang chủ
  2. » Công Nghệ Thông Tin

Học php, mysql và javascript - p 40 docx

10 187 0

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 1,72 MB

Nội dung

Example 17-3. The adduser.php program <?php // adduser.php // Start with the PHP code $forename = $surname = $username = $password = $age = $email = ""; if (isset($_POST['forename'])) $forename = fix_string($_POST['forename']); if (isset($_POST['surname'])) $surname = fix_string($_POST['surname']); if (isset($_POST['username'])) $username = fix_string($_POST['username']); if (isset($_POST['password'])) $password = fix_string($_POST['password']); if (isset($_POST['age'])) $age = fix_string($_POST['age']); if (isset($_POST['email'])) $email = fix_string($_POST['email']); $fail = validate_forename($forename); $fail .= validate_surname($surname); $fail .= validate_username($username); $fail .= validate_password($password); $fail .= validate_age($age); $fail .= validate_email($email); echo "<html><head><title>An Example Form</title>"; if ($fail == "") { echo "</head><body>Form data successfully validated: $forename, $surname, $username, $password, $age, $email.</body></html>"; // This is where you would enter the posted fields into a database exit; } // Now output the HTML and JavaScript code echo <<<_END <! The HTML section > <style>.signup { border: 1px solid #999999; font: normal 14px helvetica; color:#444444; }</style> <script type="text/javascript"> function validate(form) { fail = validateForename(form.forename.value) fail += validateSurname(form.surname.value) fail += validateUsername(form.username.value) fail += validatePassword(form.password.value) fail += validateAge(form.age.value) fail += validateEmail(form.email.value) Redisplaying a Form After PHP Validation | 371 if (fail == "") return true else { alert(fail); return false } } </script></head><body> <table class="signup" border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee"> <th colspan="2" align="center">Signup Form</th> <tr><td colspan="2">Sorry, the following errors were found<br /> in your form: <p><font color=red size=1><i>$fail</i></font></p> </td></tr> <form method="post" action="adduser.php" onSubmit="return validate(this)"> <tr><td>Forename</td><td><input type="text" maxlength="32" name="forename" value="$forename" /></td> </tr><tr><td>Surname</td><td><input type="text" maxlength="32" name="surname" value="$surname" /></td> </tr><tr><td>Username</td><td><input type="text" maxlength="16" name="username" value="$username" /></td> </tr><tr><td>Password</td><td><input type="text" maxlength="12" name="password" value="$password" /></td> </tr><tr><td>Age</td><td><input type="text" maxlength="3" name="age" value="$age" /></td> </tr><tr><td>Email</td><td><input type="text" maxlength="64" name="email" value="$email" /></td> </tr><tr><td colspan="2" align="center"> <input type="submit" value="Signup" /></td> </tr></form></table> <! The JavaScript section > <script type="text/javascript"> function validateForename(field) { if (field == "") return "No Forename was entered.\\n" return "" } function validateSurname(field) { if (field == "") return "No Surname was entered.\\n" return "" } function validateUsername(field) { if (field == "") return "No Username was entered.\\n" else if (field.length < 5) return "Usernames must be at least 5 characters.\\n" else if (/[^a-zA-Z0-9_-]/.test(field)) return "Only a-z, A-Z, 0-9, - and _ allowed in Usernames.\\n" return "" } function validatePassword(field) { if (field == "") return "No Password was entered.\\n" else if (field.length < 6) 372 | Chapter 17: JavaScript and PHP Validation and Error Handling return "Passwords must be at least 6 characters.\\n" else if (!/[a-z]/.test(field) || ! /[A-Z]/.test(field) || ! /[0-9]/.test(field)) return "Passwords require one each of a-z, A-Z and 0-9.\\n" return "" } function validateAge(field) { if (isNaN(field)) return "No Age was entered.\\n" else if (field < 18 || field > 110) return "Age must be between 18 and 110.\\n" return "" } function validateEmail(field) { if (field == "") return "No Email was entered.\\n" else if (!((field.indexOf(".") > 0) && (field.indexOf("@") > 0)) || /[^a-zA-Z0-9.@_-]/.test(field)) return "The Email address is invalid.\\n" return "" } </script></body></html> _END; // Finally, here are the PHP functions function validate_forename($field) { if ($field == "") return "No Forename was entered<br />"; return ""; } function validate_surname($field) { if ($field == "") return "No Surname was entered<br />"; return ""; } function validate_username($field) { if ($field == "") return "No Username was entered<br />"; else if (strlen($field) < 5) return "Usernames must be at least 5 characters<br />"; else if (preg_match("/[^a-zA-Z0-9_-]/", $field)) return "Only letters, numbers, - and _ in usernames<br />"; return ""; } function validate_password($field) { if ($field == "") return "No Password was entered<br />"; else if (strlen($field) < 6) return "Passwords must be at least 6 characters<br />"; else if ( !preg_match("/[a-z]/", $field) || !preg_match("/[A-Z]/", $field) || !preg_match("/[0-9]/", $field)) return "Passwords require 1 each of a-z, A-Z and 0-9<br />"; return ""; Redisplaying a Form After PHP Validation | 373 } function validate_age($field) { if ($field == "") return "No Age was entered<br />"; else if ($field < 18 || $field > 110) return "Age must be between 18 and 110<br />"; return ""; } function validate_email($field) { if ($field == "") return "No Email was entered<br />"; else if (!((strpos($field, ".") > 0) && (strpos($field, "@") > 0)) || preg_match("/[^a-zA-Z0-9.@_-]/", $field)) return "The Email address is invalid<br />"; return ""; } function fix_string($string) { if (get_magic_quotes_gpc()) $string = stripslashes($string); return htmlentities ($string); } ?> The result of submitting the form with JavaScript disabled (and two fields incorrectly completed) can be seen in Figure 17-5. Figure 17-5. The form as represented after PHP validation fails 374 | Chapter 17: JavaScript and PHP Validation and Error Handling I have put the PHP section of this code (and changes to the HTML section) in a bold typeface so that you can more clearly see the difference between this and Examples 17-1 and 17-2. If you browsed through this example (or, hopefully, typed it in or downloaded it from the http://lpmj.net website), you’ll have seen that the PHP code is almost a clone of the JavaScript code; the same regular expressions are used to validate each field in very similar functions. But there are a couple of things to note. First, the fix_string function (right at the end) is used to sanitize each field and prevent any attempts at code injection from succeeding. Also, you will see that the HTML from Example 17-1 has been repeated in the PHP code within a <<<_END _END; structure, displaying the form with the values that the visitor entered the previous time. This is done by simply adding an extra value param- eter to each <input > tag (such as value="$forename"). This courtesy is highly rec- ommended so that the user has to edit only the previously entered values, and doesn’t have to type the fields in all over again. In the real world, you probably wouldn’t start with an HTML form such as the one in Example 17-1. Instead, you’d be more likely to go straight ahead and write the PHP program in Example 17-3, which incorporates all the HTML. And, of course, you’d also need to make a minor tweak for the case when it’s the first time the program is called up, to prevent it displaying errors when all the fields are empty. You also might drop the six JavaScript functions into their own .js file for separate inclusion. Now that you’ve seen how to bring all of PHP, HTML, and JavaScript together, the next chapter will introduce Ajax (Asynchronous JavaScript And XML), which uses JavaScript calls to the server in the background to seamlessly update portions of a web page, without having to resubmit the entire page to the web server. Test Your Knowledge: Questions Question 17-1 What JavaScript method can you use to send a form for validation prior to sub- mitting it? Question 17-2 What JavaScript method is used to match a string against a regular expression? Question 17-3 Write a regular expression to match any characters that are not in a word, as defined by regular expression syntax. Test Your Knowledge: Questions | 375 Question 17-4 Write a regular expression to match either of the words fox or fix. Question 17-5 Write a regular expression to match any single word followed by any nonword character. Question 17-6 Using regular expressions, write a JavaScript function to test whether the word fox exists in the string “The quick brown fox”. Question 17-7 Using regular expressions, write a PHP function to replace all occurrences of the word the in “The cow jumps over the moon” with the word my. Question 17-8 What HTML keyword is used to precomplete form fields with a value? See the section “Chapter 17 Answers” on page 449 in Appendix A for the answers to these questions. 376 | Chapter 17: JavaScript and PHP Validation and Error Handling CHAPTER 18 Using Ajax The term “Ajax” was first coined in 2005. It stands for Asynchronous JavaScript and XML, which, in simple terms, means using a set of methods built into JavaScript to transfer data between the browser and a server in the background. An excellent example of this technology is Google Maps (see Figure 18-1), in which new sections of a map are downloaded from the server when needed, without requiring a page refresh. Figure 18-1. Google Maps is an excellent example of Ajax in action 377 Using Ajax not only substantially reduces the amount of data that must be sent back and forth, it also makes web pages seamlessly dynamic—allowing them to behave more like self-contained applications. The results are a much improved user interface and better responsiveness. What Is Ajax? The beginnings of Ajax as used today started with the release of Internet Explorer 5 in 1999, which introduced a new ActiveX object, XMLHttpRequest. ActiveX is Microsoft’s technology for signing plug-ins that add additional software to your computer. Other browser developers later followed suit, but rather than using ActiveX, they all imple- mented the feature as a native part of the JavaScript interpreter. However, even before then, an early form of Ajax had already surfaced that used hidden frames on a page that interacted with the server in the background. Chat rooms were early adopters of this technology, using it to poll for and display new message posts without requiring page reloads. Nowadays, though, XMLHttpRequest is the way to go, and there have been numerous frameworks written to simplify its use. In fact, Chapter 19 introduces the powerful Yahoo! User Interface (YUI) JavaScript framework. But first, let’s see how to implement Ajax with raw JavaScript. This will help you understand what your program and the browser are doing as you code with YUI or another library of your choice. Using XMLHttpRequest Due to the differences between browser implementations of XMLHttpRequest, it’s nec- essary to create a special function in order to ensure that your code will work on all major browsers. To do this, you must understand the three ways of creating an XMLHttpRequest object: • IE 5: request = new ActiveXObject("Microsoft.XMLHTTP") • IE 6+: request = new ActiveXObject("Msxml2.XMLHTTP") • All others: request = new XMLHttpRequest() This is the case because Microsoft chose to implement a change with the release of Internet Explorer 6. Therefore, the code in Example 18-1 will work for all the following browsers and newer versions: • Windows Internet Explorer 5.0 • Mozilla Firefox 1.0 • Netscape 7.1 • Apple Safari 1.2 378 | Chapter 18: Using Ajax • Konqueror 3.0 • Nokia S60 • Google Chrome 1.0 • Opera 8.0 Example 18-1. A cross-browser Ajax function <script> function ajaxRequest() { try // Non IE Browser? { var request = new XMLHttpRequest() } catch(e1) { try // IE 6+? { request = new ActiveXObject("Msxml2.XMLHTTP") } catch(e2) { try // IE 5? { request = new ActiveXObject("Microsoft.XMLHTTP") } catch(e3) // There is no Ajax Support { request = false } } } return request } </script> You may remember the introduction to error handling in the previous chapter, using the try catch construct. Example 18-1 is a perfect illustration of its utility, because it uses the try keyword to execute the non-IE Ajax command, and upon success, jumps on to the final return statement, where the new object is returned. Otherwise, a catch traps the error and the subsequent command is executed. Again, upon success, the new object is returned; otherwise, the final of the three commands is tried. If that attempt fails, then the browser doesn’t support Ajax and the request object is set to false; otherwise, the object is returned. So there you have it—a cross- browser Ajax request function that you may wish to add to your library of useful Java- Script functions. OK, so now you have a means of creating an XMLHttpRequest object, but what can you do with these objects? Well, each one comes with a set of properties (variables) and methods (functions), which are detailed in Tables 18-1 and 18-2. Using XMLHttpRequest | 379 Table 18-1. An XMLHttpRequest object’s properties Properties Description onreadystatechange Specifies an event handling function to be called whenever the readyState property of an object changes. readyState An integer property that reports on the status of a request. It can have any of these values: 0 = Uninitialized, 1 = Loading, 2 = Loaded, 3 = Interactive, and 4 = Completed. responseText The data returned by the server in text format. responseXML The data returned by the server in XML format. status The HTTP status code returned by the server. statusText The HTTP status text returned by the server. Table 18-2. An XMLHttpRequest object’s methods Methods Description abort() Aborts the current request. getAllResponseHeaders() Returns all headers as a string. getResponseHeader(param) Returns the value of param as a string. open('method', 'url', 'asynch') Specifies the HTTP method to use (GET or POST), the target URL, and whether the request should be handled asynchronously (true or false). send(data) Sends data to the target server using the specified HTTP method. setRequestHeader('param', 'value') Sets a header with a parameter/value pair. These properties and methods give you control over what data you send to the server and receive back, as well as a choice of send and receive methods. For example, you can choose whether to request plain text (which could include HTML and other tags) or data in XML format. You can also decide whether you wish to use the POST or GET method to send to the server. Let’s look at the POST method first by creating a very simple pair of documents: a com- bination of HTML and JavaScript, and a PHP program to interact via Ajax with the first. Hopefully you’ll enjoy these examples, because they illustrate just what Web 2.0 and Ajax are all about. With a few lines of JavaScript, they request a web document from a third-party web server, which is then returned to the browser by your server and placed within a section of the current document. Your First Ajax Program Type in and save the code in Example 18-2 as urlpost.html, but don’t load it into your browser yet. 380 | Chapter 18: Using Ajax . fix_string($_POST['username']); if (isset($_POST['password'])) $password = fix_string($_POST['password']); if (isset($_POST['age'])) $age = fix_string($_POST['age']); if. Example 1 7-3 . The adduser.php program <?php // adduser.php // Start with the PHP code $forename = $surname = $username = $password = $age = $email = ""; if (isset($_POST['forename'])) . (isset($_POST['forename'])) $forename = fix_string($_POST['forename']); if (isset($_POST['surname'])) $surname = fix_string($_POST['surname']); if (isset($_POST['username']))

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

w