JasonA JasonA - 1 year ago 97
Ajax Question

Ajax result change Jade assignment variable

Looking to change a Jade assigned variable with the results of an ajax post so that the page's Jade loop utilizes the new data (updating only the parts of the dom that relate to the loop and not rendering the page over).


router.post('/initial', function(req, res) {
res.render('/page', {data: data})
router.post('/refresh', function(req, res) {


block content
- var fluxdata = data
each item in fluxdata
span= item


$(document).on('click', '#button', function() {
$.post('/refresh', function(newdata) {
var fluxdata = newdata

I tried out partials, but wasn't sure I was on the right track. Looked around the internet and stackoverflow for a while and can't find a similar question about Jade assignments.

Answer Source
// Jade template
block content
        - var fluxdata = data
        each item in fluxdata
            span #{item.id} : #{item.username}
        button(id="add") POST Data

after your template is rendered your html will look like this

// HTML rendered
<div class="content">
    <span>1 : Yves</span>
    <span>2 : Jason</span>
    <button id="add">POST DATA</button>

// backend code

var users = [
        username: "Yves", 
        id: 1
        username: "Jason", 
        id: 2

router.get("/initial", function(request, responser) {
    response.render("index", { data: users})

router.post("/refresh", function(request, responser) {
    users.push({username: "Alex",id: 1})

    response.json({ data: users})

// Your jquery code

$("#button").on('click', function(event){
    $.post('/refesh', function(data) {
        for(var user in data) {
            var span = $("<span>")          
            span.text(user.id + ": " + user.username )


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download