PHP and AJAX - Simplify the Code
Tags: php, javascript, ajax
Published: 2019-11-03 06:22:01

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
```

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

```
/
  /ajax
    /posts
       ...posts files
    /comments
       ...comments files
    /misc
       ...misc files
```

# Step 2 - PHP + AJAX

For AJAX, we can use any data structures. But, I prefer [JSON](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/Boolean) value.

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

**src/Ajax.php**

```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 
		)));

	}

}
```

This class includes three [static methods](https://developer.hyvor.com/tutorials/php/oop-static-methods-properties). `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.

```js
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);
            }
        }
    })
}
```

**create-post.php** - PHP AJAX Handler

```php
<?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
));
```

In this way, you can write AJAX handlers in PHP with a little amount of code. The trick is to use [OOP](https://developer.hyvor.com/tutorials/php/oop-intro) to handle the statuses and data.

Good luck with your next PHP + AJAX application.