How to change ajax authorization header on preupload
How to change ajax authorization header on preupload

Hello,
I'm using the upload type to upload a file. When uploading I use an authorization header with a token. This works.
{
label: 'Image:',
name: 'image',
type: 'upload',
ajax: {
type: 'POST',
url: 'the url',
headers {
'Authorization':'token'
}
}
}
The token can expire after some time and there will be created a new token automatically. The token value has to change after initializing of the DataTable. I tried some things:
editor.on( 'preUpload', function ( e, fieldName, file, ajaxData ) {
editor.field(fieldName).set('ajax', {
type: 'POST',
url: 'the url',
headers: {
'Authorization': 'the new token'
}
})
})
But this doesn't work.
How can I set the new authorization header token after initializing the DataTable editor?
This question has an accepted answers - jump to answer
Answers
You need to have the headers as an object that you can mutate:
Then when you get a new token you can do:
Allan
Hello Allen,
Thanks for your quick response.
I tried this. But after the editor is initialized it doesn't show the new token but instead the old one.
This works:
This doesn't work:
It doesn't look like you are creating and using a "headers" object like Allan suggested. Create the headers object variable first:
Then use that variable as part of the
ajax
option:Kevin
I changed my code to this and it still doesn't work:
This works:
This doesn't work
Can you link to the page in question so we can see the full code please? It will also let me trace through what is happening.
Thanks,
Allan
Yes, I tried it and it looks like the Editor reads the variable during initialization and sets the
ajax
option. The variable is not read again after initialization. Use theajax()
API to set the new ajax configuration. See this example:https://live.datatables.net/guwafemu/601/edit
Open the browser's network inspector and go to the XHR tab. Edit any row and click update. Find the
Authorization
header in the Request Headers section for the initial value. Click the Update token button and do the same again to see the changed token.This is the code:
Kevin
Ah bother - I have the initialisation object being run through a deep extend, so yes my idea wouldn't work. Many thanks for spotting that Kevin, the workaround and a running example! Amazing!
Allan
This is something i could also use. Thanks for that. But what I want to do is this:
https://live.datatables.net/futurovu/1/edit
You might want to do that, but as Kevin noted, that isn't currently possible due to how Editor clones the Ajax object.
Allan
Looking at the jQuery docs a little more, you could do this:
That will impact all Ajax queries that jQuery sends (including DataTables and Editor).
Allan
Hello Allen, thank your very much!! This solved the problem.
https://live.datatables.net/futurovu/2/edit