0

Just learning nodejs. I want to change content inside my html without completely rendering in the page when I post.

Here is my current code.

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs')
var arr = [];

app.get('/', function (req, res) {
  res.render('index', {messages: null, error: null});
})

app.post('/user', function (req, res) {
        var input = req.body.userInput;
        var output = "";
        arr.push(input);
        for(var i = 0; i < arr.length;i++){
            (function(){
                console.log(arr[i]);
                output +=arr[i] + "</br>";
            })(i);
      }
      res.render('index', {messages: output, error: null});  
})


app.listen(port, function () {
  console.log('Example app listening on port 3000!')
})

Thanks. Any advice is really appreciated.

4
  • Couldn't understand your question? Do you mean lazy loading ? Commented Jul 10, 2018 at 9:25
  • Sorry, so I want to dynamically change to messages value without reloading the whole page - as it's doing currently. Commented Jul 10, 2018 at 9:28
  • @Buupu You will need to use JavaScript on the frontend to achieve that. Commented Jul 10, 2018 at 9:29
  • Instead of rendering a page using res.render(), send just the data in json like res.json({messages: output, error: null}). Make it a REST API. Then use the json in the front-end to update the page without reloading the full page. Commented Jul 10, 2018 at 9:30

2 Answers 2

2

Send just the data:

app.post('/user', function (req, res) {
        var input = req.body.userInput;
        var output = "";
        arr.push(input);
        for(var i = 0; i < arr.length;i++){
            (function(){
                console.log(arr[i]);
                output +=arr[i] + "</br>";
            })(i);
      }
      res.status(200).json({messages: output, error: null});//Not rendering new page, just sending data
})

In the front-end, handle as follows if you're using plain JS:

function handlePostUser() { // Invoke this on form-submit or wherever applicable
            var xhr = new XMLHttpRequest();
            xhr.open("POST", 'your link/user', true);
            xhr.setRequestHeader("Content-Type", "application/json");
            var payload = { data to post };
            xhr.send(payload);
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4 && !xhr.status) {
                    // Handle error
                    console.log("FAILED");
                } else if (xhr.readyState === 4 && xhr.status === 200) {
                    console.log("SUCCESS");
                    //your logic to update the page. No reloading will happen
                }
            }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! Think I understand better.
Hi again, I've tried to make the changes, but it seems when I submit the page just changes into the json text. Any idea why this might be happening?
How are you invoking the API? If you're giving your URL in action attribute of form element, then it'll redirect. Instead use event handlers to invoke XHR or AJAX from javascript. Which framework/library are you using in the front-end?
2

You can't do that with server-side code.

You could have to write client-side JavaScript to manipulate the DOM of the existing page.

That JS could use Ajax to get fresh data from the server. You could either write client-side code to extract the portion you care about, or create a different server-side endpoint that only returns the bit of data you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.