Click here to Skip to main content
16,016,301 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I am trying to fill an HTML table through a datatable which brings information from a database. Within the ajax parameters to bring the information from the database there is a piece of information that allows me to only extract the records of that parameter, but when I execute it by clicking a search button I get an error where it says that the parameter is null , but the parameter is the selected value in a combo that I fill when loading the page. This is the code that was initially made by the table and later by the script.

What I have tried:

HTML
<div class="card">
    <div class="card-body">
        <h5 for="txtLista" class="form-label">Integrantes</h5>
        <table id="tabla" class="display cell-border" style="width: 100%">
            <thead>
                <tr>
                    <th>Nombre</th>
                    <th>Fecha nacimiento</th>
                    <th>Edad</th>
                    <th>Sexo</th>
                    <th>Tipo documento</th>
                    <th>Numero documento</th>
                    <th>Editar/Eliminar</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
</div>

JQuery
@section scripts{
    <script>
	var tabladata;
	var filaseleccionada;

	$(document).ready(function () {
    	   $("<option>").attr({ "value": "0", "disabled": "disabled", "selected": "true" }).text("Seleccionar").appendTo("#cbbunidad");
    	   jQuery.ajax({

        	url: "@Url.Action("ListarUnidad", "Mantenedor")",
        	type: "GET",
        	datatype: "json",
        	contentType: "application/json; charset=utf-8",
        	success: function (data) {

            		if (data.data != null) {
                		$.each(data.data, function (index, item) {
                    			$("<option>").attr({"value":item.uniId}).text(item.uniNombre).appendTo("#cbbunidad");
                		})
            		}
        	},
        	error: function (error) {
            		console.log(error)
        	}
    	    });
	})

	$("#btnBuscar").on("click", function () {

            tabladata = $("#tabla").DataTable({
                destroy: true,
                responsive: true,
                ordering: false,
                "ajax": {
                    url: "@Url.Action("ListarIntegrantesUnidad", "Mantenedor")",
                    type: "POST",
                    datatype: "json",
                    contentType: "application/json; charset=utf-8",
		    data: JSON.stringify({ idunidad: $("#cbbunidad option:selected").val() })
                },
                "columns": [
                    { "data": "intNombre" },
                    { "data": "intFechaNacimiento" },
                    { "data": "intEdad" },
                    { "data": "intSexo" },
                    { "data": "intTipoDocumento" },
                    { "data": "intNumeroDocumento" },
                    {
                        "defaultContent": '<button type="button" class="btn btn-primary btn-sm btn-editar"></button>' +
                            '<button type="button" class="btn btn-danger btn-sm btn-retirar ms-2">^__i class="fas fa-trash"></button>',
                        "orderable": false,
                        "searchable": false,
                        "width": "90px"
                    }
                ],
                "language": {
                    "url": "https://cdn.datatables.net/plug-ins/2.0.2/i18n/es-ES.json",
                }
            })
	})
    </script>
}


And the error message that is given is:

DataTables warning:table id=tabla - Ajax error. For more information about this error, please see http://datatables.net/tn/7

I am relatively new to web programming and appreciate any help you can give me.
Posted
Updated 2-May-24 15:02pm
v3

1 solution

The error you are seeing is down to the server responding with something other than a 2xx status. This could be the server responding with a 404 error (NotFound), a 401 (unauthorized), or some other status. We don't have access to the server and we don't have access to the code so we can't correct the code for you.

Next time you run this, open up the console window in your browser and select the network tab. Rerun the code that runs this and watch the items in the network tab. The status of each call will be returned so watch and see what comes back for that call. The status will tell you what is happening.
 
Share this answer
 
Comments
Member 12760369 28-Apr-24 8:44am    
The console message I get in the debugger is

jquery-3.4.1.js:9837


POST https://localhost:44310/Mantenedor/ListarIntegrantesUnidad 500 (Internal Server Error)

and the response is




<title>El diccionario de parámetros contiene una entrada NULL para el parámetro 'idunidad' del tipo que no acepta valores NULL 'System.Int32' del método 'System.Web.Mvc.JsonResult ListarIntegrantesUnidad(Int32)' en 'CapaPresentacion.Controllers.MantenedorController'. Un parámetro opcional debe ser un tipo de referencia, un tipo que acepte valores NULL o debe declararse como parámetro opcional.<br>Nombre del parámetro: parameters




Detalles de la excepción: System.ArgumentException: El diccionario de parámetros contiene una entrada NULL para el parámetro 'idunidad' del tipo que no acepta valores NULL 'System.Int32' del método 'System.Web.Mvc.JsonResult ListarIntegrantesUnidad(Int32)' en 'CapaPresentacion.Controllers.MantenedorController'. Un parámetro opcional debe ser un tipo de referencia, un tipo que acepte valores NULL o debe declararse como parámetro opcional.Nombre del parámetro: parameters

Error de código fuente:




Se ha generado una excepción no controlada durante la ejecución de la solicitud Web actual. La información sobre el origen y la ubicación de la excepción pueden identificarse utilizando la excepción del seguimiento de la pila siguiente.



Seguimiento de la pila:


<pre>

[ArgumentException: El diccionario de parámetros contiene una entrada NULL para el parámetro 'idunidad' del tipo que no acepta valores NULL 'System.Int32' del método 'System.Web.Mvc.JsonResult ListarIntegrantesUnidad(Int32)' en 'CapaPresentacion.Controllers.MantenedorController'. Un parámetro opc
Dave Kreskowiak 28-Apr-24 13:38pm    
The 500 error means either you're sending data to the controller in the wrong format, in the wrong place in the request so that it couldn't be parsed on the server side, or your server side code crashed for some reason.

Looking at the bottom of what you posted, it seems you should be sending a value for "idunidad", but either that value doesn't exist, or isn't being handled correctly in your controller method: "ListarIntegrantesUnidad", "Mantenedor".
Pete O'Hanlon 29-Apr-24 2:39am    
The error tells you, right at the top, what is wrong. It is expecting a parameter called unitid (idunidad) to be supplied, and this is missing. The server side has an expectation that a none-null value will be passed in here. If you correct this, you might get the results you are expecting. I say might because you may have missed out other parameters.
Member 12760369 29-Apr-24 15:36pm    
In the debugger, before starting the definition of the table, it shows me the correct value of the combo, but once it enters the table is when the error occurs. I modified passing the parameter from POST to GET but it remains the same.
The method I use in the Maintainer controller is:

[HttpGet]
public JsonResult ListarIntegrantesUnidad(int idunidad)
{
List<entidadintegrantesunidad> oLista = new List<entidadintegrantesunidad>();
oLista = new CN_IntegrantesUnidad().ListarenUnidad(idunidad);
return Json(new { data = oLista }, JsonRequestBehavior.AllowGet);
}
Pete O'Hanlon 30-Apr-24 1:40am    
Again, use the network tab to check what you are passing over. The error is telling you that you didn't supply idunidad, so check to see what you actually did pass across.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900