JasonA JasonA - 25 days ago 21
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).

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.

Answer
// 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)
        }

    });

})
Comments