I have the following REST api that is called inside another callback function.
If I comment out the alert at the end of the function, it does not return the correct variable. How can I fix it?I tried replacing the alert with a pause function but it was not successful.
function getResponseAttachments(itemID) {
var htmlresponsedoc = '<br/>';
var listname = 'Response';
var siteWebUrl = _spPageContextInfo.webAbsoluteUrl;
// Rest URL
// alert('get response attachment is called.');
var requestUri = siteWebUrl + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Title,ID,Attachments,AttachmentFiles&$expand=AttachmentFiles";
$.ajax({
url: requestUri,
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
$.each(data.d.results, function (i, item){
var title = item.Title;
var respnseID = item.ID;
if (respnseID == itemID)
{
var attachmentUrl0 = item.AttachmentFiles.results[0];
var attachmentUrl1 = item.AttachmentFiles.results[1];
var attachmentUrl2 = item.AttachmentFiles.results[2];
var attachmentUrl3 = item.AttachmentFiles.results[3];
var attachmentUrl4 = item.AttachmentFiles.results[4];
if (attachmentUrl0)
{
htmlresponsedoc += '<strong>Documents for Review: </strong><br/>';
htmlresponsedoc += '<a href="' + attachmentUrl0.ServerRelativeUrl + '">' + attachmentUrl0.FileName + '</a>';
htmlresponsedoc += '<br/><br/>';
}
if (attachmentUrl1)
{
htmlresponsedoc += '<a href="' + attachmentUrl1.ServerRelativeUrl + '">' + attachmentUrl1.FileName + '</a>';
htmlresponsedoc += '<br/><br/>';
}
if (attachmentUrl2)
{
htmlresponsedoc += '<a href="' + attachmentUrl2.ServerRelativeUrl + '">' + attachmentUrl2.FileName + '</a>';
htmlresponsedoc += '<br/><br/>';
}
if (attachmentUrl3)
{
htmlresponsedoc += '<a href="' + attachmentUrl3.ServerRelativeUrl + '">' + attachmentUrl3.FileName + '</a>';
htmlresponsedoc += '<br/><br/>';
}
if (attachmentUrl4)
{
htmlresponsedoc += '<a href="' + attachmentUrl4.ServerRelativeUrl + '">' + attachmentUrl4.FileName + '</a>';
htmlresponsedoc += '<br/><br/>';
}
}
})
},
error: function () {
alert("Error getting the Test Item attachment.");
}
});
console.log(htmlresponsedoc);
alert('This alert is needed for the successful execution of the function');
return htmlresponsedoc
}
faye fouladi