Full Stack Web Developer (Q1-Q2 2021)

Estimating read time ...
Edited 7th November 2021

OOP PHP, jQuery Validation and Ajax

In this chapter we're moving our focus onto introducing Object-Orientated Programming (OOP) in PHP, using jQuery Validator and then reusing our previously adopted Ajax skills.

For the current task at hand it is worth understanding the differences between client-side and server-side (or otherwise referred to as front-end and back-end, but not always interchangeable depending on the context), therefore the next section of this course is dedicated to describing the differences.

In summary for this part of the task I’d like you to:

  • From the ‘Contact Us’ HTML form we created earlier on in this course, enhance your ‘ContactProcess.php’ further from procedural/linear code to OOP whilst retaining SendGrid integration;
  • Implement the jQuery Validation Plugin with your HTML form. This will enable client-side validation for your contact form based on the rules you define.
  • Using Ajax POST your ‘Contact Us’ form to your ‘ContactProcess.php’ file, removing the need for users having to be redirected.

To complete the tasks and for additional knowledge, you can continue reading this chapter on how to achieve these.

1. Understanding OOP PHP

PHP initially started as a simple scripting language to enable web pages to be more dynamic, moving away from being static; i.e. a static page is a single HTML file which does not vary in content, whereas dynamic sites have changing and varying content, e.g. eBay and Amazon are examples of dynamic pages, as they provide different recommended items for each user (amongst other personalised content). (Just for clarity, eBay and Amazon are not written in PHP.)

As PHP had simple beginnings (and as you have experienced with using it), it parses HTML natively and therefore HTML and PHP code can be inserted into the same file. PHP has advanced drastically since then onto becoming its own independent programming language whilst still retaining the ability to parse HTML, maintaining a minimal learning curve to getting started.

When we write code our interpreters read from the top of the file to the bottom, executing code in the order they are placed. Solely relying on this would indicate that the code is procedural, however the same method of execution still applies to OOP but they are placed in methods/functions and not relied upon for the entire file.

In OOP (in almost any language, including Java, PHP, C++ and etc) we have classes and they hold our objects. Our class or objects are not invoked by default and we must make a call to execute them. Objects may be interchangeably referred to as methods or functions. So let’s take a look at an example OOP PHP file:

<?php namespace app\Service; use Helper; class CarService { private $brands = [ ‘Ford’, ‘Jaguar’, ‘Jeep’ ]; public function random() { return $this->brands[ $this->select() ]; } public function select() { return array_rand($this->brands, 1); } } $car = new CarService(); echo $car->random(); // Print the response. ?>
  • Firstly you’ll notice at the start and end are the usual PHP opening and closing tags (<?php and ?>).
  • Next you’ll see a namespace statement. The namespace allows us to have multiple classes, objects and variables with the same name if they’re in a different namespace. The namespace should match your directory structure. (We can ignore namespaces for now, you can even omit this.)
  • Next we have the use statement(s) which imports any additional PHP classes (or packages) we want to make use of in the current class; we can have multiple use statements. For this to work we need Composer to autoload all packages and files, so you may need to require Composer’s vendor/autoload.php file at the top.
  • Now we define our class with the name CarService. Our class should match the filename including capitalisations, so our filename should be ‘CarService.php’ (this is not absolutely mandatory at this stage, but the Laravel framework and other languages such as Java expect filenames to match with the class name; therefore it is a good practice to build and maintain).
  • We then define the $brands variable which is an array holding 3 car manufacturers. Before the variable is declared, the ‘private’ keyword is set which ensures that the variable cannot be accessed outside the class. The variable can only be accessed inside the class using $this->brands.
  • Now we define the functions/objects. These have the ‘public’ keyword which denotes that they can be accessed from anywhere and not limited to just the class (so the three visibility options are public, protected and private). For now we can just use ‘public’ as we’re getting comfortable with OOP.
  • Towards the end of the file (outside of the class) we define a variable $car which invokes the CarService class. On the next line we then call the random() function/object, which will return a random car manufacturer.

The above example is a simplistic demonstration of OOP in PHP, but you’ll find it’s similar to other programming languages. OOP allows us to follow the DRY principles (an acronym for Don’t Repeat Yourself), as we do not need to duplicate code as we can break them down into reusable objects/functions.

OOP also provides a ‘Constructor’ method, this is an object which is immediately executed as soon as the class the called. In the constructor method you can define variables, load and prepare other classes, define your own variables or even execute objects. You may find this useful when converting your current procedural PHP code to OOP for the contact form, so instead of using $_POST repeatedly you can declare that as a variable. For example:

