Michele
Michele

Reputation: 15

Button enabled throughjs function goes back to disabled state

I have a form with two buttons and some texareas. As the second one should only be available after the first has been clicked I set it to disabled as default and then enable it with a js function call. That works. However when the first button is clicked some php code is executed (through if(isset($_POST['submit'])){ if ($_SERVER["REQUEST_METHOD"] == "POST")) and after that php code has been executed the button goes back to the disabled state.

Any ideas why? I seems that the whole form is reloaded once the php is done but I don't know why.

Here's the code for the buttons and js function:

<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" onclick="enableButton2()"/>
   
<input id="saveFile" class="button_text" type="submit" name="download" value="Download" disabled/>

<script>
    function enableButton2() {
        document.getElementById("saveFile").disabled = false;
    }
</script>

Upvotes: 0

Views: 37

Answers (1)

bZezzz
bZezzz

Reputation: 1002

Take a look at Fetch API to post your form with first button then is response is ok (mean your php was executed and return something), the second button is enabled else it display error.

function enableButton2() {
  var form = new FormData(document.getElementById('form'));
  fetch("YOUR-URL", { //Edit YOUR-URL to your .php script
    method: "POST",
    body: form
  }).then(function(response) {
    if (response.ok) {
      //Put your code here if form successfully submitted
      document.getElementById('saveFile').disabled = false;
    } else {
      //Put your code here if form successfully submitted but return something else than HTTP 200 Status
      console.log('Network error');
    }
  }).catch(function(error) {
    //Put your code here if form unsuccessfully submitted
    console.log(error.message);
  });
}
<form action=# id="form">
  <input id="saveForm" class="button_text" name="submit" type="button" value="Submit" onclick="enableButton2()" />
  <input id="saveFile" class="button_text" type="submit" name="download" value="Download" disabled />
</form>

Upvotes: 0

Related Questions