GSP tags in JavaScript - javascript

I had the following in the <head> of a GSP
<script type="text/javascript>
$("button.remove-item").click(function() {
$.ajax({
url: "${createLink(action: 'remove', controller: 'cart')}",
type: 'POST'
});
});
</script>
Notice that I'm using the Grails createLink tag to construct the URL that the AJAX request will post to. When I moved this code into checkout.js and replaced the block of code above with:
<script type="text/javascript" src="${resource(dir: 'js', file: 'checkout.js')}"></script>
the createLink tag is no longer evaluated by Grails. So it seems that Grails tags within <script> blocks are evaluated, but tags within .js files included by GSPs are not - is there a way to change this?

Check out the GSParse plugin to have css and js parsed as a gsp file:
http://nerderg.com/GSParse
http://grails.org/plugin/gsp-arse

You are right .js files are not evaluated by grails! but the GSP are! so thats why when u were setting a tag it was working.
I would suggest you to have a differente approach of how to grab that link! as u are using jquery I would do like this:
<input type="button" class="remove-item" data-url="${createLink(action: 'remove', controller: 'cart')}" value="GO" />
checkout.js:
$("button.remove-item").click(function() {
$.ajax({
url: $(this).data('url'),
type: 'POST'
});
});

Related

Thymeleaf onclick attribute with JS script won't work in Spring

I have a table generated through:
<tr *some other th tags* th:onclick="'javascript:openPoolModal(\''+ ${networkHashrate.id} + '\');'">
I have a openPoolModal function in static/js/openPoolModal.js
I have added a <script type="text/javascript" src="../js/openPoolModal.js"></script> to the .html file header where the function is used.
The function looks like this:
function openPoolModal(id){
$.ajax({
url: "/" + id,
success: function(data){
$("#PoolModalHolder").html(data);
$("#PoolModal").modal("show");
}
});
}
What am I missing?
I think this is a directory problem. You're including the js file by calling this script from your html file:
<script type="text/javascript" src="../js/openPoolModal.js"></script>
But if your html file is in directory resources/templates/ then this script is trying to call resources/js/openPoolModel.js which isn't where your Javascript file is.
Adding the js function directly to the html file called the function so your script and directory is wrong.

Laravel site not using Ajax in external javascript file

I am trying to have my site use Ajax from another file but it never works unless the code is actually in the view.
The site successfully calls my other Javascript file but does not seem to recognize the one with Ajax in it.
The following is in my external Javascript file with Ajax in it (ajax.js):
$(document).ready(function(){
$("#idForm").submit(function(e) {
$.ajax({
type: "POST",
url: "{{ url('/auth/login') }}",
data: $("#idForm").serialize(),
success: function(data)
{
location.reload();
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
And the following is in my master layout file that successfully uses the form.js file but not ajax.js .
<html>
<body>
<!--Other Stuff-->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost/sitename/public/js/forms.js"></script>
<script type="text/javascript" src="http://localhost/sitename/public/js/ajax.js"></script>
</body>
</html>
Any ideas?
By default, external js file don't support blade syntax. So, to send the ajax request from external js file need to do the followings:
create a global variable to ur template.blade.php file as follows:
var SITE_URL = "{{URL::to('/')}}";
then when to send the ajax request do:
$.ajax({
url: SITE_URL + '/route_name'
});

Load Javascript after AJAX-fetched HTML is fully loaded

I have a situation where the HTML part is loaded with AJAX into a DIV with ID="dynamic content" using main.js script. This script is situated inside the HEAD part of main.php and it goes like this:
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
}
});
The Javascript file responsible for controlling that content is situated in another JS file named secondary.js. This file is placed just before the closing of BODY again inside main.php.
main.php Document Structure:
<html>
<head>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
....
<div id="dynamic-content"></div>
....
....
<script type="text/javascript" src="js/secondary.js"></script>
</body>
</html>
Sometimes the content of content.php is too large, and secondary.js file loads before the content is fully loaded. Hence some elements are not targeted and i have problems.
Is there a way for me to delay for 1-2 seconds the execution of secondary.js, just to make sure that the content is fully loaded?
ps: all above files are hosted on the same server
Thanks in advance.
What you're trying to achieve is async behaviour. Whatever secondary.js does, put it inside a function and call it inside the ajax callback. If you do so, you won't even need two JavaScript files.
Don't try to manage this by timeouts or loading order. This will not be failsafe. You cannot know the exact time the browser needs to load your content. For example, what if you are on very slow internet connection? Don't try to predict those things, that's what the callback is for :-)
Your code could look sth like this:
function doSthWithLoadedContent() {
// whatever secondary.js tries to do
}
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
doSthWithLoadedContent();
}
});
You could possibly load the script using $.getScript once the output has been applied to the html tag:
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
$.getScript('js/secondary.js');
}
});
https://api.jquery.com/jquery.getscript/
The best way to do this would actually be to hand a callback to the function that does your ajax call. I probably wouldn't put this in html but it demonstrates the method:
<html>
<head>
<script type="text/javascript" src="js/main.js"></script>
<script lang="javascript>
function doWhenLoaded(someCallback)
{
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
someCallback();
}
});
}
$(document).ready(function(){
doWhenLoaded(function(){
$.getScript('js/secondary.js');
});
})
</script>
</head>
...
</html>
Instead of using $.getScript you could also load in secondary.js with main.js and wrap it in a function call (i.e. doStuff = function() { /* your code here */ }). Then you could call doWhenLoaded(doStuff) in $(document).ready.
You have to add script after ajax call.
$.ajax({
url: 'url of ajax',
type: "POST",
data: data,
dataType: "html",
success: function (data) {
$('#instructions').html('<div>' + data + '</div>');
$.getScript("js/html5lightbox/html5lightbox.js", function() {
$('body').find('.html5lightbox').html5lightbox();
});
}
});

