Storing a php array client side - javascript

I have a web page that queries a database to get a list of products with their related data like price, size,weight e.t.c and displays it to the user, I want to add one of those sort dropdown list so that a user can sort the products by price or any other key I specify.
I plan to do it using Ajax on dropdown change query the database again and use the selected value as the sort key in the query.
My question is, is there a way that this can be done client side without running another query? Can php send the query result to the browser and store it there and then use jquery to sort it over and over again?
Thanks everyone for the help!

There are many ways this can be achieved. A simple example can be done with HTML5 LocalStorage.
Here's a general overview of how that can be done:
You make an initial call to your DB for products via AJAX, returns a JSON object.
You serialize that JSON object via javascript e.g. var stringData = JSON.stringify(data)
Store said variable into localstorage: window.localStorage.setItem("products", stringData);
You can then later access it via var products = window.localStorage.getItem("products) and finally deserialize it with var productsObj = JSON.parse(products) or do it all in one c-c-c-c-c-combo breaker: productsObj = JSON.parse(window.localStorage.getItem("products))
Do as you please by using filtering functions!
Another way is to store the initial JSON object using some form of store e.g. Redux, but let's save that for another day ;)
And of course, you may optionally have a globally accessible object that you can assign the initial JSON data to as a property and later access as you would any other property.

Take a look at this jquery plugin
http://tablesorter.com/docs/example-ajax.html
Maybe it's what you are looking for? No need to requery the database.

Related

JSON in localforage, efficient way to update property values (Binarysearch, etc.)?

I would like to come straight to the point and show you my sample data, which is around the average of 180.000 lines from a .csv file, so a lot of lines. I am reading in the .csv with papaparse. Then I am saving the data as array of objects, which looks like this:
I just used this picture as you can also see all the properties my objects have or should have. The data is from Media Transperency Data, which is open source and shows the payments between institiutions.
The array of objects is saved by using the localforage technology, which is basically an IndexedDB or WebSQL with localstorage like API. So I save the data never on a sever! Only in the client!
The Question:
So my question is now, the user can add the sourceHash and/or targetHash attributes in a client interface. So for example assume the user loaded the "Energie Steiermark Kunden GmbH" object and now adds the sourceHash -- "company" to it. So basically a tag. This is already reflected in the client and shown, however I need to get this also in the localforage and therefore rewrite the initial array of objects. So I would need to search for every object in my huge 180.000 lines array that has the name "Energie Steiermark Kunden GmbH", as there can be multiple and set the property sourceHash to "company". Then save it again in the localforage.
The first question would be how to do this most efficient? I can get the data out of localforage by using the following method and set it respectively.
Get:
localforage.getItem('data').then((value) => {
...
});
Set:
localforage.setItem('data', dataObject);
However, the question is how do I do this most efficiently? I mean if the sourceNode only starts with "E" for example we don't need to search all sourceNode's. The same goes of course for the targetNode.
Thank you in advance!
UPDATE:
Thanks for the answeres already! And how would you do it the most efficient way in Javascript? I mean is it possible to do it in few lines. If we assume I have for example the current sourceHash "company" and want to assign it to every node starting with "Energie Steiermark Kunden GmbH" that appear across all timeNode's. It could be 20151, 20152, 20153, 20154 and so on...
Localforage is only a localStorage/sessionStorage-like wrapper over the actual storage engine, and so it only offers you the key-value capabilities of localStorage. In short, there's no more efficient way to do this for arbitrary queries.
This sounds more like a case for IndexedDB, as you can define search indexes over the data, for instance for sourceNodes, and do more efficient queries that way.

Accessing item from LocalStorage (Angular 1.2)

I am running an old version of Angular - I have an object within my localStorage and I am trying to retrieve a single item from the object (rather than the whole the thing..)
var email = localStorage.user;
However the output of the localStorage.user variable is much longer (see below)- how would I retrieve the email address in this case 'bob#abc.com'?
{"firstname":"Bob","lastname":"Dole","id":"2000001999","accountId":"15","email":"bob#abc.com","instances":[{"name":"Test"}]}"
LocalStorage values are always stored as strings. In order to refer to the email in the object, we need to convert it to a JSON. We can do that by parsing the string using JSON.parse() method like below :
var email = JSON.parse(localstorage.user).email
You have Json structure not JS object, so parse it 1st
var email = JSON.parse(localStorage.user).email;
Using html5 local storage we can store data, add expire time by using cookies and sessions. https://stackoverflow.com/a/41385990/6554634 go through that, gives a lot of explanation

Is it possible to store a JSON object directly into the DOM somehow?

