0
votes

How do you insert the correct "xhr" value into the HTML5 button?

I am not sure how this whole XMLHttpRequest works. I believe it takes: xml data, text, numbers or null from the HTML5 button input and prints it out in text input in this case but can it store a value in it to call on it later. That is the question!

<script type="text/javascript">
  function readBody(xhr) {
    var data;
    if (!xhr.responseType || xhr.responseType === "text"){
        data = xhr.responseText;
    } else if (xhr.responseType === "document") {
        data = xhr.responseXML;
    } else {
        data = xhr.response;
    }
    window.document.myform.xhr1.value = data; 
    return data;
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200); {
        window.document.myform.readBodyxhr.value = readBody(xhr);
    }
    else {
        alert(xhr.status);
    }
    xhr.open('GET', 'http://www.google.com', true);
    xhr.send(null);
  }
</script>

...HTML5
<input type="button" name="XMLHttpRequest" value="XMLHttpRequest" onclick="readBody(xhr)" />
<input type="text" name="xhr1" value="" size="4"/></td>
<input type="text" name="readBodyxhr" value="" size="4"/></td>      
1
<input type="text"> expects .value to be a string, not a document, ArrayBuffer or Blob. What is expected response?guest271314
I just want to be able to add xhr as a string, number or whatever. "function readBody(xhr) { " .How do you add "xhr" in HTML5 code?losopha

1 Answers

0
votes

Move call to .open() and .send() outside of onreadystatechange handler.

Substituted onload and onerror for onreadystatechange. ; following if condition is a syntax error. Note also, XMLHttpRequest with true passed at third parameter at .open() sets load handler to return results asynchronously.

<script type="text/javascript">
  var url = "https://gist.githubusercontent.com/guest271314/6a76aa9d2921350c9d53/raw/1864137bfd2eb62705bd0e71175048a28b3253e6/abc.txt";

  function readBody() {

    var xhr = new XMLHttpRequest();
    
    xhr.onload = function() {
      window.document.myform
      .readBodyxhr.value = xhr.responseText;
    }

    xhr.onerror = function() {
      alert(xhr.status);
    }

    xhr.open("GET", url, true);
    xhr.send(null);
  }
</script>

...HTML5
<form name="myform">
  <input type="button" name="XMLHttpRequest" value="XMLHttpRequest" onclick="readBody()" />
  <input type="text" name="xhr1" value="" size="4" />
  <input type="text" name="readBodyxhr" value="" size="4" />
</form>