0

Hello everyone I'm trying to post the data inside a JavaScript variable using AJAX, can anyone help me with the syntax?

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

How can I do this?

Samuel Goldenbaum
  • 18,391
  • 17
  • 66
  • 104
IceeFrog
  • 327
  • 3
  • 16
  • 1
    `data: JSON.stringify(total_registros)` – Iskandar Reza Nov 15 '19 at 21:37
  • Edited question with your answer, thanks for the quick answer, do you know how can I retrieve this information in the controller? Btw will type : 'syntax' in the AJAX will be JSON? and contentType: 'application/SYNTAX', would be json instead of SYNTAX? – IceeFrog Nov 15 '19 at 21:39
  • @IskandarRezaRazali the data is not an object – Samuel Goldenbaum Nov 15 '19 at 21:40
  • @Chev using stringify would make it an object if I'm not wrong? http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/ – IceeFrog Nov 15 '19 at 21:41
  • 2
    @Chev JSON.stringify() doesn't care if it's an object, an array or even a boolean. It just turns it into a string that can be passed as a url query string for the controller to accept. – Iskandar Reza Nov 15 '19 at 21:42
  • Yes, "SYNTAX" should be "json" in those two places. – Heretic Monkey Nov 15 '19 at 21:47
  • @HereticMonkey Thanks sir, edited the question with your answer, I appreciate a lot everyone's help <3 – IceeFrog Nov 15 '19 at 21:47
  • Had a look at the `total_registros` and seems its an array of objects like `[{ "A": "val1", "B": "val2", "C": "val3", "D": "1500", "E": "val5" }, { "A": "val1", "B": "val2", "C": "val3", "D": "500", "E": "val5" }]`. If that data is correct, then change the contentType to `application/json` and possibly JSON.stringify the data - may actually not need to JSON.stringify – Samuel Goldenbaum Nov 15 '19 at 21:56
  • @IceeFrog it doesn't help to fix the issues in your question. This makes it difficult for other users to follow what the issue was, the chat history and the final answer. I have rolled back the edit to make it more clear for other users. – Samuel Goldenbaum Nov 16 '19 at 00:00
  • @Chev never thought about it that way, thought it was gonna speed up answers, but indeed, I should keep original question, thanks for the feedback I won't forget this :) – IceeFrog Nov 16 '19 at 00:01
  • No prob bud, been away but will post a full answer for you including the MVC side – Samuel Goldenbaum Nov 16 '19 at 00:02
  • @Chev Thanks a lot sir, I appreciate your time, I'll be around crawling the web :) – IceeFrog Nov 16 '19 at 00:04
  • @Dementic hey thanks for your answer, I'll take a look at it ASAP – IceeFrog Nov 16 '19 at 00:15

1 Answers1

1

There are a few issues to point out. Your sample data generated is an array of objects like the following:

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

This is a great format for JSON to be posted to the MVC API routes.

MVC API:

Create a public class that represents the data 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; }
}

Create routes to accept your post. I have shown two examples here - one to add a single object and one for an array of 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 of type MyModel specified will use binding to convert the JSON into an instance of MyModel for you.

Finally, update the JavaScript:

Change the options to post JSON by updating the content type to application/json then and stringify'ing 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 a 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);
    }
});
Samuel Goldenbaum
  • 18,391
  • 17
  • 66
  • 104