Remove item from firebase array with value using jquery - javascript

I want to remove a value from firebase database with value using jquery.
I want to delete 235 value from the firebase.
I tried..
var dbRef = new Firebase("https://afgani-cinemas.firebaseio.com/");
var showId = getUrlParameter('showId');
var bookings = dbRef.child('bookings/'+showId);
function removeFromFB(seatId){
dbRef.orderByValue().equalTo().on('child_added', function(snapshot){
snapshot.dbRef().remove();
});
}
removeFromFB(235);
Any suggestions in my code. Its not working!!!
getting warning like this
firebase.js:40 FIREBASE WARNING: Using an unspecified index. Consider adding ".indexOn": ".value" at / to your security rules for better performance

Try using this code snippet
var bookings = firebase.child('root/321');
function removeFromFB(valu){
bookings.on('child_added', function(data) {
if(data.val()==valu){
bookings.child(data.key()).remove();
}
});
}
removeFromFB(deleteValue);
in your case "deleteValue" will be 235

Related

How can i get data from firebase

I want to do a user search vie search bar.when I enter the last name I should receive data about users if there are matches but i don't know how.
here is my try
searchBar(){
let a=app.database().ref('users/'+app.auth().currentUser.uid).orderByChild('/surname').equalTo('Крюкин');
console.log(a);
}
here is structure of data
Try the following:
searchBar(){
let a=app.database().ref('users');
a.orderByChild('surname').equalTo('Крюкин').on('value',((snapshot) => {
snapshot.forEach((childSnapshot) => {
console.log(childSnapshot.val());
});
}
First you are not using a userID, that's a random id generated using push() in your database. Therefore you need to use forEach() to access the data.
Check the guide:
https://firebase.google.com/docs/database/web/read-and-write
you dont exactly read data from firebase.
You should create a handle, which you did, a in your case
and then on that handle you register value event listener the code below is from official docs
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
// ...
});
});
in your case you shloud just to
a.on("value",list=>{list.forEach(...)})
also you can subscribe for future child_added/removed/updated events
here are the docs

Trying to delete a multi-path firestore field document with the batch method

I'm trying to delete a field document with multi-path location with the
firestore batch method. I used to do it with the update method on Real Time Database. Now I don't really know how to do it on Firestore.
deleteVenueFromEvent(event)
{
var eventkey = event.$key;
var venuekey = event.venue.venuekey;
var batch = this.afs.firestore.batch();
var eventRef = this.eventCollection.doc(eventkey).ref;
batch.update(eventRef, { venue: null });
var deleteVenueRef = this.venueCollection.doc(venuekey).collection('events').doc(eventkey).ref;
batch.delete(deleteVenueRef);
batch.commit().then(function() {console.log('Batch Delete')});
}
I find the way to do it with the following code :
var deleteVenueRef = this.venueCollection.doc(venuekey).ref;
batch.update(deleteVenueRef, {['events.' + eventkey] :firebase.firestore.FieldValue.delete()});

Firebase - Set Firebase references dynamically based on user input

I'm trying to set firebase references dynamically. What I know from the doc is firebase set references at the initial state. As long as I try to make it dinamic it give me permission error.
For example I want to get fruit name from the input, so the code:
$('.fruit').click(function(){
var name = $(this).text();
getFuitName(name);
});
function getFruitName(name){
var fruit = firebase.database().ref('fruit/' + name );
fruit.once('value', function(snapshot) {
console.log(snapshot.val().name);
});
}
What should I do? Any special approach to do this?
I found the solution. I've to separated the database references like this:
var database = firebase.database(); // I add this line
$('.fruit').click(function(){
var name = $(this).text();
getFuitName(name);
});
function getFruitName(name){
var fruit = database.ref('fruit/' + name ); //and then modified this line
fruit.once('value', function(snapshot) {
console.log(snapshot.val().name);
});
}

Firebase Web retrieve data

I have the following db structure in firebase
I'm trying to grab data that belongs to a specific user id (uid). The documentation has the following example:
firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
var username = snapshot.val().username;
// ...
});
But how can I retrieve data from my example without knowing the unique key for each object?
Update:
I tried a new approach by adding the user id as the main key and each child object has it's own unique id.
Now the challenge is how to get the value of "title".
firebase.database().ref('/tasks/').orderByChild('uid').equalTo(userUID)
Well that is pretty straightforward. Then you can use it like this:
return firebase.database().ref('/tasks/').orderByChild('uid').equalTo(userUID).once('value').then(function(snapshot) {
var username = snapshot.val().username;
// ...
});
Of course you need to set userUID.
It is query with some filtering. More on Retrieve Data - Firebase doc
Edit: Solution for new challenge is:
var ref = firebase.database().ref('/tasks/' + userUID);
//I am doing a child based listener, but you can use .once('value')...
ref.on('child_added', function(data) {
//data.key will be like -KPmraap79lz41FpWqLI
addNewTaskView(data.key, data.val().title);
});
ref.on('child_changed', function(data) {
updateTaskView(data.key, data.val().title);
});
ref.on('child_removed', function(data) {
removeTaskView(data.key, data.val().title);
});
Note that this is just an example.

Cant get the current id of a data from local Storage using jquery

