Home > other >  I have an RESTFul API that renders HTML through a GET endpoint. How can I display this html in my wo
I have an RESTFul API that renders HTML through a GET endpoint. How can I display this html in my wo

Time:02-23

I'm using a nocode API that returns some HTML based on some parameters in the URL when the user makes a GET request. I'd like to improve the user experience and have a form like a contact 7 form that can map user input for each form field in the call to API.

For example form would look like following:

Name: Todd Email: [email protected] Key: zjdHSDFHSDFHSDFS

My API is example https://api.com/endpoint/v1/

When the user enters name, email and key I need to make a call like this:

My API is example https://api.com/endpoint/v1?name={name}&email={email} with the Key field passed in as a header (X-BLOBR-KEY: {key})

I couldn't figure out how to do this with javascript or with a wordpress plugin.

CodePudding user response:

Here is some code. It is a generic HTML form and a custom submit function in vanilla JavaScript placed inside the head tag. I think it achieves what you want besides the header.

It is not possible to perform an HTTP redirect with headers, read more here. An alternative would be to perform an async request then if it returns HTML you could replace the existing HTML with the new HTML. This is a bit of hacky approach in my opinion.

As it stands, I'm not sure what value a header like this would be adding. If it's hard-coded into the HTML/JavaScript anyone could see it, manipulate it, or use it on their own form to spoof yours. To avoid this you could look into using PHP. I know W3 has resources for HTML forms with PHP.

<html>
  <head>
    <script>
      function submitFunction(e) {
        // Prevent the default form submitting actions to occur
        e.preventDefault();
        e.stopPropagation();

        // Get the form
        let form = document.querySelector("#myForm");

        // Get all field data from the form
        let data = new FormData(form);

        // Convert key-value pairs to URL parameters
        let params = new URLSearchParams(data);

        // Build the endpoint URL
        let newUrl = `https://api.com/endpoint/v1?${params}`;

        // Send to endpoint URL
        window.location.href = newUrl;
      }
    </script>
  </head>
  <body>
    <h2>HTML Form</h2>
    <form id="myForm" onsubmit="submitFunction(event)">
      <label for="fname">First name:</label><br>
      <input type="text" id="fname" name="fname" value="John">
      <br>
      <label for="lname">Last name:</label><br>
      <input type="text" id="lname" name="lname" value="Doe">
      <br><br>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

  • Related