Ajax Issue - 415 HTTP Response

Ajax Issue - 415 HTTP Response

hpcithpcit Posts: 1Questions: 1Answers: 0

A little background, I'm on the .NET platform using the DataTables plugin on a page and have an API (Web API) that returns the response that the plugin is expecting by default (via the documentation) and in my javascript, I'm attempting to use the ajax api option for DataTables and am getting a 415 response from my API. Now, I can perform a standard fetch to test my API and I get the expected response (200 OK and the response object). Code below:

HTML

<table class="table table-bordered table-hover table-checkable" id="patients">
    <thead>
        <tr>
            <th></th>
            <th>RecordID</th>
            <th>Last Name</th>
            <th>First Name</th>
            <th>Location</th>
        </tr>
    </thead>
</table>

Javascript (doesn't work and I get a 415 Response)

$('#patients').DataTable().clear().destroy();

var args = {
        recordID: $('#recordIdFilter').val().trim() == '' ? null : $('#recordIdFilter').val().trim().replaceAll('-', '').replaceAll('(', '').replaceAll(')', ''),
        firstName: $('#firstNameFilter').val().trim() == '' ? null : $('#firstNameFilter').val().trim().replaceAll('-', '').replaceAll('(', '').replaceAll(')', ''),
        lastName: $('#lastNameFilter').val().trim() == '' ? null : $('#lastNameFilter').val().trim().replaceAll('-', '').replaceAll('(', '').replaceAll(')', ''),
        status: $('#statusSelector').selectpicker('val') == '' ? null : $('#statusSelector').selectpicker('val')
};

var dtable = $('#patients').DataTable({
        responsive: true,
        processing: true,
        ajax: {
            url: '/api/patients/search',
            type: 'POST',
            datatype: 'json',
            data: JSON.stringify(args)
        },
        lengthMenu: [30, 50, 100, -1],
        pageLength: 30,
        order: [[1, 'asc']],
        language: {
            'lengthMenu': 'Display _MENU_',
        },
        headerCallback: function (thead, data, start, end, display) {
            thead.getElementsByTagName('th')[0].innerHTML = `
                                <label class="checkbox checkbox-single">
                                    <input type="checkbox" value="" class="group-checkable"/>
                                    <span></span>
                                </label>`;
        },
        columns: [
            {
                data: 'recordID', width: 'auto', className: 'dt-left', orderable: false,
                render: function (data, type, full, meta) {
                    return `
                                    <label class="checkbox checkbox-single">
                                        <input type="checkbox" value="" class="checkable"/>
                                        <span></span>
                                    </label>`;
                },
            }
            , { data: 'recordID', title: 'ID', width: 'auto', orderable: true }
            , { data: 'lastName', title: 'Last Name', width: 'auto', orderable: true }
            , { data: 'firstName', title: 'First Name', width: 'auto', orderable: true }
            , { data: 'location', title: 'Location', width: 'auto', orderable: true }
        ],
    });

    dtable.on('change', '.group-checkable', function () {
        var set = $(this).closest('table').find('td:first-child .checkable');
        var checked = $(this).is(':checked');

        $(set).each(function () {
            if (checked) {
                $(this).prop('checked', true);
                $(this).closest('tr').addClass('active');
            }
            else {
                $(this).prop('checked', false);
                $(this).closest('tr').removeClass('active');
            }
        });

        showHideNotifyButton();
    });

    dtable.on('change', 'tbody tr .checkbox', function () {
        $(this).parents('tr').toggleClass('active');

        showHideNotifyButton();
    });

Javascript (works and I get a valid response)

fetch('/api/patients/search', {
    method: 'POST',
    body: JSON.stringify(args),
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
    }).then(response => response.json())
      .then(data => { console.output(data) });

If Anyone Cares, My API EndPoint

[HttpPost, Route("api/patients/search")]
public async Task<IActionResult> PatientSearch(PatientSearchModel args)
{
    var results = await _patientService.Search(args.RecordId, args.FirstName, args.LastName, args.Status);

    var response = new
    {
        recordsTotal = results.Count,
        recordsFiltered = results.Count,
        data = results.OrderBy(r => r.LastName).ThenBy(r => r.FirstName).ToArray()
    };

    return Ok(response);
}

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 19,936Questions: 26Answers: 4,700
    Answer ✓

    Here is some info regarding the 415 error response:
    https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415

    One option is to try setting the headers like you have in your working solution. The other is you probably need to use ajax.data as a function. See the examples in the docs.

    I would look at the server logs to see if there are more details of why the 415 response is sent.

    Kevin

Sign In or Register to comment.