Passing an extra variable to the callback function in AJAX and saving the XMLHttpRequest.response as a variable

Attempting to read a local file on the server using the standard loadDoc(url, cfunc) function, my goal is to:

1) Search for a specific string in the file (getLine());

2) If possible, save that line to a variable.

For point 1, I provide a string to the callback. 2) The challenge arises when trying to retrieve the response due to the asynchronous nature of XMLHTTPRequest. Currently, the error encountered is: "ReferenceError: xhttp is not defined"

function main(){
    var url="data.txt"
    var str="1,0,"; //just an example
    var myCallBackWithVar = function(){
        getLine(str);
    };
    loadDoc(url, myCallBackWithVar);

    //Any way to obtain the line here?
}

function loadDoc(url, cfunc) {
    var xhttp=new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
        cfunc(xhttp);
        }
    }
    xhttp.overrideMimeType('text/plain');
    xhttp.open("GET", url, true);
    xhttp.send();
}

//Locate string with desired data in txt file
function getLine(str) {
    var data=xhttp.responseText;
    //Locate the line in the txt file
    var start=data.indexOf(str);
    var end=data.indexOf(";",start);
    var line=data.substring(start,end);    
    return line;
}

data.txt resembles the following:

some data here
0,0,9;
1,0,10;
1,1,11;

I have previously attempted to pass the XMLHTTPRequest object getLine(xhttp,str). How can I address points 1 and 2 effectively? I prefer to avoid using jQuery at this time. Thank you

Answer №1

Is there a way to extract the line from here?

I would advise against it. There is no guarantee that your application will function correctly. XHR operates asynchronously, and it is recommended to implement an asynchronous architecture.

Below is an example of how this functionality can be achieved.

    var text; // declaring a global variable
    var str = "1,0,"; // just for illustration

    function main(){
        var url = "data.txt";
        var cb = function (data){
            text = getLine(data);
            // you can utilize the text variable here
            // or anywhere else in your code
        }

        loadDoc(url, cb);
    }

    function loadDoc(url, cb) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                cb(xhr.responseText);
            }
        }
        xhr.overrideMimeType('text/plain');
        xhr.open("GET", url, true);
        xhr.send();
    }

    //Extracting the line with the desired data from the txt file
    function getLine(data) {
        if(data) {
            //Locating the line within the txt file
            var start = data.indexOf(str);
            var end = data.indexOf(";", start);
            var line = data.substring(start, end);

            return line;
        }
    }

Answer №2

Instead of passing the entire xhttp variable to the callback function, you can simplify the process. Consider the following:

