Firebase range query - javascript

Im using AngularFire+Firebase and have data at firebase-database.
Im trying to paginate Data with Smart Table
My problem is that I dont know how to range query without specifying any child i,e fetch records from record # 25 to 35
Below query gives me first 5 records
var queryFIrst = visitRef.startAt().limitToFirst(5);
$scope.Visits = $firebaseArray(queryFIrst);
now Im trying to get records next 5,from 6 to 10 and I tried below
var queryFIrst = visitRef.startAt().limitToFirst(5).endAt().limitToFirst(5);
$scope.Visits = $firebaseArray(queryFIrst);
but it giving error that startAt and endAt can't be used like this with limit

In general pagination is not a good fit for Firebase's realtime data model/API. You're trying to model a SQL SKIP operator, which won't work with the Firebase Database.
But if you want to model pagination in Firebase, you should think of having an "anchor point".
When you've loaded the first page, the last item on that page becomes the anchor point. When you then want to load the next page, you create a query that starts at the anchor point and load n+1 item.
In pseudo-code (it's real JavaScript, I just didn't run it):
var page1 = visitRef.orderByKey().limitToFirst(5);
var anchorKey;
page1.on('child_added', function(snapshot) {
anchorKey = snapshot.key; // this will always be the last child_added we received
});
Now when you want to load the next page of items, you create a new query that starts at the anchor key:
var page2 = visitRef.orderByKey().startAt(anchorKey).limitToFirst(6);
A few things to note here:
You seem to be using an approach from the Firebase 1.x SDK, such as an empty startAt(). While that code may still work, my snippets use the syntax/idiom for the 3.x SDK.
For the second page you'll need to load one extra item, since the anchor item is loaded for both pages.
If you want to be able to paginate back, you'll also need the anchor key at the start of the page.

Is that what you needed that time?
visitRef.orderByKey().startAt("25").endAt("35")
I asked a similar question Get specific range of Firebase Database children

Related

Get product details from the previous page

I want take list of purchased products. Unfortunately there are no product details on my "order-received" page. Can I get product details from the previous page using GTM?
Order-received Page
I have product details on a previous(basket) page:
function printOrderItems() {
var hrefs = document.querySelectorAll("#form_cart > table > tbody > tr > td.product-info > a");
var result = [];
hrefs.forEach(function(t) {
result.push(t.text)
});
return result;
}
previous page
this is being created when a customer chooses to make an order correct? could you not, using a jquery click event, send that information via an ajax and then load your order received page dynamically from a handler?
In case you still need an answer: Use a custom HTML tag to extract the products on the basket page and store the result in sessionStorage. SessionStorage accepts only a string, but you can use JSON.stringify to convert the array of product names into a string.
On the 'order-received' page use a variable of type Custom JavaScript to retrieve the products from sessionStorage. Use JSON.parse to convert the string back to an array. Then you can use this variable in any GTM tags that you want to run on that page.
Note though that sessionStorage is only available within the same subdomain and within the same tab. If that is an issue you could try to use a session cookie to persist the data from one page to the next. However, cookies are limited in size and therefore are not really suitable for persisting a potentially long list of product names.

Javascript/PHP - Get last post ID from livechat system

I am currently upgrading my livechat system to use the append function with JavaScript.
And in order to get it to work I will need to get the latest chat date or ID somehow.
So I can then do a query like:
SELECT date, message, name FROM chat WHERE id > $lastPostId";
This will then allow me to append all the latest messages instead of updating all of the HTML everytime there is a new message
So basically, my chat right now works like this:
Every second it checks for my PHP file, loadchat.php.
Loadchat.php will get every single message from the database
It then replaces all current data in my div: #chatbox by using .html() function.
And I want to change it to the append function in jquery allowing it to run a lot smoother
Because it only needs to read everything the first time and then append
So my question is, how do I get the last post ID?
Case 1:
Add one more field in your database called timestamp. When you update the chat you can store the value of last timestamp in session.Now each time fetching a new chat just send that timestamp to loadchat.php and query the db to fetch rows where timestamp > stored_timestamp.
Case 2:
You can take a flag in db like is_read. When you insert the new chat the default value of is_read will be 0. When you fetch the data just update the flag i.e is_read = 1. Now in your query you just have to check for the flag.
where is_read = 0.
It will fetch all the unread messages and will do the job.
Hope it will help!!

How to check changed columns in mysql

