Why does ajax transmit only the initial input value and not the rest of them?

I recently developed a school website where teachers can input students' marks. Currently, I have organized the project into three main files:

The first file is designed to showcase every student's name based on their subject and course.

<table class="check">
    <tr class="arrow">
        <th>Student</th>
        <th>Add Mark</th>
    </tr>
    @foreach(var users in user){
    <tr class="arrow">
        <td>@users.Nombre @users.Apellido</td>
        <td>
            <form method="post">
                <input type="text" id="user" style="display: none" name="user" @Validation.For("nombre") value="@users.UserId" />
                       <input type="text" id="galleryId" style="display: none" name="galleryId" @Validation.For("nombre") value="@galleryId" />
                       <input type="text" id="note" name="button2" name="note" @Validation.For("nombre") />
                       <input type="button"   value="Ready" title="Ready" onclick="loco(document.getElementById('user').value, document.getElementById('galleryId').value, document.getElementById('note').value)" />
            </form>
        </td>
    </tr>
    }
</table>

On this page, you will notice that I utilized foreach to display each student's name alongside an input textbox for the teacher to enter the mark of a specific student. The form is included within the foreach loop for this purpose.

The following file focuses on implementing ajax functionality:

function loco(user, gallery, note) {
    var xmlhttp;
    var user = document.getElementById("user").value;
    var galleryid = document.getElementById("galleryId").value;
    var note = document.getElementById("note").value;

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.open("GET", "/Marks/add1/" + gallery + "/" + user + "/" + note, true);
    xmlhttp.send();
}

Lastly, we have a page dedicated to inserting marks into the database without presenting any additional visual components.

@{
    var db2 = Database.Open("ica");
    var user = UrlData[1];
    var galleryId = UrlData[0];
    var note = UrlData[2].AsInt();
    db2.Execute("INSERT INTO Notas (Nota, UserId, Sub_Id) VALUES (@0, @1, @2)", note, user, galleryId);
}

However, I am facing an issue where the ajax function tends to send values only for the first student rather than the subsequent ones. Upon clicking the submit button for the second or third student, it consistently sends the mark of the initial student. Any insights into resolving this matter would be greatly appreciated.

Answer №1

Your current issue stems from utilizing static IDs in the HTML code within your for-each loop, resulting in multiple elements sharing the same identifiers for "user," "galleryId," and "note." Consequently, your selector is only capable of targeting the initial occurrence regardless of which one you intend to access. To overcome this limitation, consider incorporating an incremental index at the end of each ID instead of rigidly predefined values. This approach will enable clear differentiation between individual elements.

Answer №2

IMPORTANT:

I noticed that you have used the name attribute multiple times in the same input field, please remove one of them:

<input type="text" id="note" name="button2" name="note" @Validation.For("nombre") />

In this code snippet, you have set the name as button2 and also as note. Please remove button2.

To make the necessary changes:

function loco(form) {
    var xmlhttp;
    var user = form.name.value;
    var gallery = form.galleryId.value;
    var note = form.note.value;

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.open("GET", "/Marks/add1/" + gallery + "/" + user + "/" + note, true);
    xmlhttp.send();
    return false;
}

Update your HTML code as shown below:

<form onsubmit="return loco(this)">
    <input type="text" id="user" style="display: none" name="user" @Validation.For("nombre") value="@users.UserId" />
    <input type="text" id="galleryId" style="display: none" name="galleryId" @Validation.For("nombre") value="@galleryId" />
    <input type="text" id="note" name="note" @Validation.For("nombre") />
    <input type="submit" value="Ready" title="Ready" />
</form>

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

How can I make the columns in Next.js / Tailwind expand horizontally first instead of vertically?

Recently, I decided to customize the Next.js Image Gallery starter for some hands-on experience in full stack development with Next.js. My goal was to create a chronological photo gallery of a recent trip, but encountered an issue where the responsive colu ...

What is the best way to retrieve a list of fields from a set of JSON documents?

Currently, I am facing a scenario where I have two MongoDB collections named stu_creds and stu_profile. My objective is to initially fetch all the student records from the stu_creds collection where the stu_pref_contact field corresponds to email. Subseque ...

personalized XMLHttpRequest method open

