How to pass Thymeleaf object from base page to ajax generated page? - javascript

I have a registration process that has substeps and I have individual HTML pages for these substeps for easier management. Now I have a "base page" which is the container. The following div is where I load the subpages.
<div id="substeps" th:object="${stepFourForm}">
</div>
and I load the substeps using ajax
$('#substeps').html(data);
How can the loaded substep page retrieve the stepFourForm object on the base page?

You should remove div content before loading substep page. And you can do it using thymeleaf fragments.
$.ajax({
type: "GET",
url: "/example-url",
success: function (data) {
$('#substeps').html('');
$('#substeps').html(data);
}
});
Controller code:
#RequestMapping("/example-url")
public ModelAndView example() {
ModelAndView view = new ModelAndView("substep1 :: content");
return view;
}
Example fragment html name substep1:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:dt="http://www.thymeleaf.org/dandelion/datatables">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<div th:fragment="content">
--some content
</div>
</body>
</html>

Related

Jquery TypeError when replacing page content

I'm trying to achieve the following:
A simple Java Spring application, after receiving a GET request, sends me an HTML page with a form. When the button is pressed in this form, there is a POST request with an XML content sent back to the Spring app, which, in turn, responds with an HTML page. I would like to be able to display this response as a proper page in a browser, including all the scripts being downloaded and fully functional.
The form HTML page:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<meta charset="UTF-8" />
<title>Request Report Form</title>
</head>
<body>
<form method="post" action="">
<script>
function sendXml()
{
event.preventDefault();
const request = '<?xml version="1.0" encoding="UTF-8"?>\n' +
<!-- skip -->
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
data: request,
contentType: 'application/xml;'
}).done(function (data) {
$("html").html(data);
}).fail(function (data) {
$("html").html(data.responseText);
});
}
</script>
</form>
</body>
</html>
The $("html").html(data); part above is supposed to replace the current page's content with the content received from the server, as far as I understand. But the page is not being displayed. There is an error message in the browser's console: "TypeError: n.head is null", it seems to have to do with JQuery, see the image link.
My questions are, why does JQuery kicks in and what is it trying to do? And how do I fix this error?
I don't know much about frontend side of development, so please go easy on me ;-)
Edit
Just realised that my first question is moot, I am trying to display the response page using JQuery, so obviously, it kicks in at that point. But the call fails for some reason.
The content of the response from the server that I'd like to see rendered by the browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Progress Report</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body data-user="eyJjaGFydCI6eyJyZW5kZXJUbyI6IlByb2dyZXNzIiwidHlwZSI6ImNvbHVtbiJ9LCJzZXJpZXMiOlt7Im5hbWUiOiJQcm9ncmVzcyIsImRhdGEiOlsxLDEsMCwwLDAsMCwwLDAsMCwwXX1dLCJ0aXRsZSI6eyJ0ZXh0IjoiUHJvZ3Jlc3MifSwieEF4aXMiOlt7InR5cGUiOiJsaW5lYXIiLCJjYXRlZ29yaWVzIjpbIlJlZ2lzdGVyZWQ8YnI+KDQuNi4xMykiLCJTZXNzaW9uIDE8YnI+KDEyLjcuMTUpIiwiU2Vzc2lvbiAyIiwiU2Vzc2lvbiAzIiwiU2Vzc2lvbiA0IiwiU2Vzc2lvbiA1IiwiU2Vzc2lvbiA2IiwiU2Vzc2lvbiA3IiwiU2Vzc2lvbiA4IiwiRmluaXNoZWQiXX1dLCJ5QXhpcyI6W3sidGl0bGUiOnsidGV4dCI6IlNlc3Npb24gU3RhcnRlZCJ9LCJtaW4iOjB9XX0=">
<div id="wrap">
<div class="container">
<div class="report"></div>
</div>
</div>
<script>
window.onload = function (event) {
event.preventDefault();
$(".report").append("<div class='chart'><div id='Progress'><img src='staticMedia/img/loader.gif' /></div></div>");
userData = $("body").data("user"); // get user report data
var chart = new Highcharts.Chart(JSON.parse(atob(userData)));
// destroys legend if only 1 series
if (chart.series.length < 2) {
chart.legend.destroy();
}
}
</script>
</body>
</html>
Found an answer here: stackoverflow.com/a/11984907/3182810. Replacing
$("html").html(data);
in the form with
document.open();
document.write(data);
document.close();
does the trick.

Importing HTML Template within template

