dopamane
dopamane

Reputation: 1315

How to re-render a view using expressJS with new data?

I am creating a NodeJS inventory system using ExpressJS and MongooseJS (for accessing MongoDB). I am trying to implement a search bar. I want the user to type into the search bar, press enter, then see an updated table that has all matching items in the database.

Currently, when the user presses enter after typing in the search bar, jQuery sends a POST to my Express server with the text in the search bar. Using mongooseJS, I find all matches. The issue is that when I render the view again, the page does not update and show the user the new information that matched the search.

Here is my router code:

var express = require('express');
var router = express.Router();
var InventoryObject = require('mongoose').model('InventoryObject');
var searchdata = '';

/* GET home page. */
router.get('/', function(req, res) {
    var regSearch = new RegExp('.*'+searchdata+'.*', 'i');

    InventoryObject.find({productId: {$regex: regSearch}}).sort('-_id').exec(function (err, data) {    

        res.render('index', {'inventoryObjects' : data});
        searchdata = '';

  });
});

router.post('/', function(req, res) {
    searchdata = req.body.searchbar;

});

Everything seems to work except re-rendering the page. What am I doing wrong/missing?

Upvotes: 1

Views: 10380

Answers (2)

Brad Wells
Brad Wells

Reputation: 429

Are you positive that you want to do this?

success: function (data) {
    location.reload();
}

Why not fetch the updated inventory data with that call and use it in the success function to update the page?

Upvotes: 1

dopamane
dopamane

Reputation: 1315

I noticed that I had forgotten res.redirect('/') shortly after posting this question. However, the solution I found that works still does not use res.redirect('/'). Instead, I used res.end() at the end of the post route. I then went back to the client side jQuery script that fired off the AJAX POST and used the success tag to initiate a location.reload().

Client Side POST

$.ajax({
    url: '/',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({
        type:'search',
        searchbar: ($('#searchbar').val())
    }),
    success: function (data) {
        location.reload();
    }
});

Server Side, added res.end()

var express = require('express');
var router = express.Router();
var InventoryObject = require('mongoose').model('InventoryObject');
var searchdata = '';

/* GET home page. */
router.get('/', function(req, res) {
    var regSearch = new RegExp('.*'+searchdata+'.*', 'i');

    InventoryObject.find({productId: {$regex: regSearch}}).sort('-_id').exec(function (err, data) {    

        res.render('index', {'inventoryObjects' : data});
        searchdata = '';

    });
});

router.post('/', function(req, res) {
    searchdata = req.body.searchbar;
    res.end();
});

Upvotes: 1

Related Questions