var open = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, uri, async, user, pass) { this.addEventListener("readystatechange", function(event) { if(this.readyState == 4){ var self = this; var respons ...

Transmit information from an HTML input field (not a form) to a Python CGI script through AJAX

I am currently facing a challenge where I need to send data programmatically without using form fields directly to a python CGI script. The issue lies in not knowing how to extract this data in Python. Normally, with a form, I could use "form = cgi.FieldSt ...

Unable to load external JavaScript file

I'm having trouble getting this codepen code to work on my local machine: http://codepen.io/desandro/pen/mCdbD/ Whenever I attempt to load the JavaScript as an external script, it doesn't function correctly: <!DOCTYPE html> <html lang ...

How to troubleshoot Path Intellisense in VScode when using jsconfig.json for Next.js

In the structure of my project, it looks like this: jsconfig.json next.config.json components |_atoms |_Button.jsx |_Button.module.scss |_... |_... ... Within the jsconfig.json file, I have specified the following settings: { ...

The response cannot be processed by the jQuery ajax() function

I've been attempting to handle the response body of an ajax call made with jQuery, but I haven't had any luck so far. Here is the jQuery code I'm using: function doAjaxClosedStatus(url, requestId, closedStatusId) { $.ajax({ type: "POST ...

Generate a responsive list with a pop-up feature under each item (using Vue.js)

Currently, I believe that Vue may not be necessary since most tasks can be done using JavaScript and CSS. I am attempting to design a list layout as follows: [A] [B] [C] [D] When an item is clicked, the information about that specific item should ...

What are the steps to integrate DeviceOrientationControls with scrolling on iOS 13?

I am currently using DeviceOrientationEvents data to animate the rotation of a camera in three.js using DeviceOrientationControls. The controls are updated with each animation frame, and everything is functioning as expected. However, I have noticed that w ...

Update the table that includes a php script

I have a piece of PHP code embedded within a table tag that displays text from a database. I am looking for a way to automatically refresh this table every minute with updated content from the database, without refreshing the entire page. While I have co ...

Modifying the Title of a Google Calendar Event with the Google Calendar API v3 and Data Looping Functionality

I have successfully implemented retrieving events from my Google calendar using an API key. Displayed on my webpage are the events in the following format: 5/31/2016 9:00:00 AM - 5/31/2016 12:00:00 PM Event Title: Staff Meeting Description: Wee ...

Validate and send a Django form using Ajax while utilizing django-crispy-forms

My experience with django and web development is very new to me. I am seeking guidance on how to submit a Django form using Ajax while utilizing django-crispy-forms. Specifically, I need assistance with the following: validating input submitting with ...

What are the specific characteristics of Integral Types?

After researching the switch documentation and realizing it only works with integral types, I tried to find a clear definition without success. The only thing I could locate was a list of integral types. I theorized that integral types are those fully int ...

Issues with ngresource failing to properly filter data when calling an oData based Rest Controller

My web API controller is built with MongoDb as the backend. public class NodesRestController : ApiController { private INodeService _nodeService; public NodesRestController(INodeService nodeService) { _nodeService = nodeService; ...

Issue with .NET API: The class System.Text.Json.JsonElement has not been properly configured for serialization within this ObjectSerializer

I have recently started working with .NET Core API and MongoDB for my backend. Currently, I am facing an issue while trying to implement a basic CRUD operation for a specific collection. The GET method in my API is functioning correctly, but I am encounter ...

What is a way to utilize Three.js without relying on Node.js, Express, or any build tools?

Objective: Start by importing the necessary modules... Issue: When trying to import jsm files like OrbitControls.js using from 'three';, an error occurs: [Error] TypeError: Module specifier, 'three' does not start with "/", ...

Navigating through web pages with Selenium and C#

It seems there may be a logical error in my code. Initially, my goal is to: Visit the corresponding page of my website, which in this case is this link, and retrieve the data using my public void GDataPicker method. Where I need help is with the foll ...

The effectiveness of recursion in asynchronous function calls within AngularJS

My task involves creating a JSON output in tree structure from recursive async calls. The code I have developed for this purpose is detailed below: $scope.processTree = function (mData, callback) { _processTree.getWebCollection( ...

"Maximizing the efficiency of passing state in React: expert tips

I am currently working on developing a social media platform similar to Facebook. A crucial feature of this project is the feed, which displays a list of posts retrieved from the database and rendered dynamically. In Feed.js const [posts, setPosts] = useS ...

Is it possible to trigger a click event exclusively on a parent element?

One feature I'm trying to implement in my app is the ability to click on an item, such as changing the background color or text, and have a modal pop up with a color picker to customize the color of that specific item. However, I've run into an i ...