Troubleshooting a problem with AJAX returning the data

Currently, I have a javascript function that calls another javascript function called zConvertEmplidtoRowid. This second function utilizes an ajax call to execute a query and retrieve data stored in a variable named rowid. My challenge lies in figuring out how to return this data back to the original function.

Below is a snippet of the original function where the ajax function (zConvertEmplidtoRowid) is being invoked:

var rowid = zConvertEmplidtoRowid(emplid);
//the alert should display the result obtained from the ajax query
alert(rowid);
zEmployeePortrait(emplid,ajaxlink);
}

Here's the ajax function itself. In order to properly implement the return functionality, some adjustments may be required within this section. Given my limited experience with ajax, I'm unsure about the exact steps needed:

function zConvertEmplidtoRowid(emplid, ajaxlink, callback) {

  if (typeof XMLHttpRequest == 'undefined') {
            XMLHttpRequest = function() {
                try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
                try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
                try { return new ActiveXObject("Msxml2.XMLHTTP"); }     catch(e) {}
                try { return new ActiveXObject("Microsoft.XMLHTTP"); }  catch(e) {}

            throw new Error('This browser does not support XMLHttpRequest or XMLHTTP.');
            };
        }
  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
      var rowid = request.responseText;
      callback(rowid);
    }    
  }

  var ajax_link = ajax_link + "?emplid=" + emplid;
  request.open('GET', ajax_link);
  request.send();
}

Answer №1

As highlighted by @epascarello, the ajax call operates asynchronously, but your code assumes a synchronous return.

You have two choices:

1) Adjust the ajax call to be synchronous (not recommended).

2) Include a callback function as an argument in the function triggering the ajax call and call the callback upon completion.

For example:

function convertEmpIdtoRowId(empId, url, callback) { //Added a callback parameter

  if (typeof XMLHttpRequest == 'undefined') {
            XMLHttpRequest = function() {
                try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
                try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
                try { return new ActiveXObject("Msxml2.XMLHTTP"); }     catch(e) {}
                try { return new ActiveXObject("Microsoft.XMLHTTP"); }  catch(e) {}

            throw new Error('This browser does not support XMLHttpRequest or XMLHTTP.');
            };
        }
  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
      var rowId = request.responseText;
            //invoke the callback with the rowId
            callback(rowId);
    }    
  }

  var ajaxUrl = url + "?empid=" + empId;
  request.open('GET', ajaxUrl);
  request.send();
}

convertEmpIdtoRowId(empId, url, function(rId) {
    alert(rId);
    fetchEmployeeDetails(empId, url);
});

Answer №2

Epascarello suggested in the comment that in order to receive a return value from the javascript call, it needs to be made synchronously.

Personally, I often use jQuery to help with the call, but a quick search indicates that you can achieve this by changing:

request.open('GET', ajax_link);

to:

request.open('GET', ajax_link, false);

After making this adjustment, you can access the response through:

request.responseText

You can find more information about synchronous and asynchronous requests here.

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

I am encountering an issue with running my Mocha tests. Can anyone provide assistance on how to solve this problem?

https://i.sstatic.net/kLnxs.png Could the issue be with the package.json file or am I not executing the proper command to run it? ...

jQuery Rails breathes new life into live search input box

I'm new to jQuery and recently followed a tutorial on creating a live search bar. The functionality works well, but I noticed that with every character entered, the ajax request triggers and causes me to lose focus on the text box. This forces me to r ...

Tips for Disabling ML5 Posenet

