Random Guy
Random Guy

Reputation: 1

html - How to get text input value from a file?

So I have a form in HTML which submits the content of 2 inputs to an external website. What I am trying to achieve is get the value of the input from a text file. Is that possible? If so, how can I do it?

  <form action="http://blockbench.net/web/index.php" method="POST">
    <input type="text" name="model" value="I want this value to be gotten from a text file I have in the directory of my website">
    <input type="text" name="textures" value="">
    <button type="submit">Submit</button>
  </form>

Upvotes: 0

Views: 850

Answers (1)

geekonaut
geekonaut

Reputation: 5954

You have two possibilities to do this: server side (which I'd recommend) or client side.

Server side: Depending on what language you have available on your server, you can have the file content served as part of the HTML. For PHP for instance:

<form action="http://blockbench.net/web/index.php" method="POST">
  <input type="text" name="model" value="<?php echo file_get_contents('some_file_on_server.txt'); ?>">
  <input type="text" name="textures" value="">
  <button type="submit">Submit</button>
</form>

Client side: Alternatively, if the file you want to read is publicly available on the same web server, you can have the browser request it via JavaScript and fill in the data.

<form action="http://blockbench.net/web/index.php" method="POST">
  <input type="text" name="model" value="">
  <input type="text" name="textures" value="">
  <button type="submit">Submit</button>
</form>
<script>
  fetch('http://your-server/some_file.txt')
    .then(response => response.text())
    .then(text => document.querySelector('[name="model"]').value = text)
</script>

I recommend going for the server side way, because the text from the file will be immediately available as the HTML arrives in the browser while the client side solution will take some time (or may even fail) to download the text from the server and fill it into the input element.

Upvotes: 1

Related Questions