Setting http header for ajax

Setting http header for ajax

shandy.sawyer@promedica.orgshandy.sawyer@promedica.org Posts: 4Questions: 1Answers: 0
edited June 4 in Free community support

Is there a way to set ajax http header info similar to setting the url?

My use case is that I don't want to call out to ajax to load data until after user input. From what I've found in the documentation:

"As of DataTables 2, this option can be given as an empty string to indicate to DataTables that it is an Ajax sourced table, but not to make an Ajax request until a URL is given, which can be done with ajax.url().load(). This can be useful if you are using DataTables to display search results obtained by Ajax, for example."

// setup blank table
const myTable = $('#myTable').DataTable({
    serverSide: false,
    ajax: "", // allow ajax to be set later
    columns: [
        ...
    ]
});

// now load after user input
$('button').on('click', function () {
    const id = $("#search").val();
    // fails because no api key in the header
    myTable.ajax.url(`${apiUrl}/Payments/${id}`).load();
});

However I need to be able to set the http header in the ajax request so I can pass an API Key to the API endpoint I am calling out to. I have seen people an ajax call separate from the DataTable api:

$('button').on('click', function () {
    const id = $("#search").val();
    $.ajax({
        url: `${apiUrl}/Payments/${id}`,
        headers: getApiHeaders(),
        success: function (data) {
            myTable.clear();
            myTable.rows.add(data).draw();
        },
        error: function () {
            alert("There was an error");
        }
    });
});

Is that the only way and proper way to do this?

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 22,019Questions: 26Answers: 5,082

    Possibly you can use jQuery ajaxSetup to define the default ajax settings. The ajax option uses jQuery ajax.

    Kevin

  • shandy.sawyer@promedica.orgshandy.sawyer@promedica.org Posts: 4Questions: 1Answers: 0
    edited June 4

    @kthorngren I tried adding:

    $.ajaxSetup({
        headers: getApiHeaders(),
    });
    

    I can confirm getApiHeaders() works because I use it in other places to initialize other DataTables normally

    But, in this case I get this error after table.ajax.url().load() is called in my code and the asp.net core api endpoint (HttpGet) is hit and returns data:

    Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    at eval (jquery.dataTables.mjs:7723:28)
    at Object.callback [as success] (jquery.dataTables.mjs:3924:3)
    at fire (jquery.js:3213:31)
    at Object.fireWith [as resolveWith] (jquery.js:3343:7)
    at done (jquery.js:9617:14)
    at XMLHttpRequest.eval (jquery.js:9878:9)

  • kthorngrenkthorngren Posts: 22,019Questions: 26Answers: 5,082
    edited June 4

    table.ajax.url().load()

    Did you define the URL string with a standalone ajax.url() call or as part of the above statement?

    I created this simple test case and it works. Use the browser's network inspector to see the defined Authorization header is in the request:
    https://live.datatables.net/socirone/62/edit

    Can you post a link to a test case showing the issue so we can help debug?
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • allanallan Posts: 64,528Questions: 1Answers: 10,666 Site admin
    Answer ✓

    You can give ajax as an object and just set the url property to an empty string. Then use ajax.url() to set the URL to what you want - e.g.:

    let table = new DataTable('#example', {
        ajax: {
            url: '',
            dataSrc: 'data',
            headers: {
                Authorization: 'my-key'
            }
        },
        columns: [
            { data: 'name' },
            { data: 'position' },
            { data: 'office' },
            { data: 'extn' },
            { data: 'start_date' },
            { data: 'salary' }
        ]
    });
     
    setTimeout(() => {
        table.ajax.url('/ajax/objects.txt').load();
    }, 1000);
    

    I created this test case: https://live.datatables.net/socirone/64/edit .

    It is worth me highlighting that you must specify ajax.dataSrc at the moment, if you take this approach. That's an error that I've just committed a fix for, but hopefully it is no big problem to add that property for the moment.

    Allan

  • shandy.sawyer@promedica.orgshandy.sawyer@promedica.org Posts: 4Questions: 1Answers: 0

    Need to clarify, I was using a template with preinstalled DataTables files. Turns out this was version 1.13.5. Moving to 2.3.1 allows a much more straight forward approach of specifying a blank ajax url and any headers (blank url failed in 1.13.5):

    // initial setup of empty table
    $('#myTable').DataTable({
        serverSide: false,
        ajax: {
            url: '',
            dataSrc: '',
            headers: getApiHeaders()
        },
        columns: [
            ...
        ]
    });
    
    $('#search').on('click', function () {
        const id = $("#search").val();
        const endPointUrl = `${apiUrl}/Payments/${id}`;
        masterTable.ajax.url(endPointUrl).load();
    });
    
  • shandy.sawyer@promedica.orgshandy.sawyer@promedica.org Posts: 4Questions: 1Answers: 0

    For some reason your responses didn't pop up until after I commented again. Thank you @allan and @kthorngren for the follow ups!

  • allanallan Posts: 64,528Questions: 1Answers: 10,666 Site admin

    Awesome - good to hear the new version helps :).

    Allan

Sign In or Register to comment.