PHP plugin that takes raw text from a POST request and returns the processed text?

Hello dear friends! I am new to Grav CMS and would be happy if you support me.

How to create a PHP plugin that takes raw text from a POST request and returns the processed text?

For example, if I want to create a PHP plugin and use it as an API to convert text to uppercase.

This is how I want:

  1. There is an input field and a submit button.
  2. Enter “hello world” in the input field, click “Submit”.
  3. There is an Ajax data exchange between the client and my plugin. Ajax. As a result, “HELLO WORLD” is returned in the input field.

For me it is important that the text processing is on the server. And it is important that js can make a POST request and receive a response asynchronously.

@FedorovDeomid, Not sure what the origin of the API request is, but here is a simple sample.

  • Install fresh copy of Grav 1.7.33
  • In file /user/pages/02.typography/default.md add the following script somewhere:
    <script>
    "use strict";
    class Sender {
    
      async send() {
        let response;
    
        try {
          response = await fetch(window.location.pathname + '/myapi:mytask', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({formField: 'Hello world!'}),
          });
        }
        catch (error) {
          alert('Error');
          return;
        }
    
        if (response.ok) {
          const answer = await response.json();
          alert(answer.formField);
        }
        else {
          alert('Invalid answer');
        }
      }
    }
    
    const sender = new Sender();
    void sender.send();
    </script>
    
  • Install plugin DevTools $ bin/gpm install devtools
  • Create new plugin $ bin/plugin devtools new-plugin
  • At the last line in function onPluginsInitialized in file /user/plugins/yourplugin/yourplugin.php add the following:
    // Should use $this->grav['uri'] object and check if API request is made 
    // on correct route
    $isCorrectRoute = true;
    
    if ($isCorrectRoute) {
      // Use Uri again to get params of API request.
    
      $asyncPostData = json_decode(file_get_contents('php://input'), true);
    
      if ($asyncPostData) {
        $asyncPostData['formField'] = strtoupper($asyncPostData['formField']);
        echo json_encode($asyncPostData);
    
        die();
      }
    }
    
  • When accessing page https://yourdomain/typography you should get an alert with ‘HELLO WORLD!’.

Note:

  • This is only a rough concept to get you going.
  • I presume, you know to use JavaScript to write the response back into the form field.
  • Please check if correct route is being called. You don’t want to run the plugin on each and every request.
  • Use the params of the request to determine which function to execute.
  • See the docs about plugins
2 Likes

Thanks a lot! Thank you for making my plan a reality!

@FedorovDeomid, In that case, you may close the post, by ticking the “solution” icon in the lower right corner…