chrome.storage.sync.remove array doesn't work - javascript

I am making a small Chrome extension. I would like to use chrome.storage but I can't get it to delete multiple items (array) from storage. Single item removal works.
function clearNotes(symbol)
{
var toRemove = "{";
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
toRemove += "'" + index + "',";
});
if (toRemove.charAt(toRemove.length - 1) == ",") {
toRemove = toRemove.slice(0,- 1);
}
toRemove = "}";
alert(toRemove);
});
chrome.storage.sync.remove(toRemove, function(Items) {
alert("removed");
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value) {
alert(index);
});
});
});
};
Nothing seems to break but the last loop that alerts out what is in the storage still shows all the values I am trying to delete.

When you pass in a string to sync.remove, Chrome will attempt to remove the one single item whose key matches the input string. If you need to remove multiple items, use an array of key values.
Also, you should move your remove call to inside your get callback.
function clearNotes(symbol)
{
// CHANGE: array, not a string
var toRemove = [];
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value)
{
// CHANGE: add key to array
toRemove.push(index);
});
alert(toRemove);
// CHANGE: now inside callback
chrome.storage.sync.remove(toRemove, function(Items) {
alert("removed");
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value)
{
alert(index);
});
});
});
});
};

Slightly Slimmer and updated solution
chrome.storage.sync.get(null, (data) => {
const keys = Object.keys(data).filter((x) => x.startsWith('<start-of-key>')); // Can replace `startsWith` with regex or any other string comparison
chrome.storage.sync.remove(keys);
});

Related

how to remove the chrome.storage.local

Im not getting how remove chrome.storage.local values in javascript?
i use like this but the storage value is not removing from the store:chrome.storage.local.remove(result.MyFile.Base64File);
Please check the below code, here I'm using chrome.storage.local.set to set
var obj = { DocName: "name", Base64File: "Base64string" };
chrome.storage.local.set({ 'MyFile': obj });
and chrome.storage.local.get to retrive the values
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
}
Note: You can not remove values, you can remove indexes with specific names what causes that they gets removed WITH there values.
Tbh I could not run the code but I'm pretty sure something like this should work. But I really recommend you to avoid chrome.storage because it's some kind of "dumb" :)
So please have a look at this code:
function clearItem(symbol) {
var remove = [];
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
if (index == "symbol") remove.push(index);
});
chrome.storage.sync.remove(remove, function(Items) {
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
console.log("removed: " + index);
});
});
});
});
};

Converting Checkbox formfields to name value pairs for form submission

