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?