How to easily call JavaScript modules from PHP?
Richard Dobroň
Posted on July 13, 2022
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
2. Install npm package:
$ npm install bigpipe-util
3. Add this lines to /path/to/resources/js/app.js:
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")
5. Add this lines to page footer:
What all can be Ajaxifed?
Links
<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
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.
Refresh & Redirecting
Payload
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:
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:
- 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:
Demo app with examples
- The demo application is written in Laravel, but this library is framework-agnostic.
-
⚠️ The demo server does not support HTTPS, so you may need to confirm a security exception.
Posted on July 13, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.