Tips for sending information to a JavaScript variable through AJAX requests

Hello there, I'm currently working on a project that involves posting data stored in a JavaScript variable using AJAX. Can anyone assist me with the correct syntax for this process?

<div class="container-fluid">
    <div class="card shadow mb-4">
        <div class="card-header py-3">



    <table class="table table-bordered" width="100%" cellspacing="0" id="myTableData">
        <thead>
            <tr>
                <th>A</th>
                <th>B</th>
                <th>C</th>
                <th>D</th>
                <th>E</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>val1</td>
                <td>val2</td>
                <td>val3</td>
                <td>500</td>
                <td>val5</td>
            </tr>
            <tr>
                <td>val1</td>
                <td>val2</td>
                <td>val3</td>
                <td>1500</td>
                <td>val5</td>
            </tr>
        </tbody>
    </table>
<script>
    init();
    function init(){

        addRowHandlers('myTableData');

    }

    function addRowHandlers(tableId) {
        if(document.getElementById(tableId)!=null){
            var table = document.getElementById(tableId);
            var rows = table.getElementsByTagName('tr');
            var A = "";
            var B = "";
            var C = "";
            var D = "";
            function Registro(A, B, C, D, E) {
                            this.A = A;
                            this.B = B; 
                            this.C = C; 
                            this.D = D;
                            this.E = E;
                        };
            var total_registros = [];

            // Use let instead of var to avoid a closure arount the looping variable
            for ( let i = 1; i < rows.length; i++) {

                rows[i].i = i;
                rows[i].onclick = function() {
                    A = table.rows[this.i].cells[0].innerHTML;                
                    B = table.rows[this.i].cells[1].innerHTML;
                    C = table.rows[this.i].cells[2].innerHTML;
                    D = table.rows[this.i].cells[3].innerHTML;
                    E = table.rows[this.i].cells[4].innerHTML;
                    var newRegistro = new Registro(A, B, C, D, E);
                    total_registros.push(newRegistro);
                    console.log("-Log- New data", total_registros);
                    // Now remove the handler because the job is done
                    rows[i].onclick = null;
                };
            }
        }
    }
</script>

Currently, this grabs data and saves it inside total_registros[], how am I able to post this using AJAX?

<script>

    function seleccionar() {
        $.ajax({
            url: 'myURL',
            type: 'post',
            dataType: 'SYNTAX',
            contentType: 'application/SYNTAX',
            data: JSON.stringify(total_registros),
            success: function (response) {
                $('#').html(response);
            },
            error: function (error) {
                console.log(error);
            }
        });
    }
</script>

On success I just expect it to return a html response inside a the #div I declare

This data will be retrieved inside a [HttpPost] Controller in MVC

[HttpPost]
public ActionResult View()
{
    return View();
}

What would be the best way to accomplish this task?

Answer №1

There are a couple of things to address. The data you have provided is in the form of an array of objects, as shown below:

[
   { A: "val1", B: "val2", C: "val3", D: 1500, E: "val5" }, 
   { A: "val1", B: "val2", C: "val3", D: 1500, E: "val5" }
]

This format is ideal for sending JSON to the MVC API endpoints.

MVC API:

Create a public class that matches the structure of the data mentioned above:

public class MyModel {
    public string A { get; set; }

    public string B { get; set; }

    public string C { get; set; }

    public int D { get; set; }

    public string E { get; set; }
}

Set up routes to handle your data. Here are two examples - one for adding a single object and another for multiple objects:

    [HttpPost]
    public JsonResult AddModel ([FromBody] MyModel model) {
        // process the model
        ... 

        return Json (model);
    }

    [HttpPost]
    public JsonResult AddModels ([FromBody] IList<MyModel> models) {
        // process the list of models
        ...

        return Json (models);
    }

The parameter type MyModel specified will automatically convert the incoming JSON into an instance of MyModel using binding.

Lastly, update the JavaScript:

To send JSON data, change the content type to application/json and stringify the data:

// posting a single model
let data = JSON.stringify({ A: "val1", B: "val2", C: "val3", D: 1500, E: "val5" });
$.ajax({
    url: '/AddModel',
    type: 'post',
    contentType: 'application/json',
    data: data,
    success: function (response) {
        console.info(response);
    },
    error: function (error) {
        console.error(error);
    }
});

// posting multiple models
data = JSON.stringify([{ A: "val1", B: "val2", C: "val3", D: 1500, E: "val5" }, { A: "val1", B: "val2", C: "val3", D: 1500, E: "val5" }]);
$.ajax({
    url: '/AddModels',
    type: 'post',
    contentType: 'application/json',
    data: data,
    success: function (response) {
        console.info(response);
    },
    error: function (error) {
        console.error(error);
    }
});

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 we convert milliseconds to the corresponding date and time zone in Java?