Looking to halt Posenet after completing app task private sketch(p: any) { p.setup = () => { this.poseNet = ml5.poseNet(p.createCapture(p.VIDEO), { outputStride: 8 }); this.poseNet.on(&apos ...

transferring numerous parameters in a servlet using AJAX

function retrieveXmlHttpRequest() { var xmlHttp = false; if (window.XMLHttpRequest) { return new XMLHttpRequest(); //To support the browsers IE7+, Firefox, Chrome, Opera, Safar ...

The Vue application successfully compiles but fails to load in the web browser

Upon running npm run serve on my Vue app, the console displays the following output: DONE Compiled successfully in 17450ms 2:15:55 PM App running at: - Local: ...

Validation for dates in Angular.Js input is important to ensure that only

Take a look at this form: <form name="user_submission" novalidate="novalidate" method="post"> <input type="date" name="date_of_birth" ng-focus="save_data()" ng-model-options="{timezone: 'UTC'}" ng-pattern="/^(19\d{2}|[2-9]& ...

How to reference a ListView control using its DataSource in a C# class

Currently, I have a ListView embedded in a webpage connected to a C# class datasource called CommentsDAO. This class contains the necessary methods to retrieve or delete data from the ListView. While data retrieval is successful, deleting a row proves to b ...

jquery ajax function that returns an object when successful

Below is a brief example of an AJAX call wrapped in a function. MyNS.GetStrings = function (successCallback, errorCallback) { var url = serverUrl + "/GetStrings"; $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", dataType: ...

Combining strings and variables in Vue.js with the use of bootstrap-vue syntax

Hey, I'm facing a little syntax hiccup with '="collapse-{{ product.id }}"' in both the b-button and b-collapse. Any ideas on how to properly structure this? Just looking to set up a unique ID that connects the button to the collaps ...

Tips for preventing the nesting of promises when managing errors from various APIs

Currently, I am developing an application that requires making requests to two different APIs. The authentication process is handled by Cognito, while a lambda function communicates with a database. However, the issue I am facing does not seem to be specif ...

What is the best way to extract a nested array of objects and merge them into the main array?

I've been working on a feature that involves grouping and ungrouping items. A few days ago, I posted this question: How can I group specific items within an object in the same array and delete them from the core array? where some helpful individuals ...

Utilizing Ajax to Make Calls to a Web API

I have the following snippet of code in my .NET project: // GET api/EmailValidationStaging/5 public EmailValidation GetEmailValidation(long id) With this GET method, I can make a call like so: $("#buttonFIND").click(function (e) { e.preventDefault() ...

Exploring elements within a JavaScript array

I'm struggling to retrieve model objects from my view model. It seems like a JavaScript/KnockoutJS familiarity issue, so any guidance is welcomed. Here is the code snippet: <!-- VIEW --> <select data-bind="options: allTypes, ...

Executing filepicker.io Javascript API calls may lead to unsafe errors in Javascript

I am currently using AngularJS and encountering an issue when trying to call filePicker.pickAndStore from my Upload controller. Every attempt to use a filepicker.io API function triggers an "Unsafe Javascript attempt" error: The frame requesting access ...

Comparing the $viewValue in AngularJS with the ng-model attribute or an object parameter

I am working on a dynamic form that uses ng-min/ng-max for validation. The ng-max and ng-min are connected to object parameters modelParam.maxvalue and modelParam.minvalue. I need to show an alert or error message if the value entered in the form field goe ...

Performing a Jquery ajax post to an MVC2 action

I have a script set up to send a POST request to an endpoint, and it seems like the routing is correct as it hits the breakpoint on the server. $(document).ready(function() { var o = new Object(); o.message = 'Hi from the page'; $.ajax({ ...

Codeigniter is causing issues when trying to submit a jQuery POST request while CSRF protection is

I've encountered an issue while trying to POST to a Codeigniter controller with CSRF protection enabled. The request keeps failing, resulting in HTTP/1.1 500 Internal Server Error and displaying a message saying "This action is not allowed". I attemp ...

When using $.getJSON and $.ajax, the expected JSON object is not being returned

Currently, I am taking on the "local weather" front-end development challenge on freecodecamp.com. However, I'm facing some challenges when it comes to making an API call to fetch weather data from various weather APIs. This particular task requires r ...

Trouble with Displaying 3rd Level JQuery Dropdown Menu

Currently working on implementing a 3 level dropdown feature. I have been using a third-party responsive menu in Opencart and it's been working well. You can see a demo of it here: Unfortunately, Opencart does not natively support 3 level categories, ...

Error encountered with the Schema in expressjs and mongoose frameworks

I am currently working on integrating mongoDB with an expressjs project using mongoose, and I have encountered a specific error. throw new mongoose.Error.MissingSchemaError(name); ^ MissingSchemaError: Schema hasn't been registered for model ...