Use of the Xmlhttprequest object to perform an asynchronous HTTP request to update data on the server without a complete web page update

Asked

Viewed 61 times

0

I have basic knowledge and am using in the application: html/css, javascript, Nodejs, and for the database - Mongodb - Mongoose.

My application is very simple, as you can see in the image below, serves to publish texts containing title and content. I need that as soon as a new content is posted it appears right below, in the post list, but without the complete update of the page. I accept references or videos explaining how to do.

inserir a descrição da imagem aqui

Below is the javascript code I have so far.

// Publicar conteúdos
  app.get('/home', function(req, res, next){
    Postagem.find().sort({date:'desc'}).then(function (posts) {
      res.render('home', {posts: posts})//FORMULARIO HTML
    })
  })

// Recebendo os posts

  app.post('/home/postagens', function(req, res, next){
  var errosPostagem = []
  // Validação da postagem

  if(!req.body.titulo || typeof req.body.titulo == undefined || req.body.titulo == null ){
      errosPostagem.push({texto: "Título inválido "})
  }
  if(!req.body.conteudo || typeof req.body.conteudo == undefined || req.body.conteudo == null ){
      errosPostagem.push({texto: "Conteudo invalido "})
  }
      if(errosPostagem.length > 0){
        res.send('Título ou conteúdo inválido')
      }else {
            const novaPostagem = {
            titulo: req.body.titulo,
            conteudo: req.body.conteudo,
            date: req.body.date
            }
            new Postagem(novaPostagem).save().then(function(){
            }).catch(function (erro){
              res.send("Houve um erro: "+error)
            })
      }
  })
  • You can use javascript to show the data directly to the user, without reloading the page. Once the post is done you create a list with javascript and concatenate the form data. For example: https://answall.com/a/224117/21077

  • You should show your application better the problem may be in the way you are consuming the API.

  • Instead of using the old API XMLHttpRequest, you can use more modern means, such as the fetch. To learn more, read here.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.