PLATFORM
  • Tails

    Create websites with TailwindCSS

  • Wave

    Start building the next great SAAS

  • Pines

    Alpine & Tailwind UI Library

  • Auth

    Plug'n Play Authentication for Laravel

  • Designer comingsoon

    Create website designs with AI

  • DevBlog comingsoon

    Blog platform for developers

  • Static

    Build a simple static website

  • SaaS Adventure

    21-day program to build a SAAS

How to easily call JavaScript modules from PHP?

How to easily call JavaScript modules from PHP?

You have surely solved it many times, but the solution was not very attractive. This tutorial is about generating JavaScript code in PHP using the BigPipe library, which is inspired by the Facebook architecture.

The purpose of this library is to rapidly reduce the continuously repetitive code to work with the DOM and improve the communication barrier between PHP and JavaScript.

Requirements

  • PHP 7.1 or higher
  • Node 8, 10+.
  • Webpack

Installation

  1. Install composer package:
$ composer require richarddobron/bigpipe
  1. Install npm package:
$ npm install bigpipe-util
  1. Add this lines to /path/to/resources/js/app.js:
import Primer from 'bigpipe-util/src/Primer';

Primer();

window.require = (modulePath) => {
  return modulePath.startsWith('bigpipe-util/')
    ? require('bigpipe-util/' + modulePath.substring(13) + '.js').default
    : require('./' + modulePath).default;
};
  1. Create file /path/to/resources/js/ServerJS.js
  • this step is optional, but if you skip it, use this in next step: require("bigpipe-util/ServerJS")
import ServerJSImpl from 'bigpipe-util/src/ServerJS';
export default class ServerJS extends ServerJSImpl {
}
  1. Add this lines to page footer:
<script>
    (new (require("ServerJS"))).handle(<?=json_encode(\dobron\BigPipe\BigPipe::jsmods())?>);
</script>

What all can be Ajaxifed?

<a href="#"
   ajaxify="/ajax/remove.php"
   rel="async">Remove Item</a>

Forms

<form action="/submit.php"
      method="POST"
      rel="async">
    <input name="user">
    <input type="submit" name="Done">
</form>

Dialogs

<a href="#"
   ajaxify="/ajax/modal.php"
   rel="dialog">Open Modal</a>

DOMOPS API

  • setContent: Sets the content of an element.
  • appendContent: Insert content as the last child of specified element.
  • prependContent: Insert content as the first child of specified element.
  • insertAfter: Insert content after specified element.
  • insertBefore: Insert content before specified element.
  • remove: Remove specified element and its children.
  • replace: Replace specified element with content.
  • eval: Evaluates JavaScript code represented as a string.

DIALOGS API

$response = new \dobron\BigPipe\AsyncResponse();

$response->setContent('div#content', $newContent);
$response->send();

Refresh & Redirecting

$response = new \dobron\BigPipe\AsyncResponse();

$response->reload(250); // reload page with 250ms delay
// or
$response->redirect('/onboarding', 500); // redirect with 500ms delay

$response->send();

Payload

$response = new \dobron\BigPipe\AsyncResponse();

$response->setPayload([
    'username' => $_POST['username'],
    'status' => 'unavailable',
    'message' => 'Username is unavailable.',
]);

$response->send();

BigPipe API

  • require: Call JavaScript module method. You can call a specific class method or a regular function with the custom arguments.

Example PHP code:

$asyncResponse = new \dobron\BigPipe\AsyncResponse();

// $asyncResponse->bigPipe()->require(["SecretModule", "run"], ...)
// is same as:
$asyncResponse->bigPipe()->require("require('SecretModule').run()", [
    'first argument',
    'second argument',
    ...
]);
$asyncResponse->send();

Example JavaScript code:

export default class SecretModule {
    run(first, second) {
        // ...
    }
}
  • dialog: Opens a dialog but can work with multiple dialogs at once.

Example PHP code:

$asyncResponse = new \dobron\BigPipe\DialogResponse();
$asyncResponse->setTitle('Dialog title')
   ->setBody('HTML body')
   ->setFooter('HTML footer')
   ->dialog();

$asyncResponse->send();
  • transport: Through transport markers you can send HTML content but also transform the content into JavaScript objects (such as Map, Set or Element).

Example PHP code:

$asyncResponse = new \dobron\BigPipe\AsyncResponse();
$asyncResponse->bigPipe()->require("require('Chart').setup()", [
    'element' => \dobron\BigPipe\TransportMarker::transportElement('chart-div'),
    'dataPoints' => $asyncResponse->transport()->transportSet([
        ['x' => 10, 'y' => 71],
        ['x' => 20, 'y' => 55],
        ['x' => 30, 'y' => 50],
        ['x' => 40, 'y' => 65],
    ]),
]);
$asyncResponse->send();

Demo app with examples

Comments (1)

loading comments