0 Comments

I was testing some JavaScript ajax code found at: http://youmightnotneedjquery.com/ and I was getting the error:

 

Uncaught ReferenceError: request is not defined from ReferenceError: request is not defined
   at Object.rli.app.self.makeXmlHttpRequest (
http://localhost:50258/Client/Features/Posts/request_is_not_defined.html:27:25)
   at Object.rli.app.self.onExecuteClick (http://localhost:50258/Client/Features/Posts/request_is_not_defined.html:55:22)
   at HTMLButtonElement.onclick(http://localhost:50258/Client/Features/Posts/request_is_not_defined.html:12:145) request_is_not_defined.html:63
Uncaught ReferenceError: request is not defined

 

image

 

Cause

This was caused by the line:

request = new XMLHttpRequest();

When you use ‘use strict’, variables need to be defined before use.

Solution

So adding var before request fixed the problem:

<!DOCTYPE html> <html> <head> <title>Vanilla JavaScript.</title> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" /> </head> <body> <div class="spa-page"> <button onclick="rli.app.onExecuteClick()">Execute</button> </div> <script type="text/javascript"> // Use a namespace to prevent pollution of the global namespace. var rli = rli || {}; // Define application root object. rli.app = (function () { 'use strict'; var self = {}; self.makeXmlHttpRequest = function () {

// When "var" is removed from this line, an error is thrown:
// Uncaught ReferenceError: request is not defined.
var request = new XMLHttpRequest();

request.open('GET', 'http://www.google.com', true); request.onload = function () { if (this.status >= 200 && this.status < 400) { // Success! var data = JSON.parse(this.response); console.log(data); } else { // We reached our target server, but it returned an error. console.log("Error status not between 200 and 400."); } }; request.onerror = function (e) { // There was a connection error of some sort. console.log(e); }; request.send(); }; self.onExecuteClick = function () { self.makeXmlHttpRequest(); }; self.start = function () { // Define global exception handler. window.onerror = function (message, file, line, col, error) { console.log(message, "from", error.stack); }; }; return self; })(); // Start the application. rli.app.start(); </script> </body> </html>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

DEV TIPS

0 Comments

Just a dump blog post for short development tips.  …