I used AJAX to get data that I named variable myPubscore. Now I'm trying to send myPubscore to another js file. myPubscore prints fine in Ajax, but when I print just before sendResponse, I get "Error in event handler: ReferenceError: myPubscore is not defined".
How do I get myPubscore out of AJAX and into sendResponse? I read through another SO post on this problem, but the respondents mentioned that the answer had depreciated.
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`,
data: articleUrl,
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);
});