I have been scouring this website and the internet for a few hours now, and asked a question earlier which got me at least a step further.. However I am really struggling to understand how to save multiple arrays to my localStorage.
I can understand the process using a hardcoded array, but as soon as I try to implement the localStorage data, I can't understand what to do.
Heres what I have tried so far (with help from another SO user):
$("#submit").click(function () {
// prepare
var formData = $("#regForm").serializeArray();
// get all stored as Array []
var bookings = JSON.parse(localStorage.getItem('bookings') || '[]');
for (formData = 0; formData < localStorage.length; formData++) {
// insert and save
localStorage.setItem("bookings", JSON.stringify([formData]));
}
});
It works fine without the for loop, however when I resubmit the form with new data it replaces it rather than creates a new index?
Basically I am trying to create an appointment scheduler for dog walking and I need to be able to view each booking, amend, delete, and of course view the bookings (all client side - no databases).
Should I be initialising my array first? How to I approach the for loop? Any help is appreciated as I want to learn but I have been at this for hours with no luck.
You can use like following.
Save new values in the the previously stored values in variable and update the local storage at the end.
$("#submit").click(function () {
var formData = $("#regForm").serializeArray();
var bookings = JSON.parse(localStorage.getItem('bookings') || '[]');
for (formData = 0; formData < localStorage.length; formData++) {
bookings.push(formData)
}
localStorage.setItem("bookings", JSON.stringify(bookings));
});
Related
First of all, I have never successfully built an AJAX call that worked. This is my first real try at doing this.
I am working on building a function to update existing records in a SQL database. I am using ASP.NET Core (.NET 6) MVC but I also use JavaScript and jQuery. I cannot have the page refresh, so I need to use ajax to contact the Controller and update the records.
I have an array that was converted from a NodeList. When I debug step by step, the collectionsArray looks perfectly fine and has data in it.
//Create array based on the collections list
const collectionsArray = Array.from(collectionList);
$.ajax({
method: 'POST',
url: '/Collections/UpdateCollectionSortOrder',
data: collectionsArray,
})
.done(function (msg) {
alert('Sent');
});
However, when I run the application and debug the code, the array is received in the Controller as {string[0]}.
Here is the method which is in the Controller, with my mouse hovered over the parameter:
Do not pay attention to the rest of the code in the controller method. I have not really written anything in there of importance yet. I plan to do that once the data is correctly transferred to the Controller.
I have tried dozens of ideas including what you see in the Controller with the serialize function, just to see if it processes the junk data that is getting passed, but it hasn't made a difference.
I have been Googling the issue & reading other StackOverflow posts. I've tried things like adding/changing contentType, dataType, adding 'traditional: true', using JSON.stringify, putting 'data: { collections: collectionsArray }' in a dozen different formats. I tried processing it as a GET instead of POST, I tried using params.
I am out of ideas. Things that have worked for others are not working for me. What am I doing wrong? I'm sure it's something minor.
UPDATE: Here is the code which explains what the collectionList object is:
//Re-assign SortID's via each row's ID value
var collectionList = document.querySelectorAll(".collection-row");
for (var i = 1; i <= collectionList.length; i++) {
collectionList[i - 1].setAttribute('id', i);
}
What I am doing is getting a list off the screen and then re-assigning the ID value, because the point of this screen is to change the sort order of the list. So I'm using the ID field to update the sort order, and then I plan to pass the new IDs and names to the DB, once I can get the array to pass through.
UPDATE: SOLVED!
I want to post this follow up in case anyone else runs into a similar issue.
Thanks to #freedomn-m for their guidance!
So I took the NodeList object (collectionList) and converted it to a 2-dimensional array, pulling out only the fields I need, and then I passed that array onto the controller. My previous efforts were causing me to push all sorts of junk that was not being understood by the system.
//Create a 2-dimensional array based on the collections list
const collectionArray = [];
for (var i = 0; i < collectionList.length; i++) {
collectionArray.push([collectionList[i].id, collectionList[i].children[1].innerHTML]);
}
$.ajax({
method: 'POST',
url: '/Collections/UpdateCollectionSortOrder',
data: { collections: collectionArray }
})
.done(function (msg) {
alert('Sent');
});
2-d array is coming through to the Controller successfully
my Script is reading Data given from a WebSocket and my goal is, to save the Data from the Websocket in a Table (HTML). This is what my Function looks like, as you can see im reading the Data from an Object, and im trying to display each Object in my HTML Table.
function websocketPush(item){
let t_item = {}
for ( let key in properties){
t_item[key] = resolve(properties[key],item);
}
t_item["id"] = id;
id++;
//data.push(t_item);
//data = data.slice(-30);
table.addData([t_item],true);
}
But instead of logging each item in the Table, its just logging 1 by 1 and keeps resetting the old ones.
So basically I want all the logged filed in the table and not just the newest one. I think my problem is the "id++" but I just dont know any better...
Any Help is appreciated! Thanks in advance!
I want to be able to create JavaScript note objects and dynamically delete them using a navbar pane.
var sel = window.getSelection();
var range = sel.getRangeAt(0);
var editor = { "startContainer": range.startContainer, "startOffset": range.startOffset, "endContainer": range.endContainer, "endOffset": range.endOffset };
Then using a message I would pass the location and message into a function to add notes:
Notes(editor, message);
function Notes(location, note) {
this.location = location;
this.note = note;
}
I'm trying to wrap my brain around how to actually save the data locally.
function addNote() {
// if(tyepof(Storage) !== "undefined"){
// if(localStorage.notes){
// localStorage.notes
// } else {
// localStorage.notes =
// }
localStorage.setItem()
}
Is localStorage the way to go? I know sessionStorage only stores for a session.
Here's a quick way to generate a few elements from a localStorage.getItem() call and could maybe also help you out here along with Nelson's answer. Click on the button in the fiddle and you'll see the code grab the localStorage objects and use them to create some simple <li>'s.
Fiddle:
http://jsfiddle.net/kfrvdnux/
Example code:
HTML
<button id='save'>Click the save button...</button>
<div id='content'></div>
JS
var content = document.getElementById('content'),
save = document.getElementById('save'),
output = '<ul>',
animals = [{
name: 'bob',
type: 'dog'
}, {
name: 'fred',
type: 'lizard'
}];
// set on load for testing
localStorage.setItem('animals', JSON.stringify(animals));
// grab localStorage data on click and create a list
save.addEventListener('click', function() {
var ls = JSON.parse(localStorage.getItem('animals'));
for (var i = 0; i < ls.length; i++) {
output += '<li>' + ls[i].name + ', ' + ls[i].type + '</li>';
}
output += '</ul>';
content.innerHTML = output;
});
You have many ways of doing this. In fact so many that is not praticable to explain all of them. It depends on you actual intent. If you just want notes you can loose aftwards, localStorage may be the way to go.
But for most applications you typically would do this sending data to a server that would be responsible for storing the data. In the server the data could be stored in a database, in local files, there are many ways.
Servers could be Node.js (if you want to stick to js only), or any other language that has server capabilities. That would be pratically all. Most used are Node, PHP, Python, Java and others.
You would prepare a certain url to receive a post with the data that needs to be saved and then make the client send an ajax request to this url with it.
in this question you can get some examples of how to start doing this:
Basic Ajax send/receive with node.js
the server save part is up to you :)
edit
here is a small tutorial about localStorage
https://www.taniarascia.com/how-to-use-local-storage-with-javascript/
just remember that every time you reload the page you will loose everything. In order to save the data you have to send it to a server.
Another thing: you don't need to buy a dedicated server to do this. You can implement the server in your own machine. This is a relatively easy task. Not that complicated. I advise you to take a look in the SO question above about basic ajax send/receive, before you rule this out.
Are you trying to save .txt files locally to the computer? I don't believe JavaScript has this function because it would be a huge security hole. My understanding is that you could create cookie files on the local machine but that is about it.
If you need to export files you could always use an ASP.NET/PHP to create files on a server, then the user could click on a link that would prompt you to save the dynamically created file.
Based on the comment below you should create an array of objects.
var array = [];
array[array.length] = {name: 'NAME CONTENT', other: 'Other content', number: 1}
array[array.length] = {name: 'NAME CONTENT 2', other: 'Other content 2', number: 1}
You can then get a function to do things with your object by doing something like this
PrintInfo(array[i]);
function PrintInfo(aSingleObject){
console.log(aSingleObject.name);
console.log(aSingleObject.other);
console.log(aSingleObject.number);
}
To remove objects from your array using the splice command
var array = [2, 5, 9];
console.log(array)
var index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1);
}
// array = [2, 9]
console.log(array);
I've a div which contains a list of clients pulled from Mysql.
On the same page I have a jquery dialog box which pops up to allow a user to add a new client.
What I want to happen is that when the user adds a new client the containing the list reloads so the new client is available.
Is there a way to simply reload the div without using the Load() function as this is causing errors when I redeclare my classes that populate the list ?
Of course. Without looking at your code, your confusion here suggests that you don't understand "Separation of Concerns". Separate the process of getting information from the process of displaying that information. When the user enters new information, add that to javascript array or object of information you got from the server and also send that off to the server to be updated in the database. Then run the display function again using the updated information to include the new information. Ideally, the display process will use existing markup if it can, rather than deleting it all and recreating it all just to add one item. Here's a very basic example (click here). Ideally, you would take this concept and expand on it to make it optimally efficient and organized.
Here's the sample code from my jsbin. Please keep in mind this is just to get you started.
var info = [1,2,3,4,5]; //this is what you got from your ajax call to the server
function render(element, info) {
//this is a lazy system that recreates/replaces all the markup each time. I suggest doing this more efficiently, but that is work for you to do :)
var frag = document.createDocumentFragment();
var len = info.length;
for (var i=0; i<len; ++i) {
var p = document.createElement('p');
p.textContent = info[i];
frag.appendChild(p);
}
element.innerHTML = '';
element.appendChild(frag);
}
var targetElem = document.getElementById('targetElem');
render(targetElem, info);
var addButton = document.getElementById('add');
var input = document.getElementById('infoInput');
addButton.addEventListener('click', function() {
info.push(input.value); //update the information
render(targetElem, info); //render the updated information
});
Either of these should give you success.
success: function(userinfos) {
$("#users").append($('<tr><td>'+userinfos+'</td></tr>'))
display_message("user added");
}
$.ajax({
type: "GET",
url: "ht.tp://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+
occasionData +"&relationship="+ forData +"#",
success: function (response) {
$("#testDIV").html(response);
}
});
I need to call a web service from javascript that returns a JSON array in the following format:
["hello","there","I","am","an","array"]
Unfortunately, the javascript library I'm using (Sencha Touch) to load this data into a widget doesn't accept that format as data input. It will work with something like this however:
[["hello"],["there"],["I"],["am"],["an"],["array"]]
So there are two questions here-- how can I call that web service in javascript and then manipulate the returned array into the format I need? I've been looking at jQuery's getJson() method, not sure if that's the way to go or if there are better ways.
The URL that delivers the JSON array is this right here. Thanks for your help.
Here's a jsFiddle showing both parts of what you asked about. I'm using jQuery for my AJAX call (faked in the jsFiddle) and I'm using Underscore.js for the manipulation:
http://jsfiddle.net/JohnMunsch/E7YTQ/
// Part 1: Get the raw data. Unfortunately, within a jsFiddle I can't go get it from a different domain. So I'm
// simulating the call instead.
var rawDataPromise = $.ajax({
url : "/echo/json/",
data : fakeData,
type : "POST"
});
// var rawDataPromise = $.ajax("http://fastmotorcycleservice.cloudapp.net/FastMotorCycleListService.svc/list/Bruno");
rawDataPromise.done(
function (results) {
// Part 2: Manipulate the data into the form we need.
var manipulatedResults = _.map(results, function (item) { return [ item ]; });
console.log(manipulatedResults);
}
);
// You could also pull that together into a single call $.ajax(...).done(function (results) { ... });
once you have the data in one of your local variables you can manipulate it as you want:
var data = the_function_you_use_to_get_data();
var formatted_array = new Array();
for(i in data){
var d = new Array();
d[0] = i;
formatted_array.push(d);
}
i hope it answered your question