<?php namespace app\Services; use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; class ContactProcess { protected $sendTo = ‘example@example.com’; public function __construct() { // the constructor is prepended with two underscores $this->request = $_POST; return $this->handle(); } public function handle() { // Your code here to process the form, then call the sendMessage() method. die(var_dump($this->request['subject'])); // Get the POST subject and die. return $this->sendMessage(); } Public function sendMessage() { // Your code here } } new ContactProcess(); // No need to call a method, just the class. ?>

In the above example we do not need to call a method/object as the construct method which is immediately executed upon calling the class invokes the handle() method we created via $this->handle().

You may also notice for the sendMessage() method we have opted to use camel case for it's naming, instead of send_message (snake case), SendMessage (pascal case) or send-message (kebab case). This is primarily as Laravel (a PHP framework we will move onto) uses and expects us to use camel case. Pascal case is used only for class names.

And generally that’s all there is to OOP PHP. Although PHP is able to parse HTML, we should avoid placing any HTML inside OOP methods and preferably place the PHP code at the top of the file. Ideally however the code should not contain any HTML and should be purely PHP only. For a more detailed guide on OOP PHP, please see the w3schools OOP PHP section.

Please implement the OOP standard to your existing ‘ContactProcess.php’ file we created from an earlier chapter.

2. Implementing jQuery Validation

Now moving away from OOP PHP, I’d like you to implement a client-side form validator which will ensure that visitors/users complete your HTML form correctly before being allowed to submit. We can achieve this using the jQuery Validation Plugin which is a module written in jQuery, and you’ll need to define the rules in your custom JS file.

To get started with jQuery Validation we’ll use a CDN hosting the module. In your footer.php file add the following line after the jQuery script and before any of your custom scripts:

<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.min.js"></script>

This needs to be placed after jQuery as it is dependent on jQuery and before your own scripts as we will be using the methods it provides in our own code.

This package (along with jQuery, Bootstrap and FontAwesome all of which we have utilised) can be installed using NPM, as we have also setup NPM in our project. However we’re still using CDN’s to keep things simple for now as we haven’t setup a module bundler (such as Webpack) in our project. We will use more of NPM in the later chapters, especially once we begin working with Laravel.

Once we’ve added the above code into our footer, we can make use of the validation plugin. In your custom JS file you can now define the rules for the contact form. You can see examples of using the validation plugin at SitePoint, the Validation Documentation and at this Stackoverflow answer. You should be able to find other additional resources online if you perform a search.

3. Posting with Ajax

Previously we have explored integrating with APIs using both Ajax/jQuery (to OpenWeather) and PHP (to SendGrid). As PHP is a server-side language the user is required to be redirected to another page for the processing to occur. However we can now workaround this by using Ajax to perform a HTTP POST call to our ContactProcess.php file, and our PHP file will be executed on the server and the response will be returned to our client’s browser, ready for us to manipulate using jQuery/JavaScript.

By having our PHP file (i.e. ContactProcess.php) executed using Ajax provides the benefits of Ajax and the security of a server-side programming language, as we are not exposing our API keys or other source code.

Using JS we can then show a success message, rather than having this be displayed using PHP as we have done previously. This removes the need for PHP having to redirect the user back to the form, so when the user submits the form they are not taken off the current page and all interaction occurs without the need for the page to reload. This provides a better user experience (UX) for the end-user.

For example, we currently have PHP check if the parameter success=true exists before showing them a success message. We can remove that if statement in PHP and the success message will be displayed by default on the page. Using Bootstrap you can add the class d-none to the element in your HTML, which will display: none using CSS (so the message is not displayed). Upon a successful form submission, we can use jQuery/JS to remove the d-none class. (This is one way of displaying the success message, you may have alternative ideas.)

To begin using Ajax to submit your form, you should remove the action and method attributes from your <form> element as these are no longer required. We now define this in our JS code when performing the HTTP call rather than as HTML attributes.

Next we’ll want to prepare the Ajax call. When we worked with OpenWeather we only performed a GET call, which is relatively simple. Performing a POST is similar but requires additional values. You can find the jQuery documentation on performing .post() here. For the data, you’ll want to POST the form’s input. For this you can use jQuery’s .serialize() which will take all the form inputs and encode them.

Finally it’s worth noting that the jQuery Validator plugin actually provides a submitHandler option, which allows us to add our own custom code if the validation succeeds. In such case this is when we want to fire our ajax call.

Once we’ve made our call to our ContactProcess.php file, we should return a response (if we haven’t already done so when converting the file to OOP). The data we return can be the user’s input, a json object or even a string/integer/boolean. We can do this by ensuring we echo our output in the PHP file. You may want to make use of the PHP json_encode method which will convert your variable, e.g. a string, array etc. to a JSON object which is suitable for manipulation using JS.

Author(s)

Arif Ullah

Developer & CEO