I'm doing few exercise using Node.js, Express.js and MongoDB.
At the moment I've a problem trying to push new contents created with jQuery.Ajax.
I have a list of posts in homepage with Jade: (now I will write something simple, but mine is with much more html elements...)
ul
each post in posts
li
h1 title
p post
With a normal form and postback it is ok because the page is refreshed.
Bue using jQuery and Ajax on success I should append the new post without refresh the page... There is a solution with Jade to do that without writing the entire html in jQuery?
Can you suggest a better way to do this?
Jade is compiled as HTML, so no, there is no way to use jade templates in your jQuery. What you can do, however, is write snippets in jade, compile them, and save them to your webserver (such as post_template.html), then load file with jquery, create a jQuery element from the loaded text, and then change properties and contents of the elements within the new element. Then you append the element to the page.
This approach would allow you to avoid writing html in your jQuery.
//Wrap this in the code that gets updates
$.get( "templates/post.html", function( data ) {
var el = $(data);
//If you want to change specific properties
var title = el.children('h1');
title.text('My new text');
el.appendTo('ul#postList');
});
If you wanted to do this on click, for example, just wrap that function in a click handler for some element on the page that you want to use to trigger new item.