Is there any example of using a HTML template element within another HTML template element?
okay, here is a simple example:
This is my main file index.html that in it i'm importing the header.html and cloning the template in it and appending it to my master div:
<!DOCTYPE html PUBLIC "_//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xhtml="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us">
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type">
<link id="imported-header" rel="import" href="static/components/header.html">
</head>
<body>
<div class="master"></div>
</body>
<script>
var headerImp = document.querySelector('#import-header').import;
var headerTemp = headerImp.querySelector(".header");
var header_01= headerTemp .content.cloneNode(true);
document.querySelector(".master").appendChild(header_01);
</script>
</html>
Then in my header.html I'm importing another HTML and adding it to the template (I got the feeling that calling document is wrong for template in another template, but I could be wrong.):
<link id="import-field" rel="import" href="static/components/credit_field.html">
<template class="header">
<div class="credit"> </div>
</template>
<script>
var creditImp = document.querySelector('#import-field').import;
var creditTemp = creditImp.querySelector(".field");
var credit_01 = creditTemp.content.cloneNode(true);
credit_01.querySelector(".row").innerHTML = "User1";
var credit_02 = creditTemp.content.cloneNode(true);
credit_02.querySelector(".row").innerHTML = "User2";
document.querySelector(".credit").appendChild(credit_01);
document.querySelector(".credit").appendChild(credit_02);
</script>
This is credit_field.html just a template that hold the field:
<template class="field">
<div class="row"></div>
</template>
It is clearly loading it without any error, but it is giving me import error!
just for the record if I import both of them to my index.html and append them in there, it will work just fine, but I'm looking for a way to have a template within another template.
Again to clarify my question, I'm wondering how can I add an HTML template element within another HTML template element?
Note: I have seen people using Django template, but I want to sort it out within HTML, JavaScript and jQuery to avoid complexity.
Easy, you make an ajax call to the html page that you want to be used as template and you place it before or after the proper node
<script type="text/javascript">
$.ajax({
url: 'static/components/credit_field.html',
success: function(content) {
$('template')[0].before(content);
}
});
</script>

Page Reload while clicking on the href link

I have a web application in which index.jsp is a welcome page. Index.jsp contains the UI code . And i have multiple html files which has the same href link . My problem is whenever I click on the link the UI is reloaded. So when the url is same, the UI should be maintained and the page should not be reloaded.
I am new to web application development . Please help me on this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="myform_sample1">
<a href="http://localhost:8080/app/index.jsp?file=filepath" target="http://localhost:8080/app/index.jsp?file=filepath">sample1<br>
</a>
</div>
<div id="myform_sample2">
<a href="http://localhost:8080/app/index.jsp?file=filepath" target="http://localhost:8080/app/index.jsp?file=filepath">sample2<br>
</a>
</div>
</body>
</html>
you can try this:
$.ajax({
url: "test.html",
cache: false,
success: function(html){
$("#results").append(html);
}
});
on a click event you can transfer values and get back through ajax without reloading ur UI
I think you might be looking for jQuery:load, get, ajax

How can I get the content of a loaded file (with script or link)

I was wondering, how I get the content of a loaded script, stylesheet, ... bye an accessing an id set on the element.
Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script src="../jquery-1.8.3.min.js"></script>
<script id="test" src="test.txt" type="text/isis-template"></script>
<!-- File contains "Hello world" -->
<script>
$(function () {
$('#test').GET_CONTENT_OF_LOADED_FILE
});
</script>
</head>
<body>
</body>
</html>
Background: I want to load HTML templates (e.g. for mustach, knockout), but don't want to write them into the page, I'd rather have them in a seperate file. Now I saw that I can load any file with the script or link tag, so I was testing if I can load them like this....
Any comments why this might be a bad idea or how it can be done better are appreciated.
Try using load()
$(function () {
$('#test').load('yourfolder/test.html', function(resp){
alert(resp);
});
});
If you have already load the contents in some html element
contents = $('#test').html();
So you want the content of text/isis-template file when document is ready?
You are lucky because this file doesn't fall for CORS but mine(the answer i was looking for and came here today) do.
Well just do ajax!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script src="../jquery-1.8.3.min.js"></script>
<!-- File contains "Hello world" -->
<script>
$(function () {
$.ajax({ url: "test.html"})
.done(function(cont) {
var GET_CONTENT_OF_LOADED_FILE=cont;
});
});
</script>
</head>
<body></body>
</html>
If you use debug tools and see the network activity, you will see that it does not load the external files (since it is not a text/javascript, and the browser does not know how to handle it)
(wrong test on my part, was testing local files)
So you only have a tag there with an id and an external resource in the src attribute. Treat it as just metadata.
You will have to manually load the resources
something like this
// load external template resources
$('script[type="text/isis-template"]').each(function(){
$(this).load(this.src);
});
For actual use you would need to make sure the templates are loaded before you try using them..

A random number automatically appended to a js file

My index.php code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="js/jquery.js"></script>
<script>
$(function(){
$("body").load("AJAX.php");
});</script></head>
<body>
</body>
</html>
And my AJAX.php code
<body>
<script src="js/asdf.js"></script>
</body>
and my asdf.js code
function cool(){
alert("hi");}
Now When i load index.php and see the console it output
[16:21:57.237] GET http://localhost/js/asdf.js?_=1342003917230 [HTTP/1.1 200 OK 8ms]
Now i want to know why it is adding that random number to url of js file and how to prevent that?
See the docs for the ajax method:
cache
Default: true, false for dataType 'script' and 'jsonp'
If set to false, it will force requested pages not to be cached by the
browser. Setting cache to false also appends a query string parameter,
"_=[TIMESTAMP]", to the URL.
It is added to prevent the file from being served from browser cache.
If you are using the .load method in jQuery you can disable it by passing the option {cache:false}
$.ajaxSetup({cache : true});
$.load(url, data, function() {
// callback function
});
Or
$.ajax(url, {cache : true, dataType : 'html', success : function (response) {
$('body').html(response);
}});

Categories

Resources