Can you permanently add to an array in Javascript?

Forgive me, I'm very new to programming in general, especially Javascript. I've basically got an array as shown simplified below.

var recipes = [
    { "recipeName":"Recipe1" , "ingredient1":"Recipe1Ingredient1" , "ingredient2":"Recipe1Ingredient2" , "ingredient3":"Recipe1Ingredient3"},
    { "recipeName":"Recipe2" , "ingredient1":"Recipe2Ingredient1" , "ingredient2":"Recipe2Ingredient2" , "ingredient3":"Recipe2Ingredient3"},
];

On one page, users can search for recipes. On another, they can add recipes to the array via an HTML form. I have the following which pushes the new data to the array.

recipes.push({"recipeName":newRecipeName , "ingredient1":newIngredient1 , "ingredient2":newIngredient2 , "ingredient3":newIngredient3});

This works fine initially, but if I refresh the page or go back to the find page, the new recipe is removed from the array. I want the new recipe to be added permanently to the array.

I'm guessing the solution for this isn't so simple, but I've been looking into this for a while and done a lot of searching to no avail. Can anybody point me in the right direction? Again apologies for my inexperience, I'm very new to programming.

Answers:

Answer

The main thing you need to keep in mind here is that each time the page is refreshed it has no knowledge of the data that was on the previous page. As was mentioned in a previous comment, persistent storage is what you're looking for. This might come in the form of a full-on (NoSQL/RDBMS) database or in some other semi-permanent form stored only within the browser.

You can either start using a full-on database or if you want something more light weight, you can use local storage or cookies. One thing to note is that, unless you implement something server side, eg: a database, the changes will be persistent only to the user and only so long as they don't clear the cache.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.