DEV Community

Supun Kavinda
Supun Kavinda

Posted on • Originally published at groups.hyvor.com

PHP and AJAX - Simplify the Code

Nowadays, any app should use AJAX because it is fast and prevents annoying page reloading. In this guide, I'll show you how I handle AJAX requests in my PHP apps.

Step 1 - Folder/File Structure

Organizing is a significant part of any application. In PHP applications, it is a good idea to create separate files for each AJAX request.

/
  /ajax
     ...ajax handler files
Enter fullscreen mode Exit fullscreen mode

If you need it to be more organized, you can group your AJAX files.

/
  /ajax
    /posts
       ...posts files
    /comments
       ...comments files
    /misc
       ...misc files
Enter fullscreen mode Exit fullscreen mode

Step 2 - PHP + AJAX

For AJAX, we can use any data structures. But, I prefer JSON.

Basically, each file will handle one task. That task can be either successful or unsuccessful. In the JSON response of AJAX requests, the most important key is status, which will have a Boolean value.

Let's create the Handler class. I normally save class files in the /src folder.

src/Ajax.php

<?php
class Ajax {

    static function setJSONHeader() {
        header('Content-type', 'application/json');
    }

    static function success($returnArray = null) {

        $array = array (
            'status' => true
        );

        if ($returnArray !== null) {
            $array = array_merge($returnArray, $array);
        }

        self::setJSONHeader();
        exit(json_encode($array));
    }


    static function error($errorMessage = '', $errorCode = 0) {

        self::setJSONHeader();
        exit(json_encode(array(
            'status' => false,
            'error' => $errorMessage,
            'errorCode' => $errorCode 
        )));

    }

}
Enter fullscreen mode Exit fullscreen mode

This class includes three static methods. Ajax::success($array) can be called when the request is successful. $array can contain more data to be sent to the client-side. Ajax::error() can be called when an error occurs.

Step 3 - All together

Let's combine all of these methods. Assume that you have an app that allows users to create posts. Here's an example AJAX request from jQuery.

function createPost(title, text) {
    $.ajax({
        method: "POST",
        url: "/ajax/create-post.php",
        data: {
            title, text // es6
        },
        dataType: "json", // gonna receive JSON
        success: (json) => {
            if (json.status === true) {
               // enjoy!
               location.href = `/${json.slug}`;
            } else {
               // oopz :(
               alert(json.error);
            }
        }
    })
}
Enter fullscreen mode Exit fullscreen mode

create-post.php - PHP AJAX Handler

<?php
include_once 'autoload.php'; // your autoloader

// make sure you also do trim() and htmlspecialchars()
$title = $_POST['title'] ?? '';
$text = $_POST['text'] ?? ''; 

if (empty($title)) 
   Ajax::error('Title cannot be empty');
if (empty($text))
   Ajax::error('Text cannot be empty');

$slug = createSlug($title); // something to be sent to the client side

// add to database (thingengineer/mysqli-database-class)
$added = $mysqli -> insert('posts', array(
   'title' => $title,
   'text' => $text,
   'slug' => $slug
));

if (!$added)
   Ajax::error('Something went wrong on creating the post');

Ajax::success(array(
   'slug' => $slug
));
Enter fullscreen mode Exit fullscreen mode

In this way, you can write AJAX handlers in PHP with a little amount of code. The trick is to use OOP to handle the statuses and data.

Good luck with your next PHP + AJAX application.

Top comments (0)