I have a bunch of checkboxes that I have to submit to a serverside script that I can't change. The server is expecting values in the format scriptname?town=townA&town=townB etc. My checkboxes (dynammically generated) have the name of the town so are currently appearing in my query string as scriptname?townA=On&townB=On etc
I'd like to use jQuery to catch the form data before it is posted to change the format from one to the other. I've been trying to do this with the following code but I can't get it working:
$("#frmmap").click(function () {
var myarr = $('#myform').getFormValues();
$.each(myarr, function (key, value) {
alert(key + ": " + value);
});
$("#frmmap").submit();
});
jQuery.fn.getFormValues = function () {
var formvals = {};
jQuery.each(jQuery(':input', this).serializeArray(), function (i, obj) {
if (formvals[obj.name] == undefined)
formvals[obj.name] = obj.value;
else if (typeof formvals[obj.name] == Array)
formvals[obj.name].push(obj.value);
else formvals[obj.name] = [formvals[obj.name], obj.value];
});
return formvals;

Keep getting [object, Object] from array for $.each

I keep getting [object, Object] from array for $.each when i try and alert it.
Below is the code I am using, I have tried several different ways but this seems to be the way that works the best.
Could someone please help me out
var min_chats = [];
$(function () {
$(".append_chat").click(function () {
var chatid = $(this).attr('alt');
var data = $(this).attr('data');
min_chats.push({
"chatid": chatid,
"data": data
});
});
$("#max_close").live("click", function () {
var chatid = $(this).attr('alt');
var data = $(this).attr('data');
$.each(min_chats, function (key, val) {
alert(key + val);
});
});
});
The callback parameters for $.each are index and value, not key and value.
In your case key will contain the index of the array and val will contain your object containing 2 properties: chatid and data.
So your code should look like:
$.each(min_chats, function(index, val) {
alert(val.chatid + val.data);
});
$.each documentation: http://api.jquery.com/jquery.each/

Why can't jQuery update array data before ajax post?

I am trying to create an array and get all values of a form submission and put them in that array. I need to do this because during the .each function of this code I must do additional encryption to all the values per client. This is a form with hundreds of fields that are changing. So it must be an array to work. I tried to do following and several other types like it in jQuery but no dice. Can anyone help? Thanks.
Edit: Posted my working solution. Thanks for the help.
Edit 2: Accept sabithpocker's answer as it allowed me to keep my key names.
var inputArray = {};
//jQuery(this).serializeArray() = [{name: "field1", value:"val1"}, {name:field2...}...]
jQuery(this).serializeArray().each(function(index, value) {
inputArray[value.name] = encrypt(value.value);
});
//now inputArray = [{name: "field1", value:"ENCRYPTED_val1"}, {name:field2...}...]
//now to form the POST message
postMessages = [];
$(inputArray).each(function(i,v){
postMessages.push(v.name + "=" + v.value);
});
postMessage = postMessages.join('&');
Chack serializeArray() to see the JSON array format.
http://jsfiddle.net/kv9U3/
So clearly the issue is that this in your case is not the array as you suppose. Please clarify what this pointer refers to, or just verify yourselves by doing a console.log(this)
As you updated your answer, in your case this pointer refers to the form you submitted, how do you want to iterate over the form? what are you trying to achieve with the each?
UPDATE
working fiddle with capitalizing instead of encrypting
http://jsfiddle.net/kv9U3/6/
$('#x').submit(function (e) {
e.preventDefault();
var inputArray = [];
console.log(jQuery(this).serializeArray());
jQuery(jQuery(this).serializeArray()).each(function (index, value) {
item = {};
item[value.name] = value.value.toUpperCase();
inputArray[index] = item;
});
console.log(inputArray);
postMessages = [];
$(inputArray).each(function (i, v) {
for(var k in v)
postMessages[i] = k + "=" + v[k];
console.log(i, v);
});
postMessage = postMessages.join('&');
console.log(postMessage);
return false;
});
The problem is that #cja_form won't list its fields using each. You can use serialize() instead:
inputArray = jQuery(this).serialize();
Further edition, if you need to edit each element, you can use this:
var input = {};
$(this).find('input, select, textarea').each(function(){
var element = $(this);
input[element.attr('name')] = element.val();
});
Full code
jQuery(document).ready(function($){
$("#cja_form").submit(function(event){
$("#submitapp").attr("disabled","disabled");
$("#cja_status").html('<div class="cja_pending">Please wait while we process your application.</div>');
var input = {};
$(this).find('input, select, textarea').each(function(){
var element = $(this);
input[element.attr('name')] = element.val();
});
$.post('../wp-content/plugins/coffey-jobapp/processes/public-form.php', input)
.success(function(result){
if (result.indexOf("success") === -1) {
$("#submitapp").removeAttr('disabled');
$("#cja_status").html('<div class="cja_fail">'+result+'</div>');
}
else {
page = document.URL;
if (page.indexOf('?') === -1) {
window.location = page + '?action=success';
}
else {
window.location = page + '&action=success';
}
}
})
.error(function(){
$("#submitapp").removeAttr('disabled');
$("#cja_status").html('<div class="cja_fail"><strong>Failed to submit article! Check your internet connection.</strong></div>');
});
event.preventDefault();
event.returnValue = false;
return false;
});
});
Original answer:
There are no associative arrays in javascript, you need a hash/object:
var input = {};
jQuery(this).each(function(k, v){
input[k] = v;
});
Here is my working solution. In this example it adds cat to all the entries and then sends it to the PHP page as an array. From there I access my array via $_POST['data']. I found this solution on http://blog.johnryding.com/post/1548511993/how-to-submit-javascript-arrays-through-jquery-ajax-call
jQuery(document).ready(function () {
jQuery("#cja_form").submit(function(event){
jQuery("#submitapp").attr("disabled","disabled");
jQuery("#cja_status").html('<div class="cja_pending">Please wait while we process your application.</div>');
var data = [];
jQuery.each(jQuery(this).serializeArray(), function(index, value) {
data[index] = value.value + "cat";
});
jQuery.post('../wp-content/plugins/coffey-jobapp/processes/public-form.php', {'data[]': data})
.success(function(result){
if (result.indexOf("success") === -1) {
jQuery("#submitapp").removeAttr('disabled');
jQuery("#cja_status").html('<div class="cja_fail">'+result+'</div>');
} else {
page = document.URL;
if(page.indexOf('?') === -1) {
window.location = page+'?action=success';
} else {
window.location = page+'&action=success';
}
}
})
.error(function(){
jQuery("#submitapp").removeAttr('disabled');
jQuery("#cja_status").html('<div class="cja_fail"><strong>Failed to submit article! Check your internet connection.</strong></div>');
});
event.preventDefault();
event.returnValue = false;
});
});

Show contents of localStorage into div

I have this basic function :
pid = 1;
$(function() {
if (localStorage["key"+pid] != null) {
var contentsOfDiv = localStorage.getItem("key"+pid);
$("#Div").html(contentsOfdDiv);
}
});
The problem is that the pid value will change eventually and I don't want to overwrite the contents of the key.
How can I proceed to stack every Div content that localStorage is saving for me ?
You can iterate on localStorage entries just like on any object properties :
for (var key in localStorage) {
console.log(key, localStorage[key]);
}
So your code could be :
$(function() {
var lines = [];
for (var key in localStorage) {
if (/^key/.test(key)) { // does the key start with "key"
lines.push(key.slice(3) + ' = ' + localStorage[key]);
}
}
$("#Div").html(lines.join('<br>'));
});
If I have understood well, you want to use pid to loop over the object.
Best way to do this and avoid for in chain prototypical problems is the following:
(I think for this case you are better with an array rather than with an object)
http://jsfiddle.net/hqkD9/
var localStorage = ['aaaa', 'bbbbb', 'cccc', 'dddd']; // don't forget to declare with var
var html_string = '';
$.each(localStorage, function(index, value) {
html_string += value + '<br>';
});
$('#my_div').html(html_string);

Categories

Resources