Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Plugins

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

plugins

Solved by pamtbaau View solution

Started by Deomid 4 years ago · 3 replies · 760 views
4 years ago

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.

4 years ago Solution

@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:

    JS
    <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:

    PHP
    // 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
4 years ago

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

4 years ago

@FedorovDeomid, In that case, you may close the post, by ticking the "solution" icon in the lower right corner....

Suggested topics

Topic Participants Replies Views Activity
Plugins · by Rene, 1 week ago
2 75 1 week ago
Plugins · by Xavier, 4 weeks ago
2 81 4 weeks ago
Plugins · by Luka Prinčič, 7 years ago
3 1208 1 month ago
Plugins · by Sebastian van de Meer, 1 month ago
1 74 1 month ago
Plugins · by PIERROT Alain, 2 months ago
3 99 2 months ago