JasonA
JasonA

Reputation: 281

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

route.js

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

index.jade

block content
  - var fluxdata = data
  each item in fluxdata
    span= item
  div#button

client.js

$(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.

Upvotes: 2

Views: 930

Answers (2)

Yves Kipondo
Yves Kipondo

Reputation: 5623

// Jade template
block content
    div(class="content")
        - var fluxdata = data
        each item in fluxdata
            span #{item.id} : #{item.username}
    div
        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>
</div>
<div>
    <button id="add">POST DATA</button>
</div>

// 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){
    event.preventDefault()
    $.post('/refesh', function(data) {
        $(".content").html("")
        for(var user in data) {
            var span = $("<span>")          
            span.text(user.id + ": " + user.username )
            $(".content").append(span)
        }

    });

})

Upvotes: 1

Yves Kipondo
Yves Kipondo

Reputation: 5623

in your  get "/initial" route handler, your are rendering the 


res.render("/page", {data : data })

before the template name you musn't put the / and the template in witch you are trying to use data that at push to the view  is index.jade


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

Upvotes: 0

Related Questions