Passing a string from JavaScript to ASP.NET using AJAX

Having trouble passing data from JavaScript to ASP.cs using AJAX. The process doesn't seem to be working as expected. I am trying to pass a string with the results of a listbox but encountering issues. What could be causing this problem? Thank you.

    public static bool AddNewItem(string name, string surname, int age)
    {


    return true;      
   } 


   <input type="submit"  value="OK" id="enter" runat="server" onclick="submitAjax()" />



      function submitAjax() {
     var listBox = document.getElementById('SubCat');
     var i;
     var str=listBox.options[0].text;

     for(i=1;i<listBox.options.length;i++)
     str=","+listBox.options[i].text;

       $.ajax({
        type: 'POST',
        url: 'RicercaAdvForn.aspx/AddNewItem',
        data: '{str}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            if (msg.d) {
                alert("Successfully added new item");
            }
        },
        error: function () {
            alert("Error! Try again...");
        }
      } );

      }

Answer №1

It's necessary to provide each parameter separately.

details: {title: 'TheTitle', author: 'TheAuthor', year: 2022}

Answer №2

data: '{newStr}', will send the literal string "{newStr}" to your server-side code - which may not be what you intended. Consider using JSON.stringify like this:

$.ajax({
    ...
    data: JSON.stringify({ paramName: newStr }),
    ...

In this case, paramName should match the parameter expected by your server-side method.

Answer №3

Consider using the following:

data: {str},

instead of:

data: '{str}',

It is recommended to follow @Marcus Recck's advice for best practices.

Thank you.

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

What is the process for assigning custom constructor parameters to an Angular Service during its creation in an Angular Component?

I have been tasked with converting a Typescript class into an Angular 6 service: export class TestClass { customParam1; customParam2; constructor(customParam1, custom1Param2) { this.customParam1 = customParam1; this.customPara ...

Do you know the term for when JavaScript is utilized to display specific sections of a png image?

Imagine you have an image file in the format of a PNG which includes various icons intended for use on a website. How can JavaScript be utilized to choose and showcase a specific icon from that image? It's a technique I've observed in practice, b ...

Troubleshooting a 404 Error in ASP.NET using C#

Could anyone assist me with the error I'm experiencing? When I attempt to input my link as localhost:1297/Index.aspx, it opens correctly. However, if I try to access the link as http://localhost:1297/Index.aspxabc it results in a 404 error. I hav ...

The QTP Web Extensibility Toolkit is designed to enhance your testing capabilities with AJAX

Currently, I am facing a challenge while testing a web application using QTP which utilizes ajax4jsf for its ajax functionality. Unfortunately, QTP does not have the capability to detect when the ajax processes are completed. After doing some research, I ...

Unlock the power of jQuery chaining with the val() method

My selected background color is set to: var _back = "#FF0000"; Why doesn't this code change the input field's background color: $("#input").val( _back ).css("background-color",$(this).val()); But this one does? $("#input").val( _back ) ...

How to read a text file in JavaScript line by line

Coding Challenge: <script src="../scripts/jquery-3.1.0.min.js"></script> <script> $(document).ready(function(){ $('#test').click(function(){ var txtFile = '../data/mail.txt'; var file ...

Incorporating JavaScript into a Rails Application

When I click on a link "link_to" in my rails app, I am attempting to trigger a JS file. To confirm that the asset pipeline is functioning correctly, I conducted a test with: $(document).ready(function() { alert("test"); }); The alert successfully po ...

Slow rendering occurs with unthrottled range input, even with proper throttling applied

I'm currently seeking some general guidelines because I'm unsure where to turn for help at the moment. The issue I am facing involves an uncontrolled input[type=range] slider that performs very slowly when there are numerous steps (works fine wi ...

Guide to positioning a toolbar within an element when hovering over it in HTML with the help of JQuery

function attachMenuBar() { $('body').on('mouseover mouseout', '*:not(.printToolBar)', function (e) { if (this === e.target) { (e.type === 'mouseover' ? setMenuBox(e.target) : removeMenuBox(e.t ...

Find out whether a point lies inside a specific part of the surface of a sphere

As I delve into working with webGL using Three.js, I have encountered the need to determine if a click on a sphere falls within a specific section of its surface. Currently, I am able to detect when the sphere is clicked and retrieve the coordinates of th ...

Tips on containing the reach of a function in JavaScript/jQuery

I have a scenario where I have multiple .js files linked on the page, each containing functions with the same name. For example: first.js function DisplayContent(data,$target) // data is string { $target.html('<span>'+ data +'&l ...

Retrieving data from MySQL through AJAX does not yield any information

I have been following a tutorial from W3 schools on PHP and AJAX database. Majority of the content is working fine, however it seems that there is no data being retrieved from the MySQL database I created called "exercises" in the "exercisedb" database. B ...

[filepond] in order to enroll using the serverId value received from the server

Using 'filepond' within a Vue application is causing an issue. In the "process" function, the ID value obtained after transferring the file to the server (response.id) needs to be registered as 'serverId' of the file. Upon checking the ...

What is the best method for retrieving a single DataRow object from an Asp Web API?

Currently, I am in the process of developing Asp.Net WebApi code that needs to connect with some outdated C# back-end code where model classes are not utilized. Instead, pure dataTable is returned from DataAccess (I know, it sounds crazy) Below is the cod ...

Declaring a function within a conditional statement

I recently came across a code sample in the book You Don't Know JS: Scope & Closures that is puzzling to me. "Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this ...

React Component: Issue with toggle functionality in child component not meeting expectations

I'm currently working on a checkbox user interface, where I need to pass a toggle function down to a list component. The issue I'm facing is that while I can check the checkbox successfully, I'm unable to uncheck it for some reason. Below i ...

What is the best method for updating inner html with AJAX using the results obtained from json_encode?

If you need further clarification on how this works, feel free to check out this fiddle for a demonstration. In my setup, I have multiple DIVs each with a unique ID such as desk_85 (the number changes accordingly). <div class="desk_box_ver id="desk_8 ...

Query about Javascript/Node/JSON - why isn't this functioning properly?

I thought I had a good grasp on what I was doing until the process started getting jumbled. My code is being executed through Node, not a web browser. For some reason, it jumps to the prompt at the end of the while loop first and I'm not sure why tha ...

Extract the image source from this HTML retrieved using JavaScript

I need to retrieve the source URL of an image from a certain part of a document. Here is my current approach: var theImg = document.getElementById('imageDiv').innerHTML; The above code snippet returns something like this: theImg = <img src ...

Issue with updating the content of a div using Ajax in combination with jQuery tablesorter

I've been encountering difficulties with my tablesorter and ajax div content update. Whenever the ajax reloads, all the tablesorter functionalities disappear. I attempted to use livequery, but it only works for the initial listing of the table. <s ...