Luke
Luke

Reputation: 71

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.

Upvotes: 7

Views: 6717

Answers (3)

laconbass
laconbass

Reputation: 17824

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
  });
});

Upvotes: 1

Jack
Jack

Reputation: 15872

You could use something like the following, or if you want to use an AJAX call use jQuery ajax as long as there is a response

Client

script(type="text/javascript")
  $(document).ready(function(){
    //...AJAX here....
    var newValue = #{value} + 10;
  });

Server

app.get('/ajax', function(req, res){
 //This is where your code and response go
});

Upvotes: 0

Zikes
Zikes

Reputation: 5886

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).

Upvotes: 4

Related Questions