Steve Addington Steve Addington - 3 years ago 205
jQuery Question

How can I get live feedback from my backend?

I am using a POST jQuery request on the client side. This post request starts a function. When the function is finished (putting some stuff in a mongodb) I want that the client updates the data on the website without the user needing to refresh.

Can you guys give me any ideas how to do that? I just don't even know how to approach it or how to Google it :/

My stack is: Nodejs, Express, EJS, MongoDB and jQuery

Answer Source
  • You need to construct an AJAX request, which you already have
  • Then inside your backend when your mentioned function finishes processing the clients request and writing it to the database you need to send it back to the client using res.json

    router.post('/whatever_endpoint_you_are_using', function(req, res, next) {
      // code for processing the response & writing stuff to the database
      // then send the data back to the client
        res.json({"data": your_data});   
    });
    
  • Then you can access this data on the client, inside of the success callback of your AJAX request

    success: function(response){
       console.log(response.data) // your_data
    }
    
  • Lastly, you can use JS or jQuery to add this data to the DOM (you mentioned you're using jQuery so here's a jQuery example)

    $('#data_container').append('<p>'+response.data+'</p>')
    
    // or something similar I don't know how your page is structured
    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download