function retrieveData(str) {
    var content = xhttp.responseText;

In this scenario, xhttp is no longer in scope. To resolve this issue, you could rename the parameter to xhttp.

An alternative approach would be:

callbackFunction(xhttp.responseText);

Followed by:

var data = str;

By implementing this change, you only pass the necessary information as an argument.

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

Tips for implementing validation in AngularJS

Could someone help me with AngularJS validation? I'm new to it and trying to make sure everything is correct. var app=angular.module('myApp',[]) app.controller('myController',function($scope){ $scope.clickMe = function(){ if($(& ...

Retrieve a particular HTML element from an object that has been mapped

After reproducing my issue on a smaller scale for easier handling, I am now aiming to implement an onclick function that reveals the hidden content inside each column. The plan is to initially hide the content using display: none and then switch it to disp ...

Send a request with data using Ajax and receive the response

Looking to retrieve the ID of a Mailchimp list and pass it to the controller in order to fetch all the information related to that specific Mailchimplist. However, encountering an issue where all lists are being retrieved instead of data pertaining to the ...

Creating mutual reactivity between two inputs in Vue.js

I am in the process of creating a tool that calculates the cost of purchasing specific materials. One challenge I'm facing is that users sometimes buy by mass and other times by volume. My goal is to have two active input fields (one for mass and one ...

Updating or deleting query strings using JavaScript

My URL is structured as follows: http://127.0.0.1:8000/dashboard/post?page=2&order=title I am seeking a way to eliminate the query string ?page={number} or &page={number} Due to my limited knowledge of regular expressions, I am wondering if there ...

Are JS commands enough for using Node.js dom APIs like jsdom and cheerio, or do I have to rely on jQuery for these tasks?

Is there a DOM API available for Node.js that allows me to use pure JavaScript commands? I prefer not to use jQuery as I already have existing code in vanilla JS. ...

Contrast in functionality between a pair of variables within a controller

Could you please clarify the distinction between two variables a1 and a2: app.controller("someCtrl",function(){ this.a1=somevalue; var a2=somevalue; }); Also, can you explain the lifespan of variable a2? ...

Creating multiple child processes simultaneously can be achieved by spawning five child processes in parallel

My goal is to simultaneously run five spawn commands. I am passing five hls stream urls to the loop, and these streamlink commands are meant to record the video for 5 seconds before terminating those processes. I have attempted various async methods but a ...

issues with jquery's .each() method not functioning properly

I am looking to iterate over each item in lists and then each list within lists to calculate the number of items in list if the number of items in list is 3, I want to display an alert with the value of each item JSON Data { "lists":[ { ...

Utilize the JavaScript Email Error Box on different components

On my website, I have implemented a login system using LocalStorage and would like to incorporate an error message feature for incorrect entries. Since I already have assistance for handling email errors on another page, I am interested in applying that sa ...

choosing from dropdown menu items

Learn HTML <table> <tr> <td>ENTER PRINCIPLE AMOUNT</td> <td><input type="text" name="principle" size="7"></td> </tr> <tr> <td>ENTER RATE OF INTEREST</td> <td><input type="text" na ...

Utilize AntiForgeryToken for Accessing WebAPI in Aspnet 5.0 within Xamarin Environment

I am currently facing an issue with accessing a WebAPI that utilizes ValidateAntiForgeryToken. The WebAPI Method I am working with is located within a UserController for testing purposes: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Test(Stri ...

How to Upload Your Avatar Image with the Stream-Chat API from GetStream.io

I am currently in the process of developing a Stream-Chat API project and I want to allow users to upload images directly from their devices. Upon testing, everything seems to be working fine, but the uploaded image is not displayed - only the default avat ...

In Javascript, where are declared classes stored?

When working in a browser environment like Firefox 60+, I've encountered an issue while attempting to retrieve a class from the global window object: class c{}; console.log(window.c); // undefined This is peculiar, as for any other declaration, it w ...

Retrieving geographical data in GeoJSON format using AJAX request and displaying it on a Leaflet

I'm completely new to Leaflet and I'm struggling with how to integrate markers from a MySQL database onto a Leaflet map. Can anyone guide me on how to accomplish this using PHP and AJAX? .....{"type":"FeatureCollection","features":[{"geometry":{ ...

"Implementing a full page refresh when interacting with a map using

Here is an example of how I display a map on the entire page: <div id="map_canvas"> </div> UPDATE 2: I have successfully displayed a menu on the map, but there is a problem. When I click on the button, the menu appears briefly and then disapp ...

What is the best approach to building this using Angular?

Greetings, this marks the beginning of my inquiry and I must admit that articulating it correctly might be a challenge. Nevertheless, here's my attempt: Within the following code snippet, there lies an element that effectively fills up my designated ...

StorageLimit: A new condition implemented to avoid saving repetitive values in the localStorage

Is there a way to store the text of an li element as a localStorage value only once when clicked? If it already exists in localStorage, a second click should have no effect other than triggering an alert. I'm currently using an if statement inside a ...

Implementing Datatrans Ajax in Wordpress is a seamless process that enhances

I'm in the process of integrating a credit card payment service from datatrans.ch into my WordPress site. Datatrans provides an Ajax API, which you can access here: Datatrans Ajax API Example Code I copied and pasted the example code, saved it in a ...

Using JavaScript to save coordinates as a 2D Vector Object

Which option is optimal for both memory usage and calculation speed? new Float32Array(2); new Float64Array(2); {x: 0, y: 0}; [0, 0]; It's clear that option 1 uses less memory than option 2, but what about speed? Are calculations faster with 32 bits ...