Answer the question
In order to leave comments, you need to log in
How to load news from database on button click?
How to load news from MySql database on button click?
I use a bunch of JS + NodeJs (Express) + MySql
My implementation
1) Initially, I load 3 news from the database (AJAX request) with LIMIT on the page
2) Then, when the button is pressed, two queries are executed
- we determine the number of records in the table (I use COUNT in mysql )
- knowing initial LIMIT (from, to) I redefine these values.
How do I want to control the number of displayed articles (through the LIMIT task)
1) Initially, when loading three news LIMIT 0(from), 3(lim)
2) When you click on the button, change the limit in the following order LIMIT 3 (where from = lim from point 1 ), 1 (show only one entry)
3) The next time you press the LIMIT button 4.1
4) Then LIMIT 5,1 and so on, until from is equal to COUNT from the previous request
5) Hide the button. (there are no more articles in the database).
Code point 1 (loading from the database)
Server part
app.get('/news/:from/:lim', (req,res) => {
connection.query(`SELECT * FROM news LIMIT ${req.params.from}, ${req.params.lim}`, function(error, rows) {
if(error) throw new Error(error);
res.json(rows);
});
});
let newsSection = document.querySelector('.news');
let newsContainer = newsSection.querySelector('.container');
//Создаем кнопку Все новости
let newsBtn = document.createElement('button');
newsBtn.classList.add('button', 'button-o', 'news-button');
newsBtn.innerText = 'Все новости';
let lim = 3;
let from = 0;
//Ряд
let newsRow = document.createElement('div');
newsRow.classList.add('row');
//AJAX запрос на получения всех новостей из БД
let newsXhr = new XMLHttpRequest();
newsXhr.open('GET', `http://localhost:3010/news/${from}/${lim}`);
newsXhr.setRequestHeader('Content-type', 'application/json; charset = utf-8');
newsXhr.send();
newsXhr.addEventListener('readystatechange', function () {
if (newsXhr.readyState < 4) {
} else if (newsXhr.readyState === 4 && newsXhr.status === 200) {
let data = JSON.parse(newsXhr.response);
console.log(data);
for(let i = 0; i < data.length; i++) {
newsRow.append(createNews(data[i]));
}
} else {
console.log('Ошибка');
}
});
if(newsSection.contains(newsContainer)) {
//Вставка кнопки и ряда с новостями
newsContainer.append(newsBtn);
newsBtn.before(newsRow);
}else{
console.log(false);
}
app.get('/news', (req,res) => {
connection.query(`SELECT COUNT(*) FROM news `, function(error, rows) {
if(error) throw new Error(error);
res.json(rows);
});
});
newsBtn.addEventListener('click', function () {
//1 Запрос Количество записей в таблице Новости
let xhr = new XMLHttpRequest();
xhr.open('GET', `http://localhost:3010/news`);
xhr.setRequestHeader('Content-type', 'application/json; charset = utf-8');
xhr.send();
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState < 4) {
} else if (xhr.readyState === 4 && xhr.status === 200) {
let tmp = JSON.parse(xhr.response);
let newsLength;
for(let key in tmp[0]) {
newsLength = tmp[0][key];
}
//console.log(newsLength);
//2 Запрос Выборка новостей из БД
//Ограничения
//КАК ПРАВИЛЬНО ЗАДАТЬ УСЛОВИЯ ДЛЯ ЛИМИТОВ
******************************************
from = ++lim;
console.log(from);
if (from <= newsLength) {
lim = 1;
from += lim;
console.log(from);
//console.log(lim);
*************************************************************************************
let newsXhr = new XMLHttpRequest();
newsXhr.open('GET', `http://localhost:3010/news/${from}/${lim}`);
newsXhr.setRequestHeader('Content-type', 'application/json; charset = utf-8');
newsXhr.send();
newsXhr.addEventListener('readystatechange', function () {
if (newsXhr.readyState < 4) {
} else if (newsXhr.readyState === 4 && newsXhr.status === 200) {
let data = JSON.parse(newsXhr.response);
//console.log(data);
for (let i = 0; i < data.length; i++) {
newsRow.append(createNews(data[i]));
}
} else {
console.log('Ошибка');
}
});
//Конец запроса 2 на выборку новостей
}else{
console.log(from);
//Скрываем кнопку 'Все Новости'
newsBtn.hidden = true;
}
} else {
console.log('Ошибка');
}
//Конец запроса 1 на получения количество записей в таблице
});
});
Answer the question
In order to leave comments, you need to log in
Why do you need to make an additional back request to get the total number of news and keep information about from and lim on the client? Let the backing at each news return return the total number of news, the remaining number of news and the current serial number of the news. And you, based on this information, will build the next request and update the UI. Doing all this at once on the back and giving it to the client is easier than sending extra requests over the network.
It's great that you set yourself and solve problems. As I understand it, your solution works and it's great.
Now set two goals for yourself:
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question