Back

Communicate from JavaScript to PHP

Call PHP actions

Just create a new tab in the implementation-view and name it like "my_action_name.php".

'my_action_name.php'-tab

$json_response = json_encode($db->getAll('countries')); echo($json_response);

The webservice delivers a list with all countries.

'javascript'-tab

class CountrySelect extends Tag { init() { resource.action('my_action_name').then( countries=> { this.setAttribute('countries', countries ) }) } }

'html'-tab

<h1>Countries</h1> <select for="country of this.countries"> <option value="{country.code}">{country.name}</option> </select>
This is the resulting select, which gets the countries from the database.
Here are more examples how to call webservices:

'javascript'-tab

class TestTag extends Tag { init() { // Call the "login.php" tab with the username and password parameters: resource.action('login', { username: 'MyUser', password: 'pw123'} ).then( userinfo => { this.setAttribute('userinfo', userinfo ) }) } buyProduct() { // Call the "php"-tab (Main tab for webservices) resource.call({buy_product:15}).then( result=> { alert('Thank you for buying this product!') }) } }

'php'-tab

// The JavaScript "buyProduct()"-function calls the default "PHP"-tab with the "resource.call" function. $db->insert('orders', array( 'product' => $data['buy_product'], 'user_id' => $user_id));

PHP receives the parameters in the $data tag, as an array

$buy_product_id = $data['buy_product'];

'html'-tab

<div> <button (click)="this.buyProduct()">Buy</button> </div>

Call 'php'-tab with parameters in this resource.

resource.call( PARAMETERS ).then( result => { console.log( result ) })

Call the 'my_action_name.php'-tab in this resource.

resource.action( 'my_action_name', PARAMETERS ).then( result => { console.log( result ) })

Call the 'my_action_name.php'-tab in another resource.

JJResource.action('my.resource', 'my_action_name', PARAMETERS ).then( result => { console.log( result ) })

Call the 'php'-tab in another resource.

JJResource.call('my.resource', PARAMETERS ).then( result => { console.log( result ) })

Call other PHP-services from PHP

PHP receives the parameters in the $data tag, as an array

callAction($resourceName, $actionName, $data)