DEV Community

Cover image for How to easily call JavaScript modules from PHP?
Richard Dobroň
Richard Dobroň

Posted on

6 1

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


Enter fullscreen mode Exit fullscreen mode

2. Install npm package:



$ npm install bigpipe-util


Enter fullscreen mode Exit fullscreen mode

3. 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;
};
view raw app.js hosted with ❤ by GitHub

4. 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 {
}
view raw ServerJS.js hosted with ❤ by GitHub

5. Add this lines to page footer:

view raw footer.php hosted with ❤ by GitHub

What all can be Ajaxifed?

Links



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


Enter fullscreen mode Exit fullscreen mode

Forms



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


Enter fullscreen mode Exit fullscreen mode

Dialogs



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


Enter fullscreen mode Exit fullscreen mode

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

  • setController: Sets the JavaScript class controller - if you need to register an extra event listeners (show, shown, hide, hidden) or logic.

  • setTitle: Sets the title of a dialog.

  • setBody: Sets the body of a dialog.

  • setFooter: Sets the footer of a dialog.

  • setDialog: Sets the whole content of a dialog.

  • closeDialogs: Close all opened dialogs.

  • closeDialog: Close only current dialog.

  • dialog: Render defined dialog.

<?php
$response = new \dobron\BigPipe\AsyncResponse();
$response->setContent('div#content', $newContent);
$response->send();
view raw SetContent.php hosted with ❤ by GitHub

Refresh & Redirecting

<?php
$response = new \dobron\BigPipe\AsyncResponse();
$response->reload(250); // reload page with 250ms delay
// or
$response->redirect('/onboarding', 500); // redirect with 500ms delay
$response->send();
view raw Redirecting.php hosted with ❤ by GitHub

Payload

<?php
$response = new \dobron\BigPipe\AsyncResponse();
$response->setPayload([
'username' => $_POST['username'],
'status' => 'unavailable',
'message' => 'Username is unavailable.',
]);
$response->send();
view raw Payload.php hosted with ❤ by GitHub

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:

<?php
$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) {
        // ...
    }
}


Enter fullscreen mode Exit fullscreen mode
  • dialog: Opens a dialog but can work with multiple dialogs at once.

Example PHP code:

<?php
$asyncResponse = new \dobron\BigPipe\DialogResponse();
$asyncResponse->setTitle('Dialog title')
->setBody('HTML body')
->setFooter('HTML footer')
->dialog();
$asyncResponse->send();
view raw Dialog.php hosted with ❤ by GitHub
  • 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:

<?php
$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();
view raw ChartMethod.php hosted with ❤ by GitHub

Demo app with examples





Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay