How to turn a jade page into html? - html

I have a jade file called syntax.jade. What I need is a way to convert syntax.jade, along with the information I would normally pass it with a res.render statement, into a html document in node so that I can manipulate it in that form. Basically what I want is this:
when I use
res.render('syntax', {comment: comment}, function(err, html))
html contains the html of the page as a string. I need another way to get that code that doesn't require me to render the page in the browser.
The reason I want to do this is so that I can include the resulting HTML code in another res.render statement in order to provide formatting instead of doing all the formatting in the front end.

You can just require Jade as a Node module and use the renderFile() method.
var jade = require('jade');
jade.renderFile('syntax.jade', {comment: comment}), function (err, html) {
if (err) throw err;
// rendered string is in html variable
});
If there's no error, then you have a rendered HTML string as a result. If you want to do this synchronously, then just don't specify a callback:
var html = jade.renderFile('filename.jade', {comment: comment});

That is already what you have. From the express docs on res.render
When a callback is provided both the possible error and rendered
string are passed, and no automated response is performed.
So res.render(viewName, locals) does BOTH rendering of the HTML and sending that HTML as the HTTP response body. However res.render(viewName, locals, callback) with 3 arguments just renders the HTML and passes it to the callback without sending any HTTP response. Thus you can do whatever is needed with the HTML and then send a response later.
There is also app.render which is another general utility to render stuff without having anything to do with a particular http request/response.

Related

How can I validate on the client if I use MVC validation but posting a JSON object?

I'm developing a ASP.NET Core web application where I'm using DataAnnotations to decorate my view model with validation attributes. When I open a detail page with my inputs, I see that Core added the HTML5 validation attributes to the rendered HTML (i.e. data-val="true").
However, I wrote custom client-side code when the user clicks on the Save button like this:
$(document).on("click", "#SaveAsset", function (event) {
event.preventDefault();
Asset.Save();
});
I also have a Save function defined like this:
window.Asset.Save = function () {
var postData = {
'Id': $("#Id").val(),
'SerialNumber': $("#SerialNumber").val(),
'PartNumber': $("#PartNumber").val(),
'assetTypeId': $("#AssetTypeId").val()
};
$.post('/Asset/SaveAsset', postData);
}
I need to validate on the client side first before calling $.post but I'm confused about how to do it. Microsoft shows that the unobtrusive javascript works automatically when you use it with forms. But I'm not using the HTML form element to submit my page. So how can I trigger the HTML5 validation attributes?
I added the links to jquery.validate.js and jquery.validate.unobtrusive.js. Right now, if I click the Save button the data is sent to the server and the controller checks the ModelState. But it shouldn't even be sending anything to the server. The client should stop the validation.
Should I even stop doing it this way? For example, creating my postData JSON object by getting the val() of each input.
Should I use the form element? I stopped using it because my page has hundreds of inputs so I was worried I would have problems. This way, I have control over each input.
Use a javascript solution like jQuery Validation Plugin to validate data before sending to the server. Otherwise, send the data to the server, and return a the errors with a bad request if validation fails.
Eg.
Return BadRequest(string[]{"Name is required", "Id must me a number"});
then capture the errors and shoe to the user

Node.js - where to find incoming parameter in the HTML/document