How to put code thymeleaf in an external javascript file?

I have an external javascript file which is declared in my html file with the following tag:
<script type="text/javascript" th:inline="javascript" th:src="#{/js/gp-aprobarDocumento.js}"></script>
and in gp-aprobarDocumento.js the code shown below:
ventanaAprobacion = function(td)
{
/*<![CDATA[*/
idEntregable = $(td).attr("data-row-id");
idVersion = $(td).attr("data-row-version");
alert("la siguiente viene con el texto dle properties");
alert(/*[[${link.menu.page-certificacion-qa-bandeja-entrada}]]*/);
$(function() {
$("#dialog-aprobar-documento").dialog("open");
});
/*]]>*/
}
Thus when executed the function the window alert is shown empty.
Does somebody know how to put thymeleaf expression in a external javascript?
I think what you want to do it's not possible, I have a similar question (here:How do you access a model attribute with javascript variable)
but in your case you can do something like the this:
in html:
<script type="text/javascript" th:inline="javascript" >
var alertVariable = ${link.menu.page-certificacion-qa-bandeja-entrada};
</script>
and in the javascript the following:
ventanaAprobacion = function(td)
{
...
alert(alertVariable);
...
}
I know that's not really what you want but I have the same problem and I don't think there is any solution.
This worked for me. In my index.html:
<script th:inline="javascript">
/* variable used by index.js */
var referenceId = [[${referenceId}]];
</script>
<script type="text/javascript" th:src="#{/js/index.js}">
</script>
then in my index.js:
function doSomething() {
$.ajax({
type: 'GET',
url: '/api/' + referenceId ,
contentType: 'application/json',
beforeSend: beforeSend
})
}
Hope this helps.
Via DOM:
https://datatables.net/examples/data_sources/js_array.html
If you're looking to create a JS variable from a Thymeleaf object you can add said object to the DOM. I recently did a project where I returned query results to a Java object of type List<> and added that object to the DOM through my Spring Controller.
//Deliver Results Array to the DOM
model.addAttribute("myResult", myResult);
After this object is added to your Thymleaf template model you can access it in your HTML as
th:text="${myResult}"
You can also reference it in your Javascript by simply referencing the name of the model object from the DOM. I haven't been able to get the variable to populate in the seperate JS file without making it global in scope from the HTML file with:
<script th:inline="javascript">
var myResult = [[${myResult}]];
</script>
My JS file looks like this
$(function(){
//Get Thymeleaf DOM Object
console.log(myResult);
});
Returning Result from DOM
Th object in question must be reference-able from within the DOM. You may have better performance with AJAX and creating a controller that returns the data to the client over HTTP. Seems like thymeleaf 3 has other solutions as well : https://github.com/thymeleaf/thymeleaf/issues/395
Hope this helps!
Sure you can.
You can't put Thymeleaf template code in an external JavaScript file, but you can put JavaScript code in a pair of <script> tags in a html template, using a template fragment in the HTML.
Create a new HTML file 'gp-aprobarDocumento.html' in the /template folder, put your function in the script and replace /**/ with ".
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title></title>
<script th:fragment="gp-aprobarDocumento">
ventanaAprobacion = function(td)
{
idEntregable = $(td).attr("data-row-id");
idVersion = $(td).attr("data-row-version");
alert("la siguiente viene con el texto dle properties");
alert("[[${link.menu.page-certificacion-qa-bandeja-entrada}]]");
$(function() {
$("#dialog-aprobar-documento").dialog("open");
});
}
</script>
</head>
<body>
</body>
</html>
And add a th:replace <script> tag in your html file.
<script th:replace="gp-aprobarDocumento :: gp-aprobarDocumento"></script>

js .append html element do not have javascript lib

I'm trying to use $.ajax to get html string from php file and append to current html div. when i try to use php echo, everything works fine, but when i try to dynamically load using $.load or $.ajax, javascript library doesn't load or apply to the div.
included js libs in header:
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="MetroJs.lt.min.css">
<script src="MetroJs.lt.min.js" type="text/javascript"></script>
script file in header:
function getdatafromphp() {
$.ajax({
type: 'POST',
url: "autoload_process.php",
data: {group_no : track_load},
dataType: 'html',
async: true,
success: function(html) {
$("#results").append(html);
track_load++; //loaded group increment
loading = false;
}
})
}
html code in body:
<div id="results"></div><div class="animation_image" align="center"><img src="ajax-loader.gif"></div>
i put rest of css and js right after the div:
<link rel="stylesheet" type="text/css" href="index.css"/><script src="index.js" type="text/javascript"></script>
The html can be loaded into div, but it does not have any js effect to it (css is fine)
I suspect is because i use $(document).ready in both js scripts, but changing it does not help.
here is my test site: http://www.zsm.me/test/newindex/
Please help if you have any thoughts.
Thanks.
Try to bring in the data (html) into the specified div, then initialize the plugin for each of the elements inside the html.For ex:
success: function(html){
$("#mybutton").buttonset();
$("#dateofbirth").datepicker();
}
Today i find a new method by adding
<?php echo $script; ?>
in the header.
I have no idea why this works but it does...
well, hope this helps

Categories

Resources