A
A
Asikov Artur2018-03-06 22:29:27
JavaScript
Asikov Artur, 2018-03-06 22:29:27

How to optimize multiple post queries to the database on one page?

When the button is clicked, a POST request is sent to the server and the list is loaded. The rasdel variable is generated based on the id of the button that the user clicked on (the first time I write such a script,
then I take the id - is that correct? then I process it on the server)

var rasdel = '';					//   разделы

    function chart_ajax_add(rasdel ){
      $.ajax({  //на раздела выдаем список
      type: "POST",
      url: "/mar",
      data: rasdel ,
      contentType: "text/plain",
      success:function (text) {
        for(i = 0; i < text.length; i++){
          $('.razdel').find('ul').append('<li attr="'+   (i+1) + '">' + (i+1) + '. ' + text[i]['name'] +'</li>');
        }}				
    }).fail(function () {
      console.log('fail');
    });
  };

Here is what happens on the server:
app.post('/mar', (req, res) => {      
    var requ = JSON.parse(req.body);
    const db = mysql.createConnection({
        host:  'localhost',
        user: 'root',
        password: '',
        database: requ.rasdel 
        });
    let sql = 'SELECT * FROM subcharter WHERE `rasdel _id` =' + requ.rasdel ;
    db.query(sql, (err, result) =>{
        if (err) throw err;
        let mas = JSON.stringify(result);
        // console.log(mas);   
        res.type('application/json');  
        res.send(mas);      
        });
    db.end();    
});

In the future, when clicking on the elements in the newly created list, another similar list is created (already from the subsections of the selected section). How to implement it? It turns out that it is necessary to transfer two variables to the server: 1 - database, 2 - selected section? (For each section, the database has its own)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RidgeA, 2018-03-06
@RidgeA

1. No need to create a connection to the database every time. You need to do this once when starting the application. Or a connection pool.
2. It is not necessary to make requests to the database like this - it is necessary through prepared requests.
3. As part of a connection to one server, you can make requests to different databases, you only need to explicitly specify them in the request
4. Requests can be cached

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question