I have the following function in my Node.js code that renders an HTML page and passes it an javascript object called htmlParamObj
exports.getPage = function (req, res, next) {
var htmlParamObj= {
propertyOne: 'yada',
propertyTwo: 'yada yada'
};
res.render('myPage.html',htmlParamObj);
};
I can access the incoming parameter (htmlParamObj) with EJS like so: <% propertyOne %>, but I don't know how to access htmlParamObj via the document itself. I believe htmlParamOb' will be attached to the document of the html - but what field in the document can I find it in? Is it in the head, the body, the childNodes? Where?
The object passed is only used while rendering the HTML, and will not be passed to the browser in any way.
If you need that data inside the page you need to put it there.
The solution I've used when I need to pass complex data to a client side script is to place a script tag near the top of my HTML EJS file and populate that with my data. For example I might add the following to my template:
<script>
window.MY_DATA = <%= JSON.stringify(myData) %>
</script>
Notice that since JSON is a subset of javascript, I can use JSON.stringify to serialize my data into a form suitable for placement inside a script tag, and assign it to whatever variable I want.
The limitation here is that you can't send any data that can't be serialized with JSON.stringify. Not a heavy burden, but could trip you up if you want to send a function or other object.
The solution I found is to define a global attribute in my HTML like so:
<a name="team" value="<%=team._id%>"></a>
then I can access it in any script like so:
<script>
var team = document.getElementsByName('team');
</script>
This will return the correct object.
However, I don't think this is the best answer, especially given that any globally defined variable is usually a bad idea. I am hoping another answer is given to this question.

Mootools Request to change javascript code?

So I am planning on dynamically changing a page's content by fetching it from another page.
To do so, I used Mootools' Request class:
var tabContent = new Request({
url: 'foo/bar/baz.php',
onSuccess: function(data) {
$('tab_container').innerHTML = data;
}
}).send();
In any case, the HTML is fetched fine, and returns without a hitch. However, I'd like to add some events to THOSE fetched elements (Fx.slide, to be precise), and that requires some js to be included in the requested file.
Upon inspection of the returned data, the javascript is intact. However, it does not show up in the final product. That is, somewhere in between having received the data, and rendering the data (via the innerHTML bit) it seems as though the javascript has been excised out for some reason.
Hm.
add evalScripts: true to the Request options, then include the script in a simple <script></script> block at the bottom of the response.

Updating DOM element with AJAX return data fails in jQuery

I'm doing a simple AJAX post request in jQuery to another page on my site to get an XML document response. I'm putting the response into a pre element with syntax highlighting enabled. The response comes through fine (I can alert it), but it isn't being added to thepre element when I attempt to assign it in the handlResponse function with jQuery.
<head>
<script>
...
function handleResponse(response, status)
{
$("#output").text(response);
}
$.post(url, data, handleResponse, "text");
...
</script>
</head>
...
<pre id="output">
</pre>
Just to be clear, the javascript code above is in jQuery's document ready function. Any help would definitely be appreciated.
Three things:
Is the response being passed correctly? Check by doing alert of response from within the function itself.
Is the function being called correctly? Check by having it do an alert unrelated to the response variable (alert("Yo!")).
Is the text being inserted correctly? I can tell it should work, but for sake of full debug, add a ternary like this:
var preText = (response != "") ? response : "The problem is with the reponse";
Try using html instead of text...
$("#output").html(response);
EDIT: If you think escaping is the issue, the following should escape it well enough to display...
response = response.replace(/</g, "<");
$("#output").html(response);
Apparently this is a bad question. I'm using the javascript lib SyntaxHighlighter and had preloaded the syntax highlighting on the pre tag I was attempting to use. My solution was to remove the tag and dynamically create it when the ajax response comes in. This worked well other than the fact that I'm trying to determine how to load the highlighting on a dynamically appended dom element.
Thanks for the responses.

dom question: getting the full sourcode from a html document

i'm trying things out with a html document's dom (under visualbasic6) and i was wondering:
how can i get the full html sourcecode including all headers?
is there something like document.all.value?
thanks
If all you have is a DOM, there is no way to retrieve the original source, much less the response headers. It's gone. The DOM is what was generated from the source, which was thrown away thereafter.
If you must have the original source and headers, you will have to fetch it again from the server, using the location object to get the URL. For example from inside a web page script:
var req= 'XMLHttpRequest' in window? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHttpRequest');
req.onreadystatechange= function() {
if (this.readyState===4) {
alert('Headers: '+this.getAllResponseHeaders());
alert('Body: '+this.responseText);
}
};
req.open('get', location.href);
req.send(null);
Clearly this will only work for a page generated from a GET request.