Sending an Ajax post request within a loop

Using ajax post, I am sending the current "i" value in a loop to another PHP page and then retrieving the same "i" value from that page. However, before being posted, the "i" value is somehow incremented by 1. When I check the output using console.log(data);, it shows 2,..,100,1. This result is unexpected as I was expecting 1,..,100.

for (i = 1; i <= 100; i++) {
  $.ajax({
    type: 'POST',
    url: '2.php',   
    data: { 'id': i }   ,     
    success: function(data) {                                                                           
    //console.log(data);
    }
  });
}

Here is the content of 2.php:

<?php 
echo $_POST['id'];
?>

Answer №1

Utilize the ajax call within a separate function and then call that function inside the loop.

Include async:false in your ajax request as well. This will ensure that the ajax requests are sent synchronously, waiting for each previous request to finish before sending the next one.

You can structure it like this:

function func() {
    for (let i = 1; i <= 100; i++) {
        makeRequest(i);
    }
}

function makeRequest(i) {
    $.ajax({
        type: 'POST',
        url: '2.php',
        data: {
            'id': i
        },
        async:false,
        success: function(data) {
            //console.log(data);

        }
    })
}

Answer №2

Give this a try.

Learn about Closures

Understanding closure inside loops

for(i=1;i<=100; i++) {
  (function(index){
      $.ajax({
            type    :'POST',
            url     :'2.php',   
            data    :{'id':index}   ,
            success :function(data)
            {                                                                          
               //console.log(data);
            }
     });

    })(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

Utilize a foreach loop within a block of PHP code

I am working on a PHP script that retrieves responses from a form. The challenge is that there are 20 different forms to handle. When it comes to Form 1, the POST method fetches specific values and saves them into variables. $numberNa1=$_POST['number ...

Retrieving a file stored in MongoDB through GridFS using JavaScript in Node.js

Using MongoDB with JavaScript, I successfully inserted a file of any extension using GridFS. The file is stored as fs.chunks and fs.files. Now, my issue arises when trying to read the file's stream. Each time I attempt a read operation on gridStore, a ...

The onCreated listener function in the jBox Modal dialog is experiencing issues and not functioning properly after the first use

I am using jBox from the URL: . Every time I click on a link, a modal is created. The first time the modal is created, listeners for the buttons on that modal are properly added in the "onCreated" attribute and work when clicked. However, from the second ...

Unconventional array presentation

Currently, I am engaged in a Capture the Flag (CTF) competition and encountered a challenge involving JavaScript code which contains the following line: result[(j * LEN) + i] = bytes[(((j + shifter) * LEN) % bytes.length) + i] Setting aside the specific ...

Ajax fails to transmit information

Currently, I am in the process of familiarizing myself with the usage of ajax. An issue that I am encountering is that clicking a submit button in a form does not effectively send data. Below you can find the JQuery code I am using: $('input[name=" ...

The Stormpath-express login feature is incompatible with basic username and password authentication, experiencing issues

My goal is to develop a NodeJS API system tailored for an electron-based desktop application. The main feature of this app should be basic login functionality using username and password, with subsequent API calls requiring authentication via IDs and secre ...

Uploading an Array of Files Using Ajax and PHP is Not Being Received by the .php Script

I'm trying to send an array of files from a form to a .php file, but it seems that the PHP file is not receiving the files I'm uploading. Here's my HTML code: <form id="contact-form" autocomplete> <fieldset id="aboutYo ...

The content on my website is shown as &#039; instead of '

My PHP script returns a JSON object, and I have a JavaScript function that parses this JSON. I used htmlspecialchars in my PHP code, but when I display the values on my webpage &#039; is not being replaced by '. The same issue occurs with &quo ...

Invalid prop type: A form field received a `checked` prop without a corresponding `onChange` handler

In my project, I have a Parent Component called CandidateList and a Child Component called Candidate. The CandidateList component has a Select All checkbox that triggers a function to set the state when candidates are being selected, and then passes that s ...

Creating versatile styled-components with Bootstrap4 for reusability

I'm still getting the hang of using styled-components and I must admit, I really enjoy the concept. However, I've run into some challenges while trying to refactor a Component with styled components. In my case, I have a bootstrap Card that conta ...

Unable to process get requests on the Ionic application

I've been facing challenges with sending a basic get request to the Google Places API. Click here for the API link However, I keep encountering this error message: XMLHttpRequest cannot load The specified URL…ius=500&types=food&name=cruise ...

Is there a way to transfer table row data to another table by simply clicking on the corresponding checkbox in the same row?

I'm working with a table that includes 4 fields: service, amount, tax, and action. My challenge is to have the data from any row in the first table added to a second table when its checkbox is selected. The second table should have the same fields a ...

GTM - Table - Press a button to extract the text from a different element

I am not a coder, but I'm diving into the world of Google Tag Manager with the aim of tracking button clicks on search results. I have clients who want to monitor interactions with specific products displayed in their search results. While setting up ...

Node.js is throwing an error stating that it cannot read the property 'id' of a null value

I have been working on upgrading my old Discord bot from Node.js version 6.x.x to 8.x.x and organizing the commands in a separate folder for better organization. The command was functioning properly with my old bot, but it seems to be encountering issues w ...

Populate landing page with information retrieved from a REST API using Angular 6 Interceptor

To display data on the home page from a REST API using Interceptor in Angular 6, authorization with 'username' and 'password' is required. Previously, I successfully fetched data using Node.js. However, after switching to the Intercepto ...

Display a text field when the onclick event is triggered within a for

Control Panel for($i = 1; $i <= $quantity; $i++){ $data .= '<b style="margin-left:10px;">User ' . $i . '</b>'; $data .= '<div class="form-group" style="padding-top:10px;">'; $data .= ' ...

Is there a way for me to ensure that the file's name matches the object ID in the database?

let express = require("express"); let app = express(); let mongoose = require("mongoose"), bodyParser = require("body-parser"), methodOverride = require("method-override"), Book = require("./models/book"), multer = require('multer&apos ...

Retrieving all data entries that meet a specific criteria in a column using an SQL query

I have a table with the following data: +---------+--------+---------+--------------+ | ID | Data 1 |Customer | Alternative | +---------+--------+---------+--------------+ | 1 |1abc | 1 |1 | +---------+--------+---------+- ...

The object's value might be undefined, despite having null checks in place

Currently using Typescript 4.0.5 and encountering a persistent Object is possibly undefined error message My local state includes a .csv file uploaded by the user const [currentLine, setCurrentLine] = useState<File>(); The useEffect function monit ...

Using Page.ResolveClientUrl in JavaScript or jQuery allows for easy resolution of client

I find myself in a predicament where I need to choose between using an HTML page instead of a .aspx page for performance reasons. Currently, I am using an aspx page solely because of the CSS and javascript file paths like: <script type="text/javascript ...