If one has the output of a JSON.parse readily at hand, is there some legitimate way of storing that object in the DOM as a single entity?
i.e.
jsonObject = JSON.parse(something);
I'd like to consider storing the jsonObject in the DOM as a (child || textNode || ???) of some element and later retrieving it so that immediately after retrieval I could access its contents via the usual:
jsonObject.keyName
I want to avoid adding dozens of dataset attributes and later being forced to extract them one at a time. That's too much work and seems too inefficient if you have dozens of key:value pairs.
Data attributes have to be strings, you can't store objects in them directly. So don't parse the JSON string, just store the JSON string directly in the dataset attribute.
If you use jQuery, its .data() method will take an object, and it will automatically stringify it as needed.
If the elements you want to associate the object with all have IDs, another option is to use a global object as a table, keyed off the element's ID.
jsonTable[id] = jsonObject;
It depends on the life cycle of your page. If you don't intend to reload the page it's better to just leave it as a JavaScript variable on the page.
You can also consider storing the raw JSON in a hidden filed or some other hidden DOM element. Keep in mind though that hidden fields will be posted to the server if you do a post of the page
TGH has the right answer. Leave it as a variable.
An alternative is to use history.pushState() to store it along with the URL to your page. This is helpful if you ever want the user to be able to click the back button and have the json restored to the value it had for that page.
If you want to store a data (JSON) associated with DOM element.
You could use jQuery data function.
e.g., store a JSON to a restaurant row (div)
$("div.restaurant-row").data("info",{purchases: "blablabla", mealFormulas: "xxxxx"});
e.g., fetch DOM associatd data
$("div.restaurant-row").data("info").purchases; //blablabla
I'm not sure if this is what you want.
Hope this is helpful for you.

pass multidimensional javascript array to another page

I have a multidimensional array that is something like this
[0]string
[1]-->[0]string,[1]string,[2]string
[2]string
[3]string
[4]-->[0]string,[1]string,[2]string[3]string,[4]string,[5]INFO
(I hope that makes sense)
where [1] and [4] are themselves arrays which I could access INFO like myArray[4][5].
The length of the nested arrays ([1] and [4]) can varry.
I use this method to store, calculate, and distribute data across a pretty complicated form.
Not all the data thats storred in the array makes it to an input field so its not all sent to the next page when the form's post method is called.
I would like to access the array the same way on the next page as I do on the first.
Thoughts:
Method 1:
I figure I could load all the data into hidden fields, post everything, then get those values on the second page and load themm all back into an array but that would require over a hundred hidden fields.
Method 2:
I suppose I could also use .join() to concatenate the whole array into one string, load that into one input, post it , and use .split(",") to break it back up. But If I do that im not sure how to handel the multidimensional asspect of it so that I still would be able to access INFO like myArray[4][5] on page 2.
I will be accessing the arrary with Javascript, the values that DO make it to inputs on page 1 will be accessed using php on page 2.
My question is is there a better way to acomplish what I need or how can I set up the Method 2 metioned above?
This solved my problem:
var str = JSON.stringify(fullInfoArray);
sessionStorage.fullInfoArray = str;
var newArr = JSON.parse(sessionStorage.fullInfoArray);
alert(newArr[0][2][1]);
If possible, you can use sessionStorage to store the string representation of your objects using JSON.stringify():
// store value
sessionStorage.setItem('myvalue', JSON.stringify(myObject));
// retrieve value
var myObject = JSON.parse(sessionStorage.getItem('myvalue'));
Note that sessionStorage has an upper limit to how much can be stored; I believe it's about 2.5MB, so you shouldn't hit it easily.
Keep the data in your PHP Session and whenever you submit forms update the data in session.
Every page you generate can be generated using this data.
OR
If uou are using a modern browser, make use of HTML5 localStorage.
OR
You can do continue with what you are doing :)

JSON parsing a Titanium.App.Properties string

In an app, made with TideSDK; i assign a global variable (shocking I know) to a the JSON parse of a string stored in Titanium.App.Properties:
var workbookArray = JSON.parse(Titanium.App.Properties.getString('workbookArray'));
workbookArray is an array of objects.
And then on the unloading of a page, I assign Titanium.App.Properties string the value of workbookArray, which may have been changed by whoever has used the app:
Titanium.App.Properties.setString('workbookArray', JSON.stringify(workbookArray));
Each time I open the app, however, I'm told that JSON was unable to parse the first code snippet (initializing workbookArray).
Aside from this issue, I don't expect to use the app Properties API for my storage needs in the longterm, I wish i could use indexedDB with titanium. SQL is an option, but is a little messy when it comes to objects. Any other suggestions for a database solution?
Try getList and setList
http://docs.appcelerator.com/titanium/latest/#!/api/Titanium.App.Properties
What is stored in the list?

Categories

Resources