I am working on an app to store data offline. My problem is when I try to retrieve the data from local storage for update/edit, it keeps calling only the id of the first item, and not calling the id of the data in view.
Please what am I doing wrong?
Here is my code for loading employees:
// load cases from localStorage
var employees;
if (localStorage.getItem('employees')) {
employees = JSON.parse(localStorage.getItem('employees'));
} else {
// If no cases, create and save them
employees = [];
// offling storing of our cases
localStorage.setItem('employees', JSON.stringify(employees));
}
// show case listing in list view page
var showEmployees = function () {
//erase existing content
$('#employee_list').html('');
//insert each employee
for (var i = 0; i<employees.length; i++) {
addEmployees(employees[i]);
}
};
Here is my code to add an employee to list view:
//add an eliment to list view
var addEmployees = function (empData) {
//HTML content of one list element
var listElementHTML = '<li><a class="employee_list" ui-btn ui-btn-e ui-btn-icon-right ui-icon-carat-r" data-transition="fade" data-split-icon="delete" href="#item'+empData.id+'">' + empData.employeename + '<br> ' + empData.dateofbirth + '</br></a></li>';
//appending the HTML code to list view
$('#employee_list').append(listElementHTML);
};
Here is my code for Edit function:
//User input to edit form
$('#edit_employee_page').on('click' , function () {
var editEmployee = JSON.stringify({
id: employees.length+1,
employeeno: $('#employeeno').val(),
employeename:$('#employeename').val(),
stateoforigine:$('#stateoforigine').val(),
employeephone: $('#employeephone').val(),
dateofbirth:$('#dateofbirth').val()
});
//Alter the slected data
localStorage.setItem("employees", JSON.stringify(employees));
return true;
});
for (var i in employees) {
var id = JSON.parse(localStorage.getItem(employees[i]));
}
Here is my code for the Edit button:
//register Edit button
$('.edit_button').live('click', function (e) {
alert('I was Cliked!');
e.stopPropagation();
$.each(employees, function(a, b) {
//if(b.id == employees[i]){
$('#id').val(b.id);
$('#employeeno').val(b.employeeno);
$('#employeename').val(b.employeename);
$("#stateoforigine").val(i.stateoforigine);
$('#employeephone').val(b.employeephone);
$('#dateofbirth').val(b.dateofbirth);
$("#id").attr("readonly","readonly");
$('#employeeno').focus();
$.mobile.changePage('#edit_employee_page');
return false;
//}
});
});
Here is my local Storage:
[
{"id":1,
"employeeno":"DEF/234/20014",
"employeename":"Bill Gates",
"stateoforigine":"Osun",
"employeephone":"080765432",
"dateofbirth":"12/11/1965"},
{"id":2,
"employeeno":"DEF/234/20014",
"employeename":"Bill Gates",
"stateoforigine":"Osun",
"employeephone":"080765432",
"dateofbirth":"12/11/1966"},
{"id":3,
"employeeno":"DEF/234/20014",
"employeename":"Bill Gates",
"stateoforigine":"Osun",
"employeephone":"080765432",
"dateofbirth":"12/11/1966"},
{"id":4,
"employeeno":"DAST/003/2003",
"employeename":"Gold Base",
"stateoforigine":"",
"employeephone":"",
"dateofbirth":"12/03/1986"}
]
Thanks for helping me out
The way you are storing your employees into localStorage is correct, but the way you are getting them out is incorrect. You stored your employees by stating:
localStorage.setItem("employees", JSON.stringify(employees));
So, in order to retrieve them, you must use:
var employees = JSON.parse(localStorage.getItem("employees"));
You see, you stored the data as a string with a key of "employees"; therefore, you can only retrieve it by that key. Since all data stored in localStorage is saved as a string, you must use JSON.parse() to convert the data back into an object - an array in this case. Then you can iterate over your employees.
Update:
You should be running this code as soon as the page is rendered (see below). I'm not sure how you're doing that - if you're using an IIFE or jQuery's document.ready() function. I don't think it's necessary to store an empty array into localStorage if none were loaded initially, so, I took your else clause out.
var employees = [];
if (localStorage.getItem('employees') !== null) {
employees = JSON.parse(localStorage.getItem('employees'));
}
Debug this line-by-line when it runs and make positive your employees variable contains data. If it doesn't contain data, well then, there's nothing to edit.
If, however, there is data, then execute your showEmployees() function. Oddly, I'm not seeing in your code where you actually call this. Is it bound to a button or action in your UI? Also, what is that for loop doing after your $('#edit_employee_page') click event function? It's trying to read data from localStorage improperly and it does nothing.
I think if you simply stepped through your code one line at a time using breakpoints and desk-checking your inputs/outputs you'd find out where you're going wrong.
It also appears that there's a disconnect in your code. May be you left out some lines; you define a string editEmployee but out of the blues you store JSON.stringify(employees) whereas employees is not defined in your code:
$('#edit_employee_page').on('click' , function(){
var editEmployee = JSON.stringify({
id: employees.length+1,
//........
});
//Alter the slected data
localStorage.setItem("employees", JSON.stringify(employees));
return true;
});
I had a similar task to do . I did it this way.
I passed the dynamic Id to be passed as an id attribute
id="'+empData.id+'"
and then inside the
$('.edit_button').live('click', function (e) {
alert('I was Cliked!');
var empId=$(this).attr('id');
rest of the code is same.

Categories

Resources