D
D
dmitriu2562020-04-23 19:38:35
MySQL
dmitriu256, 2020-04-23 19:38:35

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);
    });
});


Client side
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);
    }


Result
5ea1c1a6adaff773892997.png

Code clicking on the button All News

Server side (getting the number of records in the table)
app.get('/news', (req,res) => {
    connection.query(`SELECT COUNT(*) FROM news `, function(error, rows) {
        if(error) throw new  Error(error);
        res.json(rows);
    });
});


Button processing client side

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 на получения количество записей в таблице
        });

    });


Result
5ea1c3fb71cb5976120197.png
Now the last entry is displayed continuously when the button is pressed. How to properly set the sampling range?
How to correctly implement this type of task - displaying the rest of the articles on click?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kerberosso, 2020-04-30
@Kerberosso

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.

Y
Yuri Kostin, 2020-05-01
@yurakostin

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:

  • Make your code better. For example, use a framework, or a couple of libraries, or at least fetch, so as not to write so much fierce code. Break your code into parts, abstract it. Move away from imperativeism towards OOP, or FP
  • Think about how you can do better. There is no single correct solution to problems. Special in js =). Everything that you have done another, more experienced developer will do a little differently, but that's all. Ideally, you should go this route. For example, as written above, reduce the number of requests. If you have a blackboard at home, stand next to it (or use a good old notebook), take a chalk or marker, and draw the data you get. Can they be combined somehow? Is it possible to approach the solution in a different way? How to make it more optimal by reducing the number of requests? How to unify the solution? You will probably go a long way, but your expertise will increase.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question