1)I am trying to determine the user's timezone and current time using the following code snippets: Calendar currentdate1 = Calendar.getInstance(); TimeZone tz = Calendar.getInstance().getTimeZone(); System.out.println("time zone"+tz); System.out.pri ...

Button click not triggering Ajax functionality

I've been working on implementing a simple Ajax function in a JSP using JQueryUI. The goal is to pass two text fields from a form and use them to populate two separate divs. However, when I click the button, nothing seems to be happening. I even tried ...

Why is the time input field in AngularJS programmed to expect a date instead?

When booking, I stored the time using $filter('date')($scope.booktime, 'mediumTime'). After booking, I have an editbooking function where I pass the time and encounter an error in the console: Error: [ngModel:datefmt] Expected 11:59:00 ...

Sending an AJAX associative array to a PHP associative array

I'm currently attempting to transmit form values to PHP utilizing the $.ajax method. Here is the HTML form structure I am working with: <form> <p> <label for="login">User ID:</label> <input type="text" name="login" id ...

Changing the element tag and flipping escape characters in html entities

My control over the string source is limited, as I can only use html(). However, I am in need of cleaning up the chaos within the source, The goal is to remove all instances of <div class="page"></div>, while retaining its content. The challen ...

When render returns another component, React does not invoke componentWillMount

Here is my code setup: const Dashboard = React.createClass({ getInitialState(){ return { user: JSON.parse(localStorage.getItem('user')) }; }, componentWillMount(){ var self = this; $.get({ url: 'http://127 ...

What is the best way to create a delay in user hover activation before triggering a slideDown

In my current code snippet, I have implemented the functionality to perform a slideDown action when a user hovers over an element. However, I would like this slide down effect to only occur if the user has hovered for at least 2 seconds. If the user does n ...

Choosing an option beforehand using angular-ui-select2 version 0.0.5

I'm struggling with setting a default option in a select2 dropdown using Angular and an ng-model. Here's my implementation: Angular controller code snippet $scope.filter = { searchValue: '', departmentId: 'Department2' } ...

Uncover the reason behind the application's crash with Titanium

If we encounter non-crashing errors, utilizing LogCatcher can help by pinpointing which Javascript code is causing the issue. However, in the event of a crash, there's no time for logging Javascript errors. In such cases, integrating tools like ARCA ...

Any ideas on how to address the null function in this.ParentForm?

((food)this.ParentForm).retrieveFoodList(); This code snippet invokes the retrieveFoodList method found in the food.cs file. However, the this.ParentForm object is currently null. ...

Exploring ways to showcase informational alerts when a link is hovered over by the mouse

I am currently working on a website that showcases links utilized by my team. One specific requirement is that when a user hovers over a link, note information should be displayed. Although the simplest solution would be to not list the link if it's n ...

What are the advantages of using history.push or another method from react-router-dom compared to simply assigning the path to window.location.pathname?

When I need to navigate within my code, I find it more convenient to simply assign the desired path to window.location.pathname. Can this approach have any drawbacks? ...

"In Vim, learning how to create block comments is an essential skill to

I am seeking a way to streamline the process of generating block comments for documentation in vim. For example: /** * comment */ Are there any available plugins that can assist with this task? ...

Encountering a problem when utilizing webview in react native due to an error with the evaluation of

While utilizing webview for trading charts, I am encountering an issue where a warning is displayed and the URL fails to load. Below is the code snippet used for loading. It seems like the video URI works fine in full screen mode, but other URIs are not ...

I want to hide jqvmap when viewing on mobile devices

I'm currently working on my website at . I have a template that I'm using as a guide, but I want to make the map disappear on mobile view and replace it with a dropdown list. Can anyone suggest what code I should use for this? Appreciate any hel ...

Mastering the use of gl Scissor is essential for effectively implementing popups in your

I am attempting to implement a pop-up view on top of the current webGL view. My strategy is as follows: Whenever I need to display a popup, I create a scissorRect and begin rendering the popup scene onto it. I was hoping that the content of the previous s ...

Refining a selection from a list using a multi-choice array

I have a filtering component that filters a list of people based on multiple input values. The string-based inputs filter properly, but when I select more than one item in the multi-select, nothing is displayed. This is likely due to person.role not contai ...

.NET application experiencing high CPU usage due to Websphere MQ

I am currently working on a .NET application that relies on WebSphere MQ for reliable publish/subscribe middleware functionality. I've encountered an issue when sending a queue of consecutive messages from the server to the client. The server utilizes ...

Is it possible to capture a submit event from a form within an iframe using jQuery or JavaScript

If I have a webpage with an embedded iframe containing a form, how can I update a hidden field value on the main page once the form is submitted? What is the best way to trigger an event in the parent page upon form submission? Here's a simplified ex ...

Is it possible to line up Ajax request in Javascript?

I am seeking a way to schedule an Ajax request to occur every second. The code I currently have in place functions flawlessly. window.onload = function () { setTimeout(doStuff, 1000); // Wait before continuing } function doStuff() { ...