I have a JSON response similar to this from ConvertAPI :
{
"ConversionCost":10,
"Files":[
{
"FileName":"somefile_XXX.pdf",
"FileExt":"pdf",
"FileSize":63911,
"FileId":"718cc1XXXXXXXXX5",
"Url":"https://v2.convertapi.com/d/XXXXXXXXXXXXXXXXXXXXXXX/somefile_XXX.pdf"
}
]
}
Where I am trying to extract the ConversionCost by result.ConversionCost[0]
(the result.files[0].Url
works fine) in the following script:
let convertApi = ConvertApi.auth({secret: '<API_SECRET>'})
let elResult = document.getElementById('result')
let elResultLink = document.getElementById('resultLink')
let elUrl = document.getElementById('urlInput')
elResult.style.display = 'none'
// On file input change, start conversion
document.getElementById('convertBtn').addEventListener('click', async e => {
elResult.style.display = 'none'
document.documentElement.style.cursor = 'wait'
try {
// Converting web page to PDF file
let params = convertApi.createParams()
params.add('url', elUrl.value)
params.add('FileName', 'The_FileName.pdf');
params.add('LoadLazyContent', 'true');
params.add('Zoom', '1.5');
params.add('PageSize', 'a4');
params.add('MarginTop', '0');
params.add('MarginRight', '0');
params.add('MarginBottom', '0');
params.add('MarginLeft', '0');
let result = await convertApi.convert('web', 'pdf', params)
fetch('some_page.asp?id=315&initials=DDD&pdf_url=' + result.files[0].Url + '&ConversionCost= ' + result.ConversionCost[0]).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function() {
console.log("Booo");
});
// Showing link with the result file
elResultLink.setAttribute('href', result.files[0].Url)
elResultLink.innerText = result.files[0].Url
elResult.style.display = 'block'
} finally {
document.documentElement.style.cursor = 'default'
}
})
But this gives me the error in the console Uncaught (in promise) TypeError: Cannot read property '0' of undefined at HTMLButtonElement.<anonymous>
Am I reading it wrong or what am I missing? .. here is the GitHub vor ConvertAPI JS : https://github.com/ConvertAPI/convertapi-js
Try this (code not tested):
fetch('includes/save_user_welcomeletter_to_server.asp?id=315&initials=DDD&pdf_url=' + result.files[0].Url + '&pdf_ConversionCost= ' + result.ConversionCost)
.then(r => r.json())
.then(o => {
// Showing link with the result file
elResultLink.setAttribute('href', o.files[0].Url)
elResultLink.innerText = o.files[0].Url
elResult.style.display = 'block'
console.log(o.ConversionCost);
})