Favorite photos and places

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:

  1. Visitor submits a web form that passes some key/value pairs data with a jQuery (Ajax) post method to the server Zend action;
  2. The incoming data will be validated on the server side Zend action and:
    1. In case of success:
      1. The data will be saved to the server (database) and.. ;
      2. A success message will be passed back to the Zend view HTML form.
    2. 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;
  3. 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:

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:

 

3) The Zend controller file (UserController.php) contains this code:

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.