ratana
Uploaded by
13 SLIDES
261 VUES
130LIKES

Developing Interactive Forms with AJAX and PHP: A Practical Guide

DESCRIPTION

This guide, created by Professor Josh Miller from Lehigh University in Spring 2012, focuses on building dynamic web forms using PHP and AJAX. It covers essential components such as setting up forms, processing submissions, and sending emails. The document includes example codes for input fields, text areas, and AJAX handling for real-time interactions. Important concepts like JSON data transfer and email form handling through PHP are explained, making this a comprehensive resource for web application development.

1 / 13

Télécharger la présentation

Developing Interactive Forms with AJAX and PHP: A Practical Guide

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Forms & AJAX Professor Josh Miller Lehigh University | Spring 2012

  2. Logins • You will need PHP to test this code, all modern web hosting companies will provide this, Lehigh does not. • I've given you an account on des170.com: • SFTP server: des170.com • Login: • Password: • Directory: web

  3. Standard Forms • DW: insert> forms> form • Insert > form > Text field, text area, checkbox, radio button, select • Button • Standard Code <form id="form1" name="form1" method="post" action="process.php"> <input name="name" type="text" /> <textarea name="contact" id="contact" cols="45" rows="5"></textarea> </form>

  4. Code from last semester… <html><head><title>mail</title></head><body> <form method='post' action='mail.php'> Email: <input name='email' type='text' /><br /> Subject: <input name='subject' type='text' /><br /> Message:<br /> <textarea name='message' rows='15' cols='40'></textarea><br /> <input type='submit' /> </form> </body></html> ---- save as mail.php in same directory, change $to line <?php $to = "YOURADDRESS@mail.com"; $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail( $to, "Subject: $subject", $message, "From: $email" ); header( 'Location: thanks.html' ); ?>

  5. Classic Form Processing Model Web Application Development

  6. AJAX • Asynchronous Javascript and XML • Except, xml isn’t cool anymore, it’s now trendy to use JSON to transfer data (JavaScript Object Notation) • “Data side” of the jQuery code we have been working with … • Pros/Cons

  7. AJAX Form Processing • Still need the HTML, PHP (slightly modified), and some javascript… • messageHandler.php: <?php $username = $_POST['username']; $phoneNumber = $_POST['phoneNumber']; $message = $_POST['message']; $email = $_POST['email']; // setup the mail headers $subject = 'New contact received through the website'; $to = 'YOUREMAIL@whatever.com'; // <-- put YOUR email address here. $from = $email; $headers = "From: $from" . "\r\n" . "Reply-to: $from" . "\r\n" . 'X-Mailer: PHP/' . phpversion(); $body = "New email received, details below\n\n"; $body .= "Full name: $username\n"; $body .= "Email address: $email\n"; $body .= "Phone number: $phoneNumber\n"; $body .= "------------------------------\n"; $body .= $message; //echo 'hello'; if (mail($to,$subject,$body,$headers)) { $returnMessage = "Thank you $username, we have received your message and reply to you as soon as possible."; $response = array('status'=>'success','message'=>$returnMessage); } else { $response = array('status'=>'error'); } header('HTTP/1.1 200 OK'); echo json_encode($response); ?>

  8. HTML part 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Contact Form</title> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <style type = "text/css"> body { font-family: verdana; font-size:12px; } #container { margin:20px 20px 0px 20px; } #statusUpdate { margin-top:20px; border:1px solid #999; padding:10px; width:300px; color:#666; display:none; } #contactForm label { color:red; display:block; } </style> </head>

  9. HTML part 2 <body> <div id = "container"> <h1>Contact Me</h1> <form id = "contactForm"> Full Name:<br /> <input type = "text" name = "fullName" id = "theName" /><br /><br /> Your Email Address:<br /> <input type = "text" name = "email" id = "theEmail" /><br /><br /> Phone Number: <br /> <input type = "text" name = "phoneNumber" id = "theNumber" /><br /><br /> Your inquiry: <br /> <textarea name = "message" id = "theMessage" rows = "6" cols = "40"></textarea><br /><br /> <input type = "button" id = "submitButton" value = "Send Now" /> </form> <div id = "statusUpdate"></div> </div> </body> </html>

  10. The Javascript <script type = "text/javascript"> jQuery(document).ready(function() { jQuery('#submitButton').click(function() { vartheName = jQuery('#theName').val(); vartheNumber = jQuery('#theNumber').val(); vartheMessage = jQuery('#theMessage').val(); vartheEmail = jQuery("#theEmail").val(); jQuery.post("messageHandler.php", { username: theName, phoneNumber: theNumber, message: theMessage, email: theEmail }, function(data) { if (data.status == 'success') { jQuery("#statusUpdate").html(data.message); jQuery("#statusUpdate").fadeIn(500); } else { jQuery("#statusUpdate").css('color','#ff0000'); jQuery("#statusUpdate").html('Sorry, there was an error sending you message.'); jQuery("#statusUpdate").fadeIn(500); } },"json" ); }); }); </script>

  11. Validdation • Almost always done client side (perhaps also server side), with javascript • jQuery simplifies this tedious task • Example: if (theName == '') { jQuery("#theName").after('<label>Please fill in your first name.</label>'); jQuery("#theName").focus(); return false; }

  12. All Validation Add before messageHandler post in the javascript – check for errors before data is sent // remove any error messages jQuery("#contactForm").find('label').remove(); // first validate the form varapos=theEmail.indexOf("@"); dotpos=theEmail.lastIndexOf("."); if (apos < 1 || dotpos-apos < 2 ) { // email address lacks an '@' symbol or a '.' jQuery("#theEmail").after('<label>Please enter a valid email address.</label>'); jQuery("#theEmail").focus(); return false; } if (theName == '') { jQuery("#theName").after('<label>Please fill in your first name.</label>'); jQuery("#theName").focus(); return false; } if (theNumber == '') { jQuery("#theNumber").after('<label>Please fill in your phone number.</label>'); jQuery("#theNumber").focus(); return false; } if (theMessage == '') { jQuery("#theMessage").after('<label>Please enter a message.</label>'); jQuery("#theMessage").focus(); return false; }

  13. Homework • Research form stylizing CSS (customizing the look, color, focus css form forms) – try to make something unusual. • Forms can be beautiful: http://www.mattdempsey.com/#contactme • Create a contact form that has additional fields than what was shown in this demo, at least 3 additional fields (try to use more than just standard text boxes) • Create a beautiful stylized form (perhaps the look of your portfolio layout), with validation, that sends a formatted email. • Nov 1,3 – work time. Due Nov 8. Must post on des170.com because you cannot use ajax between domains. Email link.

More Related