I have table user where id = primary key, lastchange = int with lastchange data (in seconds). And i have frontend page with js script. Also all users placed in div like table by pages. So, items has user id and used changed timevalue in attributes.
I want to request all changed user ids in 1 request (1 http and 1 sql). They can be changed by other user on site.
How can i do this? I dont want check every user in page by timer, there is too many requests.
In my mind it looks like:
js do get request with list of users in page in json format [{"id":1, "lastchange":123123},{"id":2, "lastchange":123123}...
Php does request in mysql like SELECT * FROM `users` WHERE `id` IN (1, 2, 3) AND `lastchange` NOT IN (123459, 123456, 123459); (this not works fine, there is no queue for lastchange, it checks all inside braces and result are wrong)
Php return only ids of different rows [1, 15, 22] etc. to js.
Js check every id separately in other request getting full info about user by id
I can check every user in php separately, but i want to know how can i do it with 1 SQL request
Sorry my bad English.
I think you might want to implement the solution differently as per the first comment.... but, if you want keep your current model the SQL you need would look something like:
SELECT * FROM users WHERE
(id = 1 AND lastchange <> 123123) OR
(id = 2 AND lastchange <> 123123) OR
...
This will keep the id's and the lastchange values that relate to each other being compared properly. It is pretty ugly SQL but not hard to generate in a loop.
Sorry my stupidness. I think i solve this.
Js request api with only user id in page
php response json like id, lastchange
js checking lastchange value and id in page
js request full data about changed user replaces old in page
Thx all for helping

Lightswitch load all data or run a async method synchronously

I have a grid with data in Lighswitch application. Grid has on every column posibility to filter column. Thanks to lsEnhancedTable
Right now I am sending an ajax request to the web api controler with the list of ids of the Customers that I want to export. It works but with a lot of data it is very slow because I have to turn off the paging of the data to get all visible customers ids so I can iterate over the VisualCollection.
To optimize this I would have to turn on back the paging of the data to 50 records so that the initial load is fast and move the loading of the data to a save/export to excel button.
Possible solutions:
Load data all data on save button click. To do this I have to somehow load all items before I can iterate over collection.
The code bellow locks UI thread since the loadMore is async. How to load all data synchronously? Ideally I would like to have some kind of progress view using a msls.showProgress.
while(3<4)
{
if (screen.tblCustomers.canLoadMore) {
screen.tblCustomers.loadMore();
}
else
break;
}
var visibleItemsIds = msls.iterate(screen.tblCustomers.data)
.where(function (c) {
return c;
})
Second approach would be turn on paging and pass just the filters applied by the users to the web api controller so I can query database and return only filtered records. But I don't know how to do that.
Third approach is the one that I am using right now. Turn off the paging->iterate over visual collection, get the customers id, pass them to the controller and return a filtered excel. This doesn't work well when there are a lot of records.
Iterate over filtered collection in the server side? I don't know if there is a way to do this in Lighswitch?
Here's an option for client side javascript.
// First build the OData filter string.
var filter = "(FieldName eq " + msls._toODataString("value", ":String") + ")";
// Then query the database.
myapp.activeDataWorkspace.ApplicationData.[TableName].filter(filter).execute().then(function (result) { ... });

Simple pagination for jquery after ajax success of php select

I want to paginate the result of my ajax success. In my ajax when I get success I append all result into one table (this table is empty by default only header).
I used this tutorial but I can't figure out how to make it work when the table is empty by default. I was able to make it run when there are values by default.
When the table is populated after ajax success nothing is happening to the data all are displayed. Is there a more applicable sample or tutorial for this kind of scenario. Or what needs to be done on the current tutorial to make it work.
Any suggestion is appreciated
You shouldn't use pagination this way, I suggest you to make your function returning only the records needed for the selected page.
It's useles to make your ajax return all the set (ej. 300 rows) if you are only going to show only a subset (ej. 30 rows in page 1). So you should add to the function which return the records from the DB (lets call it getRecords) a few parameters more:
page: the current/selected page of the paginator
records: how many records you want to show in each page
Combining this two you can limit your sql accordingly, f.instance (you can prepare the limit and the offset before the call in your php code):
select blablabla from blablable where blablablu
limit records, offset (page * records)
note: the first page here is zero. So for the first page the first record will be 0 and the last record shown will be 30 (this is (0 + 1) *30).
Here you have a good tutorial.

Categories