What could be causing my browser to display "uncaught referenceerror" in this situation?

Just running some browser tests to troubleshoot - everything's smooth sailing until this line is reached:

responseJson = JSON.parse(localReq.responseText);

So, when I evaluate JSON.parse(localReq.responseText), the correct value comes through. But as soon as I try to evaluate "responseJson," it throws an uncaught reference error and I can't pinpoint why.

function login()
{
   userName = document.getElementById("_name").value;
   password = document.getElementById("_password").value;
   data = "userName=" + userName + "&" + "password=" + password;
   localReq = new XMLHttpRequest();

   localReq.open("POST", "http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/check.php", true);
   localReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   localReq.send(data);
   response = document.getElementById("_login");

   if (localReq.status == 200)
   {
      responseJson = JSON.parse(localReq.responseText);
   }

}

Answer №1

To handle the response from the server asynchronously via a callback in your AJAX request, you should use an event listener. By not implementing this, you risk checking for a response code of 200 before receiving a response from the server.

function login(){
   userName = "username";
   password = "password";
   data = "userName=" + userName + "&" + "password=" + password;
   localReq = new XMLHttpRequest();

    // utilize an event handler here
    localReq.addEventListener("load", function(evt){
        if (localReq.status == 200) {
            responseJson = JSON.parse(localReq.responseText);
            alert("Success: " + localReq.responseText);
        } else {
            alert("Not Success!= :(");
            console.log(localReq);
        }
    });

    localReq.open("POST", "http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/check.php", true);
    localReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    localReq.send(data);
}

Take a look at this jsFiddle: http://jsfiddle.net/wwsj3r4q/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to transform a BLOB Buffer into a Base64 string using Swift?

I am facing an issue where I have stored a base64 string as a BLOB in Swift, but now I am struggling to figure out how to convert the buffered blob back into a UIImage. When storing it, Blob converts it into buffer, here is what I did: let image: UII ...

I am seeking a way to conceal text in an HTML document using JavaScript when the browser window width is less than a specified amount, and reveal it when the window width exceeds that value

I attempted to use the window.screen.width method, but it appears that the script only runs once (upon page load). I am seeking a way for the code to run continuously. Below is my JavaScript snippet: var textinSelected = document.getElementById("se ...

How can I access the parent elements within a recursive directive?

I'm currently implementing a recursive directive called https://github.com/dotJEM/angular-tree to iterate through a model structure like the one below: $scope.model = [ { label: 'parent1', children: [{ ...

Retrieve information from a web service and display it on a map

I'm currently working on an Android application that retrieves locations from a webservice and displays them on a map. The app needs to update the location data every 15 seconds. What would be the most effective approach to achieve this? The webservic ...

Enhance user experience with Angular Material and TypeScript by implementing an auto-complete feature that allows

Currently facing an issue with my code where creating a new chip triggers the label model to generate a name and ID. The problem arises when trying to select an option from the dropdown menu. Instead of returning the label name, it returns an Object. The ...

Is your Ajax jQuery live search not functioning properly with JSON data?

My programming code is not functioning properly. Here is the file I am working on. When it does work, it does not display the list and gives an error in the Json file. I am unsure of the reason behind this issue. You will be able to view the error in the C ...

Sort the array of objects based on the nested attribute

I am facing a challenge in ordering an array based on a nested object. The array contains information about objects on a timeline and I would like to sort it by the start position defined within nested arrays. Currently, I am able to iterate through the ar ...

Processing information on the second page following the activation of a button on the first page using the Console Browser

Is there a way to ensure that the 2nd page has completely loaded before manipulating data on it using JavaScript or jQuery? The commands are currently being executed in the browser console. Attempting to use a setTimeout function to wait for the 2nd page ...

Using the jQuery attr method to assign values to newly created DOM elements generated by an AJAX request

I have a div on a webpage that undergoes changes through AJAX requests triggered by user interaction with a dropdown menu. When the page first loads, I have a script to disable autocomplete for all text input elements: //Prevent browser autocomplete funct ...

Activate the 'li' element within the 'ul' whenever a 'ui-sref' link on the

I have been working on building a dashboard that consists of an abstract state called dashboard, with subdashboard as the immediate child state. https://i.sstatic.net/YTHky.png Previously, clicking on user details would take the user to the dashboard.tab ...

Ways to appropriately handle session timeouts when making an AJAX call

In my MVC application, I have incorporated AJAX for most of the CRUD operations. One issue I encountered is that when the session times out, it does not redirect to the session timeout page. Here is a snippet of the code that works perfectly fine without ...

The Signature Pad loses its focus

My HTML code is using JavaScript with Bootstrap and the Signature Pad. The issue I am facing is related to the Bootstrap Collapse feature. When I set the first panel as default, the Signature Pad does not allow me to sign. However, if I set the third panel ...

Issues retrieving information from MySQL through an AJAX request

I am encountering an issue while attempting to fetch data from a database. The code seems to only retrieve the initial row of data and not any subsequent rows. Although the data is correct, it remains the same regardless of the input provided in the HTML f ...

What is the sequence in which Jest executes its tests?

A fascinating challenge I've taken on involves testing a card game created in JavaScript using Jest. Currently, I have developed two tests: one to verify the creation of a 52-card deck and another to confirm that the player is dealt two cards at the ...

Retrieve the content inside the HTML body of a specific <link> element using jQuery based on its unique ID

I currently have the following code snippet in the header of my website <link rel="stylesheet" id="swp-google-font-headline-css" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro&ver=4.5.3" type="text/css" media="all"> My goal is to ...

The child component emitted a custom event, but the listener in the parent component was not activated

I've created a child component in Vue that emits a custom event, however the listener in the parent component is not being triggered. <template id="add-item-template"> <div class="input-group"> <input @keyup.enter="addItem" v-model=" ...

Redux: utilizing yield within an unrecognized function

Hey there! I am brand new to Reudx-Saga and have been experimenting with it for the past few days. I feel pretty comfortable with generators, actions, redux-stores, sagas, and other concepts. Overall, I have a good amount of experience with JavaScript. C ...

Is there a way to refresh the list automatically after deleting an item using Firebase?

When I use ngFor on a list to display multiple recordings in a table, I have two methods in my TypeScript file - one for getAll and another for delete, as shown below: HTML: <tr *ngFor="let value of imagesList"> <td scope="row& ...

The Net Core controller did not receive the ajax data as expected

My ajax call seems to be having an issue as the data is not getting passed to my controller correctly. Ajax $.ajax( { url: 'Playlist/AttachVideoToPlaylist', contentType: "application/json; charset=utf-8&q ...

Exploring Multilingual Autocomplete or: Best Practices for Managing Multiple Languages in Web Applications

I'm currently developing a website and I have a mysql-table named 'items' with the following structure: item_id | item (The second column is used to identify the item_id.) In a file called language1.php, I have an array that stores the it ...