How to transfer a parameter to a JavaScript function within an Ajax success callback?

While attempting to call the UpdateItem function using AJAX with an anchor tag, I encountered a console error.

Error : req is undefined

 function updateItem(id, desc, vehicleno){
         alert("i am here");
         $('#ProcessModal').modal('show');
         $('#<%=txtPartNo.ClientID%>')[0].value=id;
        $('#<%=txtPartNo.ClientID%>')[0].value=partno;
    }    

Initiating Ajax call...

     ......
    $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "<%=BasePath%>/WebServices/RequisitionService.asmx/GetAllRequisitionItems",
             data: '{ ReqID: "<%=_RecordId%>"}',
             dataType: "json",                         
             success: function (data) {       
                 var req=[];
                 var desc=[];
                 var veh=[];

                 for (var i = 0; i < data.d.length; i++) {
                      req[i] =data.d[i].RequisitionItemsID;
                       desc[i]= data.d[i].ItemDescription;
                       veh[i]= data.d[i].VehicleNumber;
                     $("#reqTable").append("<tr><td>"+data.d[i].PartNo  + "</td><td>" + data.d[i].ItemDescription +"</td><td>"+data.d[i].Quantity+"</td><td>"+data.d[i].VehicleNumber+"</td><td> " + data.d[i].ItemStatus +"</td><td>"+ data.d[i].Remarks+"</td><td><a href='javascript:updateItem(req[i], desc[i], veh[i] );'>Process</a> </td></tr>");
                }    
            },
             error: function (result) {                         
             },
         });
    ....

Answer №1

Actually, fixing the issue with the quotation marks is quite simple. You haven't done anything wrong except for that.

To correct it, follow these steps:

var req = '';
var desc = '';
var veh = '';

Then, in your function where you use these variables:

<a href='javascript:updateItem(\"" + req + "\", \"" + desc + "\",\"" + veh + "\" );' <%= (ReqStage == (int)RequisitionStage.PendingforHOApproval) ? "" : "style=display:none"  %>>Process</a> </td></tr>");

I hope this solution helps. Keep coding and have a great day :)

Answer №2

One way to achieve this is by utilizing the JavaScript Array push() Method. Here's an example:

req.push(data.d[i].RequisitionItemsID);
desc.push(data.d[i].ItemDescription);
veh.push(data.d[i].VehicleNumber);

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

Continuously generate new objects every second

I am working on a function that involves adding the RandomBlock object to the scene and then moving it downward on the screen. function enemyPaddleMovement() { scene.add(RandomBlock); RandomBlock.translateX(-8); } The RandomBlock object is created using ...

The Angular menu items that have dropdowns attached are not showing up on the screen at all

I have been working on developing a complex Angular menu, and while I have made progress with the overall structure, I am stuck on a particular issue. The menu needs to display different options based on the user's role, such as "admin." However, desp ...

Unusual CSS hierarchy observed post AJAX content load

Currently, I am facing a puzzling issue where my CSS rules seem to be losing precedence on a page loaded via AJAX. Despite placing my custom CSS file last in the main page, allowing it to take precedence over any bootstrap styles, after loading new content ...

Navigating through nested JSON arrays in JavaScript involves looping through multiple dimensions

I am facing difficulty finding the correct solution to my issue here. I am trying to iterate through the nested Products arrays in order to display each Product name. Can this be achieved with my current code, or should I consider rewriting it to make qu ...

The cloned rows created with jQuery are failing to submit via the post method

Hello, I am currently working on a project in Django and could use some assistance with my JavaScript code. Specifically, I am trying to incorporate a button that adds new rows of inputs. The button does function properly as it clones the previous row usin ...

Ensuring the Safety of Usernames with JavaScript, PHP, and MySQL

I have come across several articles discussing the implementation of a feature on a registration page that automatically checks if a username is already in use in the database. However, I am concerned about the security implications of this approach. I fea ...

When making an HTTP GET request followed by another GET request in Express, it results in an error with undefined parameters on the

When I open a form that has a link to a list and try to access the list, I encounter an "id" undefined error for the form we came from, which was already functional. The issue arises when I have a GET page where I present a form to modify a record at /loc ...

React - warning - Avoid using <Link> outside of a <Router> context

Warning: Invariant failed: It is not recommended to use <Link> outside of a <Router> Encountering this while attempting to write a test for a component where test("renders post list div ", () => { const posts = [ { created: ...

Elements vanish when SHAKE effect is in use

I've been experimenting with this framework and I'm struggling to get the shaking effect to work properly. Whenever I hover over an element, other divs seem to disappear. I tried using different versions of JQuery and JQuery UI on JSFiddle, and i ...

Challenges experienced during the process of uploading a website to the server

I seem to have encountered an issue where the Navigation background image is missing after uploading my website onto the server. Surprisingly, everything else seems to be working perfectly. What could possibly be the cause of this discrepancy? navbar-de ...

What is the best way to handle parsing JSON with special characters in JavaScript?

Content stored in my database: "Recommended cutting conditions" When using Json_encode in PHP, the result is: {"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]}; In JavaScript : var str ...

The issue arises when using IE8/9 with $.get and .html() functions, as the retrieved data

Below is a snippet of JavaScript code that I am currently working with: $(".refresh").on("click touch", function () { $.get($("a.suggest-date").attr('href') + '#suggestedDate', null, function (result) { console.log(result); ...

Comparing boolean values in React JS

I am working with a React JavaScript code in which I am iterating through a series of boolean values. The issue I am facing is that when 'data.nextrow' is false, I expect nextrow1 to also be false but it ends up being set to true instead. co ...

AWS Lambda with Node.js: Storing data during streaming - cuts short before completion leading to missing data

There's a Lambda function in my application that gets triggered whenever a new JSON file is written to an S3 bucket. The function is responsible for reading the contents of the JSON file, extracting individual records, and then storing them in a datab ...

Tips on implementing multiple consecutive setState calls in ReactJS

Recently, I discovered that setState is an async call. I'm facing an issue where I need to utilize the updated result from setState immediately after setting it, but due to its async nature, I end up getting the old state value. While researching for ...

Building an npm module locally: A step-by-step guide

Imagine I'm in the process of working on an application called MyApp and I want to create an NPM module for it, named MyModule. Currently, I can think of two approaches to developing it: Make changes -> save -> npm install /path/to/module in M ...

Ways to retrieve multiple pages using the .load function

Currently, I am constructing a manage account page using net core. The main issue I'm facing is loading content from various pages into a designated div when the user clicks on different items in the menu. How can I efficiently utilize this method wit ...

Nested Promises in Angular's $q Library

I'm facing an issue with a function that should return a list of favorite locations. Here's the code snippet in question: When I call LocationsFactory.getFavoriteLocations(), it returns a promise like this: getFavoriteLocations: function() { ...

Unable to create account using PHP

Every time I attempt to create an account, the data I receive is always problematic. The username must be between 3 and 15 characters I find it frustrating that the account creation never goes through successfully. What baffles me even more is that af ...

Exploring the capabilities of automation testing with charts.js and the latest version of Angular

While working on my testing automation for charts.js, I utilized the ngContext object to retrieve data with this code snippet: document.getElementsByTagName('chart-dataset')[0].__ngContext__. However, since upgrading to angular 14, it seems that ...