Monthly Archives: June 2015
Using jQuery and JSON to validate and save data sent from web form to server with PHP Zend Framework 1
This is a very basic example that demonstrates how to pass, validate and save data with PHP, JSON and jQuery from a web form to the server without refreshing the browser. It covers usage of PHP Zend Framework 1.
The main idea in short:
- Visitor submits a web form that passes some key/value pairs data with a jQuery (Ajax) post method to the server Zend action;
- The incoming data will be validated on the server side Zend action and:
- In case of success:
- The data will be saved to the server (database) and.. ;
- A success message will be passed back to the Zend view HTML form.
- In case an exception occurs during the validation or during attempt to save the data: the server will send back a message with the exception without saving the passed data to the database;
- In case of success:
- Above the web form will be displayed a success/exception message from the server as a result of the above operations, assuming the visitor can submit the form again.
In this paradigm JSON is used to handle the passing data between the client side JQuery and the server side Zend action.
Files involved:
1) Zend view file containing the web form HTML code. The file was called “profile.phtml”:
/application/modules/default/views/scripts/user/profile.phtml
2) Javascript file containing the jQuery code. In this case:
/js/userprofile.js
3) Zend controller file called “UserController.php” that will validate and pass the data to the Zend model in order to save/update a database record:
/application/modules/default/controllers/UserController.php
The code
1) The Zend view file (profile.phtml) contains the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<? // Appends the JS file with the jQuery code to the Zend view: $this->headScript()->appendFile('/js/userprofile.js','text/javascript'); ?> <div class="container"> <div class="alert alert-success" style="display: none"><strong>Saved!</strong> <span id="success-text"></span></div> <div class="alert alert-error" style="display: none"><strong>Error!</strong> <span id="error-text"></span></div> <form id="user_profile_form" action="#"> <label for="first_name">First name</label> <input type="text" name="first_name" id="first_name" required /> <label for="family_name">Family name</label> <input type="text" name="family_name" id="family_name" required /> <label for="email">Email</label> <input type="email" name="email" id="email" required /> <input type="submit" value="Save changes" id="submit" /> </form> </div> |
Notice the 2 div layers above the web form:
<div class=”alert alert-success” style=”display: none”><strong>Saved!</strong> <span id=”success-text”></span></div>
<div class=”alert alert-error” style=”display: none”><strong>Error!</strong> <span id=”error-text”></span></div>
They are both intended to hold and display a success or exception alert sent back from the server as a response. By default the two layers are hidden.
2) The jQuery code in /js/userprofile.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
$(document).ready(function() { $("#user_profile_form").submit(function() { var postData = { first_name: $('#first_name').val(), family_name: $('#family_name').val(), email: $('#email').val() }; $.post("/user/saveprofilechanges/", postData, function(data) { var json = jQuery.parseJSON(data); if (json.ExceptionMessage != undefined) { $('.alert').hide(); // Hide all alert layers.. $("#error-text").html(json.ExceptionMessage); // ..then fill in the exception information from the server $('.alert-error').fadeIn(300); // .. and finally fade in the error alert div slowly $('#' + json.Field).focus(); return false; } if (json.SuccessMessage != undefined) { $('.alert').hide(); // Hide all alert layers.. $("#success-text").html(json.SuccessMessage); // ..then fill in a success message $('.alert-success').fadeIn(300); // ..and finally fade in the success alert div slowly return true; } }) return false; }); }); |
3) The Zend controller file (UserController.php) contains this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
public function saveprofilechangesAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(); if ($this->getRequest()->isPost()) { $data = $this->getRequest()->getPost(); if (!empty($data) && is_array($data)) { if (empty($data['first_name']) || !preg_match("/^[a-zA-Z ]*$/",$data['first_name'])) { echo json_encode(array( 'ExceptionMessage' => "First name missing or incorrect (only letters and spaces allowed).", 'Field' => 'first_name' // Form field to focus in client form )); return FALSE; } if (empty($data['family_name']) || !preg_match("/^[a-zA-Z ]*$/",$data['family_name'])) { echo json_encode(array( 'ExceptionMessage' => "Family name missing or incorrect (only letters and spaces allowed).", 'Field' => 'family_name' // Form field to focus in client form )); return FALSE; } if (empty($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) { echo json_encode(array( 'ExceptionMessage' => "Email missing or incorrectly formatted. Please enter it again.", 'Field' => 'email' // Form field to focus in client form )); return FALSE; } // more actions.. // more actions.. try { // The update method is in User model. The $username value may come from logged user session. $this->User->update($data, array('username=?' => $username)); echo json_encode(array( 'SuccessMessage' => "Data saved!" )); return TRUE; } catch (Exception $e) { echo json_encode(array( 'ExceptionMessage' => $e->getMessage() )); return FALSE; } } } } |
Doing some validations here, before saving the changes, allows us to work on the server. It is much easier, safer and reliable than doing this with a javascript function directly in the web browser. The good thing is that the communication between the client and the server is still behind the scenes because we use Ajax to exchange the data with the server without reloading the web page.