Append new files - javascript

I have an api running that fetches all the file names in the directory and returns me an array inside an array. Currently, I am running it every second to check if a new file is added and if so... embed it to my div. The issue is that I have to empty my html every time and then re-embed the html. Is there a better way to do this? That way I only embed new filenames rather than all again.
setInterval(function(){
$.ajax({
url : 'getFiles',
success: function (data) {
$("#pics").html("");
console.log(data);
$.each(data, function (k, o) {
$.each(o, function (key, obj) {
$("#pics").append("<a href='#'>" + obj + "</a>");
});
});
}
});
}, 1000);

const images = [];
setInterval(function(){
$.ajax({
url : 'getFiles',
success: function (data) {
const fetchedImages = data.images;
if(images.length !== fetchedImages.length){ //They do not have the same elements
images = fetchedImages;
$("#pics").html("");
const domImages = fetchedImages.map(image => "<a href='#'>" + image + "</a>");
$("#pics").append(domImages.join(''));
}
}
});
}, 1000);
From our discussion i was able to create this solution.
Since you know that you only need a list of images, then you can just get it directly.
Then you can check if the images which are saved locally have the same amount of elements which you got from the server.
If they do not match, then it must mean that the list has been changed (a side-effect could be that someone changed the name of a file, then the length would be the same)
Now we just empty the #pics HTML, create a new array where each element is wrapped in an <a> tag
Lastly join just takes an array and converts it to a string. '' means that there shouldn't be any text between each element, so the string looks like this
"<a href='#'>image1.jpg</a><a href='#'>image2.jpg</a><a href='#'>image3.jpg</a>"

In your case, I will suggest to keep current implementation: clean all and generate the list by new received data. The reason is:
From performance view, clean all and regenerate it will faster than for each compare and check if duplicated => keep, remove old item or insert new item
the order of item can be easily kept as the received data. Won't be confused with the old item list.
The rule I suggest is: if the new list is totally the same, return without change directly. If the list has been changed, clean all and rebuild the list directly.

Related

How to get the index of one specific element within an javascript object

I have been working on this problem for the second day now and I simply can't seem to find the right way to do it.
Problem:
I need to send the index value of a chosen element within a javascript object to an action in PHP. So when the user chooses a certain element, the index value of said element within the object should be send to the mentioned PHP action.
What I have so far is the following:
The button for the jump:
<!-- Button to jumpo tp specific dashboard. The select and and option tags will be generated dynamicly -->
<div style="float:right; margin-right: 10px;">
<select name="idDashboards" id="idDashboards">
<option value="">Jump to Dashboard</option>
</select>
</div>
The Array itself as well as how the HTML elements are created
// The array with the dashboards as I get it from the server
var dashboardArray = <?php echo json_encode(CHtml::listData($dashboards, 'iddashboard', 'title')); ?>;
// Loop through the elements in the dashboardArray and then create option elements to be added to the above create select element.
for (var idDashboard in dashboardArray) {
$('#idDashboards').append($(document.createElement('option')).prop({
value: idDashboard,
text: dashboardArray[idDashboard].charAt(0).toUpperCase() + dashboardArray[idDashboard].slice(1)
}));
};
How the object looks like when I log it.
{2: "Dashboard_Test_1", 3: "Dashboard_Test_2", 4: "Dashboard_Test_3", 6: "Dashboard_Test_4"}
What I have been trying so far:
var dashboardIndex = -1;
var i;
// Loop to get the indexes.
for (i in dashboardArray) {
if (dashboardArray.hasOwnProperty(i)) {
dashboardIndex++
console.log(dashboardIndex+" These are the indexes");
}
}
// Ajax request that sends data to the PHP action
$("#idDashboards").change(function() {
var idDashboard = $(this).val();
console.log("The change happened!");
$.ajax({
url: 'Path/To/PHP/File/And/Action=' + dashboardIndex,
method: 'GET',
success: function(result) {
location.reload();
console.log("So far, so good!");
}
});
});
});
Now, the dashboardIndex and the index of the elements in the object align and are good. But how do I send the index value of only the element that has been chosen by the user?
I am very sorry if this is a duplicate but I could not find anything helpful so far. Every advice/help is appreciated.
Inside your change function, you should be able to use $(this).prop('selectedIndex') to get the index of the item you selected.
I am curious, however, why the API is looking for the index of the dashboard rather than the seemingly unique ID that your API is initially responding with. This may be a more resilient approach.

