Score:0

Connect React/AJAX to custom module

cn flag

I am trying to create a mini-CRUD component on the Drupal 8 site. I am fetching data from an external source, and rendering it using ReactJS.

I wish to update the database when a user clicks a button in the React component.

<button
    onClick={() =>
        $.ajax({
            type: "POST",
            url: "../path-to-file/script.php",
            data: { id: 'some data' },
        })}
>
    click me
</button>
  • I have written the React component (index.js),
  • I have connected the React component to a custom PHP script with an AJAX script (script.php).
  • I have written a custom Drupal 8 module to handle the database updates (mymodule.module).

However, I can't figure out how to connect the custom PHP script (script.php) to the module (mymodule.module) to perform the updates.

Any help would be greatly appreciated!

cn flag
It's unclear what you want to do. When do you want to execute the script? Find a drupal hook that executes at the desired timing, and use that hook in the module to execute the script.
Darcy avatar
cn flag
Thank you Patrick, I want to execute the script when a user clicks a button. I have updated my question above to include that!
Score:3
cn flag

Using AJAX to let the user arbitrarily insert data into your database via a custom PHP script seems like a really bad idea because it opens a backdoor into Drupal by circumventing Drupal's security.

To do this the "Drupal" way, you can use the JSON:API module in core to handle CRUD operations. This is way too broad a topic to describe in depth here, but Drupalize.me has a good (paid) tutorial.

This allows you to use JSON:API do CRUD on Drupal entities (nodes, media, taxonomy terms, and so on) using the same access permissions as the Drupal website.

To use this approach, you will need to configure the entities within Drupal so that they receive the data correctly when updated via JSON:API.

Instead of using a custom PHP script, I would create a new JSON:API Resource, which lets you do whatever kind of processing you want via a custom JSON:API endpoint. By doing it this way, you get all the data sanitization benefits that are built into Drupal core.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.