Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update A Jade Template form an ajax post?

I have set up a basic node.js web-app using express with the default view engine jade.

When the User first loads the page the following occurs

app.get('/', function(req, res){
    res.render('index', {
        title: 'Test',
        mode: "user"
    });
});

What i cannot work out is how to then change the parameter I initially passed into the jade template from a ajax call.

app.post('/', function(req, res){
    console.log(req.body.list);
    res.redirect('back');
    // I imagine the code needs to go here and look somewhat like the following
    // 
    // res.?update-view({
    //  mode: "admin"
    // });
});

If anyone has had experience with this working your input would be appreciated.

like image 775
Luke Avatar asked Mar 10 '11 20:03

Luke


2 Answers

I'm not exactly sure what you're after, but if it's updating the page with the results of an AJAX call (which does not refresh or otherwise reload the page) then you'll have to use client-side JavaScript. jQuery's load() or post() should be able to handle that.

Alternatively, if you are not using AJAX but instead performing a normal form submit, you have a couple of options. One, you can keep your redirect in and use Express/Connect's Sessions system to determine what is used for the get request, or two you can replace the redirect with another res.render of the index.jade page and include the variable you want to change.

It should be understood that after either of these takes place, node.js relinquishes control of the web page to the browser, unless you specifically set up architecture for communication. There are currently no controls in node.js to force updates or page changes down to the client. Except via socket connections or unless otherwise polled by the client itself (such as in the first example involving jQuery).

like image 76
Zikes Avatar answered Nov 02 '22 00:11

Zikes


Assuming you want to display the same page, with other "mode"

// set the page title for all requests
app.locals({ title: 'Test' });

// GET request
app.get('/', function(req, res){
  res.render('index', {
    // displays the default "user" mode
    mode: 'user'
  });
});

// when POST is submited
app.post('/', function(req, res){
  // this is the param given by the user
  console.log(req.body.list);

  // now render the same page
  res.render('index', {
    // with mode set to the the given parameter
    mode: req.body.list
  });
});
like image 33
laconbass Avatar answered Nov 01 '22 23:11

laconbass