I have a code where after getting information from the database it should set the variable newcolorid to the id which it get from the database. As you can see, i defined the variable before the function, but after setting the new id, it still remains the same. Basically in the console i see the new id, but after the function is done, it reverts it back to 0. What could be the problem?
var newcolorid = 0;
$.ajax({
    url: "/colors",
    dataType: "json",
    success: function(data) {
        var newcolors = [];
        jQuery.each(data.colors, function (i, elem){
            newcolors.push([elem.color_code, elem.label, elem.id]);
        });
        for(var i=0;i<newcolors.length;i++){
            if(newcolors[i][1]==label){
                newcolorid = newcolors[i][2];
                console.log(newcolorid);
                break;
            }
        }
    }
});
for (var i = 0; i < spectrums.length; i++) {
    if (spectrums[i]) {
        var spectrumPalette = spectrums[i].option("palette");
        spectrumPalette.push([[rgb, label, newcolorid]]);
        spectrums[i].option("palette", spectrumPalette);
    }
}
 
    