After using AJAX to retrieve data as myPubscore, I encountered an issue when trying to pass myPubscore to another js file. While myPubscore printed correctly in Ajax, I faced a "ReferenceError" when attempting to print it just before sendResponse.
How can I successfully transfer myPubscore from AJAX to sendResponse? I came across a similar thread on SO discussing this problem, but the suggested solution was deprecated.
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type == "articleUrl") {
console.log("background heard articleUrl")
console.log(request);
var articleUrl = request;
$.ajax({
type: 'POST',
url: `${url}/buttoncolor`,
data: articleUrl,
success: function urlFunction(data) {
var myPubscore = data;
console.log("myPubscore in ajax:")
console.log(myPubscore);
}
})
console.log("myPubscore in sendresponce:")
console.log(myPubscore);
sendResponse({score: "myPubscore"});
}
updated background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type == "articleUrl") {
console.log("background heard articleUrl")
console.log(request);
var articleUrl = request;
$.ajax({
type: 'POST',
url: `${url}/buttoncolor`,
success(data){
console.log("incoming data");
console.log(data);
sendResponse(data);
console.log("sent data");
},
});
return true;
}
content.js
chrome.runtime.sendMessage({ "type": "articleUrl", "url": url }, function (response) {
console.log("here's the response for sending the URL");
console.log(response);
});