Passing the response from an AJAX request to JavaScript

When I call ajax to retrieve a value from an asp page and return it to the calling javascript, the code looks like this:

function fetchNameFromSession()
{
    xmlhttp = GetXmlHttpObject();
    if (xmlhttp == null)
    {
        alert("Your browser does not support AJAX");
        return;
    }
    
    var url = "getImageName.asp";
    url = url + "?fetch_name=1";
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null); 
    xmlhttp.onreadystatechange = function() {

        if (xmlhttp.readyState == 4)
        {
           alert(xmlhttp.responseText);
           return xmlhttp.responseText;

        }

    }
}

The alert inside the function displays the correct value. However, when I try to access the value in the calling javascript function, it returns undefined. Can anyone help me figure out how to properly return the value from this ajax call to the javascript function that called it?

Answer №1

In your script, there is a line that reads:

return xmlhttp.responseText;

This line does not specify where the returned value should go. You will need to either include a callback function in the request to handle the response or handle it differently.

If(xmlHttp.readyState == 4)

Statement.

Answer №2

One reason for this issue is that the main function, getNameFromSession, does not return any value.

To address this, you can store the response from your onreadystatechange handler in a variable and then access this variable after calling getNameFromSession.

Answer №3

When using AJAX, the request is sent asynchronously, allowing the code to continue executing while waiting for a response. This means that the return statement may occur after the function has finished running. To properly handle the return value, it should be utilized within the function itself.

Answer №4

To ensure synchronization in AJAX, set the third parameter as false in xmlhttp.open("GET",url,true). This will make the script wait for the server to respond before returning control to the calling JavaScript.

function getSessionName()
{
    xmlhttp=GetXmlHttpObject();
    if (xmlhttp==null)
    {
        alert ("AJAX not supported by your browser");
        return;
    }
    var url="retrieveSessionName.asp";
    url=url+"?name_requested=1";
    xmlhttp.open("GET",url,false);
    xmlhttp.send(null); 
    xmlhttp.onreadystatechange=function(){

        if (xmlhttp.readyState==4)
        {
           alert(xmlhttp.responseText);
           return xmlhttp.responseText;

        }

    }
}

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 steps can I take to pinpoint the exact error location when running assetic:dump in Symfony2?

This error message indicates an issue with assetic:dump in Symfony2. [Assetic\Exception\FilterException] ...

Updating VAT amount using AJAX on Cart and Checkout pages in Woocommerce

I have a condition in my code that updates the VAT value to 0 if the condition is true. The code works well, but it requires reloading the page to reflect the updated VAT value. Is there a way to update the VAT value without needing to reload the page? Her ...

Obtaining information from the HttpServletResponse through an AJAX form

In my "first.jsp", there is a form containing hidden input values and pointing to another jsp file. <form id="popupForm" name="popupForm" action="<%= cqRequest.externalizeHref(handle) %>" method="post"> <input type= ...

Employ the symbol ""q" within a repetition sequence

When trying to retrieve data from a Mssql server, I encountered an issue with a function that contains a loop. The function returns some data to the callback, and now I need to figure out how to store this data from kriskowal's "q" into the resultset ...

Calculate the total sum of input values using jQuery

Here is the HTML I've been working with: I am trying to create a script where one textbox will display the total amount, and another textbox will display the following data: "name": [{ "id": 3, "qty": 2 }, { "id": 4, "qty": 5 }] Here's ...

Issues with Angular 2 loading properly on Internet Explorer 11

We are currently running an Asp.net MVC 5 web application integrated with Angular 2. The application functions smoothly on Chrome, Firefox, and Edge browsers, but encounters loading issues on IE 11, displaying the error illustrated in the image below: ht ...

A guide on executing multiple Post Requests in Node.js

Currently, I am facing some issues with my code while attempting to make multiple post requests based on certain conditions. The goal is to retrieve data from an online database (Firebase), save it locally, and then delete the online data. Here's wha ...

What are the counterparts of HasValue and .Value in TypeScript?

There is a method in my code: public cancelOperation(OperationId: string): Promise<void> { // some calls } I retrieve OperationId from another function: let operationId = GetOperationId() {} which returns a nullable OperationId, operat ...

After the recent update to version 4.2.0 of @material-ui/core, unexpected react hook errors have been

Currently, I am working on an electron application that utilizes react and material-ui. Recently, I made the decision to update material-ui to version 4.2.0. As a result of this update, two lines were added to my dependencies in the package.json. "@materi ...

Learn how to trigger a re-render in React to update a value stored in local storage

I need assistance in displaying a spinner with a percentage value during file uploads within my React application. To achieve this, I am utilizing Material UI's circular progress. My approach involves making a REST call using Axios to obtain the perce ...

Exploring the intricacies of initializing a JavaScript function

I recently inherited a large JavaScript file from a previous developer, and I'm trying to decipher some of the key sections. Here is the complete code: $(function () { var homepage = (function () { // Main functionalities are defined he ...

Retrieve an image from the database and associate it with corresponding features or news in PHP

I have retrieved a value from the database, displayed it as an image, and made it a link. So, I want that when a user clicks on the different image, they get the result from the query related to the image. I hope everyone understands. <?php // Connect ...

Setting up Datatables using AngularJS

I am working on a controller that organizes song rankings based on sales data. Upon initialization, the controller automatically sends an HTTP GET request to retrieve all the songs needed for display (currently set at the top 20 songs). If I ever need to a ...

Simplified React conditional rendering made easy

Currently, I am utilizing React 16 with Material-Ui components. In my root component, I have a requirement to load a tab and a view conditionally based on a property. Although I have managed to implement this functionality, the code appears quite messy a ...

Implementing Placeholder Text Across Multiple Lines with Material UI

Currently, for the React App I am developing, I am utilizing Material UI. In order to achieve a multi-line placeholder for a textarea using the TextField component, here is what I have so far: <TextField id="details" ful ...

Guide to creating a unique React component for displaying a single popup upon clicking with the ability to pass props to it

As someone who is still learning React, I decided to challenge myself by creating a Jeopardy game using this framework. My current idea is to have a popup appear when a player clicks on a box on the Jeopardy board, displaying the clue associated with that ...

Tips for eliminating duplicate data entries within a row while building a table using ReactJS

Apologies for the not-so-great title, but I'm having trouble figuring out how to tackle this specific issue in reactjs. I'm struggling with creating a table where one column remains empty while the other continues to populate with data. This is ...

What is the best way to extract the ID from an event in TypeScript?

HTML Code: <ion-checkbox color="dark" checked="false" id="1on" (ionChange)="onTap($event)" ></ion-checkbox> TypeScript Code: onTap(e) { console.log(e); console.log(e.checked); } I am trying to retrieve the id of the checkbox. H ...

The Ajax request is ineffective on mobile devices and fails to function as intended

I am brand new to using ajax and jquery! My code works perfectly on desktop PCs, but on mobile devices the ajax request is not functioning. Here is the code snippet: <script type="text/javascript"> var startTime = new Date(); //Start the cl ...

Ways to keep selected values in the Select box without unchecking them again?

Hello there, I am relatively new to ReactJS and currently facing an issue with Selects. Specifically, I have a Select component that displays a list of names using MenuItem. My goal is to have certain names pre-selected in the Select dropdown upon initial ...