Skip to content
Advertisement

how to disable button if ajax gives error message

I would like to know how I could disable and enable a button according to the message that ajax returns.

<script>
    function showHint(str) {
        if (str.length == 0) {
            document.getElementById("ajax").innerHTML = "";
            return;
        } else {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("ajax").innerHTML = this.responseText;
                }
            };
            // xmlhttp.open("POST", 'Ajax.php?endpoint=' + str, true);
            xmlhttp.open("POST", 'Ajax.php?endpoint=' + str, true);
            xmlhttp.send();
        }
    }
</script>

<span id="ajax"></span>

This is the button that should be disabled in case ajax says that the endpoint is not valid and in case it is correct it should be enabled.

<div class="field">
    <div class="control">
      <input class="button is-danger is-fullwidth has-text-weight-bold" 
      type="submit"value="Suscribirse">
    </div>
</div>

PHP CODE

<?php

$a[] = "https://127.0.0.1";
$a[] = "https://127.0.0.2";


$q = $_REQUEST["endpoint"];

$hint = "";

if ($q !== "") {
  $q = strtolower($q);
  $len=strlen($q);
  foreach($a as $name) {
    if (stristr($q, substr($name, 0, $len))) {
      if ($hint === "") {
        $hint = $name;
      } else {
        $hint .= ", $name";
      }
    }
  }
}

echo $hint === "" ? "<p class='help is-danger'>El endpoint no es valido</p>" : "<p class='help is-success'>El endpoint es valido</p>";

?>

Advertisement

Answer

If you modify the PHP to return a more useful response (JSON) you can use the contents of that in a meaningful way in the ajax callback.

<?php

    $a[] = "https://127.0.0.1";
    $a[] = "https://127.0.0.2";


    $q = $_REQUEST["endpoint"];

    $hint = "";

    if($q !== "") {
    
      $q=strtolower($q);
      $len=strlen($q);
      
      foreach($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
          if ($hint === "") {
            $hint = $name;
          } else {
            $hint .= ", $name";
          }
        }
      }
    }
    
    // create the response based upon the state of the $hint variable ( &/or other conditions too perhaps )
    $results=array(
        'status'    =>  empty( $hint ) ? false : true,
        'message'   =>  empty( $hint ) ? "<p class='help is-danger'>El endpoint no es valido</p>" : "<p class='help is-success'>El endpoint es valido</p>"
    );

    exit( json_encode( $results ) );

?>

And then tweak the ajax callback to use the response object to enable/disable the button:

function showHint(str) {
    let bttn=document.querySelector('.control > input[type="button"]');
    
    if (str.length == 0) {
        document.getElementById("ajax").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                let json=JSON.parse(this.response);
                bttn.disabled=json.status;

                document.getElementById("ajax").innerHTML=json.message;
            }
        };
        xmlhttp.open("POST", 'Ajax.php?endpoint=' + str, true);
        xmlhttp.send();
    }
}
Advertisement