-1

Why is this code not working?

    function sendHttprequest    (uRL)
        {
with (   new XMLHttpRequest ()){
open('get' ,uRL)

send ( void 0)

  console . log ("RESPONSETEXT:",responseText);;
    }
        }

It's supposed to make an HTTPS get request to the specified url. Plz help!

i got this code from freecodecamp

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Code
  • 1
  • 1

2 Answers2

1

You can’t access the response after making the XMLHttpRequest. You have to set an onload handler to wait for the request to finish and then get the response when it loads. The usage of with indicates outdated code and it’s not recommended.

So, your code, corrected:

function sendRequest(url) {
    let request = new XMLHttpRequest();
    request.onload = function (e) {
        console.log('response', request.responseText);
    };
    request.open("GET", url);
    request.send();
}

and if you must use with:

function sendRequest(url) {
    with (new XMLHttpRequest()) {
        onload = function (e) {
            console.log('response', responseText);
        };
        open("GET", url);
        send();
    }
}
Geass
  • 21
  • 1
chiliNUT
  • 18,989
  • 14
  • 66
  • 106
-1

In the open method you are missing the async parameter that should be supplied. Below is an example taken from w3schools. Visit https://www.w3schools.com/js/js_ajax_http.asp for more information.

    function loadDoc() {
          var xhttp;
           if (window.XMLHttpRequest) {
             // code for modern browsers
              xhttp = new XMLHttpRequest();
           } else {
              // code for IE6, IE5
              xhttp = new ActiveXObject("Microsoft.XMLHTTP");
           }
              xhttp.onreadystatechange = function() {
           if (this.readyState == 4 && this.status == 200) {
              document.getElementById("demo").innerHTML = this.responseText;
           }
         };
         xhttp.open("GET", "ajax_info.txt", true);
         xhttp.send();
     }
Mick
  • 79
  • 1
  • 6