JS / JSON / JQuery - How to insert Data into Json file lil css

Today i want to create a page that:
inserts things from a json file into divs but also allows you to add new infos to that json.
also i wanted to create a like button with increasing counter and sort function based on the likes.
I dont know anything about php or ajax. its maybe possible to solve without it ?
look here is my code. its not working yet obviously :)
But i hope you get the idea. I basically think iam heading the right direction but just missing some pieces :)
For designing i did put a div which containts 2 divs // 1 for img and 1 for text. i later want to style it with css so that each row there will be 2 filmbox divs and with css flexbox i want wrap it so when windows gets smaller only 1 box each row.
Like i make .filmbox{ width: 40%;} so theres space for only 2 each row and the other things gets wrapped down
LAYOUT OF THE PAGE IMAGE LINK
// Copy Pastaed this ajax from internet to read json data from external file
let readJSON = function (file) {
let json = {}
$.ajax({
'async': false,
'global': false,
'url': file,
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
};
let film = readJSON("film.json")
console.table(film)
// Insert new Data to webpage
for (let i in film){
$(".content:eq("+i+")").append(`<div class="filmbox"><div class ="imgfield">
<img src="${film[i].img}" ></div>"<div class="textfield"> <h1>" + film[i].name + "</h1>
<br>" + film[i].description + "<br>" +
"<button type="button" id="button">LIKE</button>" + "<span id="likeCounter">
</span></div></div>`);
}
// Function to insert new Data into JSON from a from - Update website on Form click
let film = []
function getValues(){
let filmName = $(#fname).value;
let description = $(#fdescription).value;
let img = $(#fimg).value;
let filmData = [{
"name" : ${filmname},
"description" : ${description},
"img" : $${img}
}]
$(#formclick)on("click", ()=>{
**// how to insert to json file ?**
window.location.reload();
})
let counter = 0
// Like Button Function
$(#button).on("click", () =>{
$(#likeCounter).text(counter++)
)};
// SORT FUNCTION to first display films with the most likes
function orderDivs(){
counter.sort()
$(#button).find($counter) // Finds the value of likke button+
**Well and now sort all the Divs according to the like value the users did
input (it dont need to save the like value somewhere just when i like some films
on the page by randomly clicking like it then should sort the divs according to that**
}
$(#sortbutton).on("click", ()=>{
orderDivs()
})
To save the data to a JSON file you'd typically post the data to a server that has file system access (e.g. PHP or Node.js).
If you want to do this client-side, you could look at the FileSystem API, or persist the data in the browser with localStorage.
Regarding the like button / count increment / sorting, it would be better to post this as a separate, more specific question.

cypress: comparing information in 2 sites

I'm starting with cypress and need to compare 2 different environments.
I did a script, but is not working properly.
My goal is:
1 - search for a specific selector value at 2 different environments.
2 - get it's value (in both env) , and then compare it if equal.
The below comparision work, but seems very poor code and it stop in first error assert and can't query reference selector, just text.
Any help is appreciated.
describe('Testing Page', function() {
//urls i need to test
var relative_urls = [
'/products/test1',
'/products/test2',
]
relative_urls.forEach((url) => {
//each url is compared here...
var productInfo = [];
//here goes the environments URL.
var testURL = 'https://www.myurl.com' + url;
var referenceURL = 'http://test.myurl.com' + url;
it('Comparing data from url:' + url, function() {
cy.visit(testURL)
//get data from selector and add it to array
cy.get('body').find(".myselector h1").should(($input) => {
productInfo.push($input.val())
})
cy.get('body').find(".myselector h2").should(($input) => {
productInfo.push($input.val())
})
//requesting second url
cy.request(referenceURL)
.its('body').should( ($input) => {
for (var j=0;j<productInfo.length;j++) {
//expect works, but compares to all site, and i need to search in a specific selector.
//Also, when it gets the first error, it stops and do not search all elements of array
expect($input.includes(productInfo[j]), 'Notice: ' + productInfo[j]).to.be.true
}
}
})
})
})
})
From reading the documentation, cy.request is really making a plain HTTP request without doing any parsing, which means you basically have to parse the body of the response yourself. cy.visit will actually get the DOM elements so you can use Cypress's query syntax to navigate the page.
I think once you have the element values from the first page you should just do cy.visit again and parse the second page.
EDIT: Apparently you can't use cy.visit cross-domain. In that case, maybe you could try parsing the response body into a DOM node like this:
var el = document.createElement( 'html' );
el.innerHTML = request.body // you can get the request object from cy.request;
Then use el.querySelector to navigate the DOM tree using CSS syntax.

Firebase - For item in directory

I have some data in a directory and I want to retrieve the value of a certain object e.g. Get the value of "NVR".
Another task I need to do is have a 'for' loop to go over and get information about different questions from the following data. I would need to get the number e.g. "001" and the items inside of that subdirectory. And it would also need to go through every directory in 'questions' such as NVR or MTH.
For the first one, you can try this:
firebase.database().ref().child("unique").on('value', function(snapshot) {
var datas = snapshot.val();
var nvr=datas.NVR;
)};
For the second one try this:
firebase.database().ref().child("questions").child("NVR").on('value', function(snapshot) {
snapshot.forEach(function(child) {
var keys=child.key;
var datas = child.val();
var correcta=child.val().correctAnswer;
var num=child.val().numberOfAnswers;
//etc
});
});
the first one the snapshot will be at unique, then you will be able to retrieve the child NVR.
In the second one, you iterate inside NVR and retrieve the key using var keys=child.key;
Try something like this for going through every directory in questions and for each one getting all the questions in it :
firebase.database.ref('questions').on('value').then((snapshots) => {
//print whole questions group (nvr, mth, etc)
console.log(snapshots.val())
snapshots.forEach((snapshot) => {
//print each question in question group
console.log(snapshot.val())
})
}
Both Peter's and Egor's answers load all data under unique. Since you know the key of the item whose value you want to retrieve, you can load this more efficiently with:
firebase.database().ref("unique/NVR").on('value', function(snapshot) {
var nvr=snapshot.val();
)};

parse is still alive, but how to query by 'index'

I found that Parse is now supported by the Buddy platform, but all the forum/help files from the old Parse website are gone...
What i would like to do is query for one row in a table by row number/index.
I now do this, but it seems inefficient to me to get all data and then select the row (although it works fine):
var thisRow = Parse.Object.extend(GlobTable);
var query= new Parse.Query(thisRow);
query.descending('updatedAt');
query.find({
success: function(results) {
var object = results[RowNumberThatINeed];
//etc using object
#Ran, thanks! Somehow it doesn't work, Parse will store '1' for every row: 1,1,1,1. But it saves all other data ok.
var Object = Parse.Object.extend(LocTable);
var obj = new Object();
obj.set("User", LocUser);
obj.set("Happened", d);
obj.set("Happy", b);
obj.set("Learned",a);
obj.set("ConnectedTo",c);
obj.increment("rowIndex");
obj.save({
success: function(obj) {
updateDatabase();
alert("Your data is saved");
},
error: function(obj, err) {
alert("Your data was not saved. Sorry..." + err);
}
});
you solution will work but you will experience a lot performance issues when your table will growth.
What i suggest to you is the following solution:
Add another field to your GlobTable of type integer. This field will be incremental field and will store your row index (let's call this field rowIndex)
Each time you save a new object to this table make sure you increment this field by using the following command:
object.increment("rowIndex");
Now your query should look like the following:
var thisRow = Parse.Object.extend(GlobTable);
var query= new Parse.Query(thisRow);
query.equalTo("rowIndex",RowNumberThatINeed);
query.first().then(function(result){
// do something with the result
},function(error){
// error handling
});
If you want event better performance you can create index (in MongoDb) on your rowIndex.
In my code snippets i use Promises according to the best practices.
I use first and not find because there will always be one object for this index

Categories

Resources