javascript loading sequence - javascript

I have a MainView "About.cshtml" it has a script tag in it and a partial view.
<script>
$(function () {}
</script>
<div>
#Html.Partial("~/Views/Maps/_MapDetailsList.cshtml", Model.saVM)
</div>
Inside "_MapDetailList.cshtml" partial view i am referencing another script ge.js
#Scripts.Render("~/Scripts/ge.js")
<table id="MapDetails">
.....
<tr><th>
<script>setGrowthArray(1, 1);</script>
</th></tr>
</table>
ge.js
var dictionaryGrowth = new Array();
function setGrowthArray(colIndex, mapDetailId) {
//making a sparse array
dictionaryGrowth[colIndex] = mapDetailId;
}
Now i want to send this dictionaryGrowth array to server side after the page/table is loaded
so i did the following in the About.cshtml script but didnot work..
<script>
$(function () {
$("#MapDetails").load(function () { alert("everything seems fine");});
}
</script>
Also please tell me what will be the script and DOM loading sequence in my case.
UPDATE
Probably the Current sequence is
Script on About.cshtml is executed
ge.js is executed
document.ready inside partial view is fired
javascript function (setGrowthArray) from inside DOM is called
Now i want to call my controller??
If i write window.onload = ... inside ge.js it is never fired

You can substitute using $.post() for .load(), pass result of setGrowthArray(1, 1) as data posted to server
<script>
$.post("/path/to/server", {growth:setGrowthArray(1, 1)}, function(data) {
console.log(data); // response from server
$("#MapDetails").html(data);
})
</script>

Related

Unable to execute scripts depending on Thymeleaf variables <script th:inline="javascript">

I have 2 simple scripts and 2 Thymeleaf variables, I want one script to be executed if thymeleaf variable is true, then again if other variable is true - related script to be executed and so on. But I get the following result - if one variable is true and script executed then second script won't be execudet even if second variable is true. So shortly, only one of scripts is executed, but need both (in sequence, not the same time). Here is the code:
<script th:inline="javascript">
var flag = [[${invalidInput}]]; //Thymleaf variable
window.onload = function() {
if(!flag)
return;
openForm();
};
</script>
<script th:inline="javascript">
var flag = [[${exists}]];
window.onload = function() {
if(!flag)
return;
openForm();
};
</script>
<!-- MODAL -->
<div class="form-popup" id="myForm">
<form id="registration" th:action="#{/registrate}" th:object="${newUser}" method="post" class="form-container">
<h1>Registration</h1>
<div class="alert" th:if="${exists}">
User already exists! Please try again.
</div>
<div class="invalidInput" th:if="${invalidInput}">
Username or password too short.
</div>
************************************************************
<script>
function openForm() {
document.getElementById("myForm").style.display = "block";
}
#PostMapping("/registrate")
public String login (#ModelAttribute(value = "newUser") User newUser, BindingResult bindingResult, Model model) {
userValidator.validate(newUser, bindingResult);
if(usrService.isUserPresent(newUser.getUsername())){
model.addAttribute("exists",true);
return "login";
}
else if(bindingResult.hasErrors()){
model.addAttribute("invalidInput",true);
return "login";
}
I don't think you can set the window.onload variable twice... one will simply overwrite the other. You can either combine your logic like this:
<script th:inline="javascript">
var invalidInput = [[${invalidInput}]]; //Thymleaf variable
var exists = [[${exists}]];
window.onload = function() {
if(invalidInput) {
openForm();
} else if (exists) {
openForm();
}
};
</script>
Or alternatively you could use something like jQuery, which has this functionality built in for you.
https://api.jquery.com/ready/
When multiple functions are added via successive calls to this method,
they run when the DOM is ready in the order in which they are added.

how to transfer data from one html page to another using javascript

I'm trying to transfer data from one html page to another page, so I wrote this program:
page1.ejs:
<a href="/events" onclick="send()">
<span class="message">
new alert
</span>
</a>
function send() {
$mesg = $('.message');
var msg = $mesg.text();
var msg1 = msg.replace(/\s/g, '');
localStorage.setItem("message", msg1);
}
page2.ejs:
<script src="socket.io/socket.io.js"></script>
<script>
document.getElementById("event").innerHTML = localStorage.getItem("message");
</script>
<td id="event"></td>
But I don't get the data transferred from the pages? what is my mistake?
The issue is in page2.ejs:
Problem: The HTMLElement <td id="event"></td> is not yet available when your <script> block is parsed and executed, so document.getElementById("event") returns undefined.
Solution: Move the <script> block to the bottom, beneath <td id="event"></td> and it should work.
page1.ejs:
On click of submit -
window.location.href="page2.ejs.html?text1="+$('#text1').val()
page2.ejs:
$(document).ready(function(){
var value1 = document.URL.indexOf('?text1=');//value from pag1.ejs
});
you should define the Send() function inside script tag
and Page 2 run the java script when page ready
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("event").innerHTML = localStorage.getItem("message");
});

How to pass a JavaScript object to another JavaScript script created from an AJAX call

I am working on a single page web app and I'm working with JavaScript objects for the first time. My index page has a menu button which populates in an element in the body using AJAX. That AJAX call returns a button and which requires it's own javascript. My issue is that I can't access the DataEntryObj object that I created in the original script from the JavaScript generated from the AJAX call. When I console log the object, it returns the text used to create the object rather than an object itself. What's going on?
index.php
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...menu
<button type="button" id="loadElement"></button>
...end of menu
<div id="response"></div>
<script>
//data Object
var DataEntryObj = function(){
this.dataArray = [[0,1,2,3,4]];
}
$(document).ready(function() {
$('#loadElement').click(function(){
var dataObject = new DataEntryObj();
console.log(DataEntryObj);
//this AJAX call works
$.post("php/entries/loadElement.php", {array : dataObject.dataArray}, function(data){
$('#response').html(data);
});
});
});
</script>
</body>
</html>
loadElement.php
...HTML
<button type="button" id="loadSubElement"></button>
<div id="subResponse"></div>
...end of HTML
<script>
$(document).ready(function() {
$('#loadSubElement').click(function(){
//this AJAX call doesn't work
$.post("php/entries/another.php", {array : DataEntryObj.dataArray}, function(data){
$('#subResponse').html(data);
});
});
});
</script>

Passing a parameter to my Knockout ViewModel

I have an MVC site that uses Knockout JS. Basically, the MVC handles routing to a few different pages, and each page has a viewmodel.
One of the pages requires a parameter to filter the data. The code for the MVC Controller for that page is as follows:
public ActionResult Transactions(int policyId)
{
ViewData["policyId"] = policyId;
return View();
}
The View for that page includes a hidden field.
<input type="hidden" name="hldPolicy" value="#ViewData["policyId"]">
Then after the html for the page,
#section scripts
{
#Scripts.Render("~/bundles/myBundle")
<script>
$(document).ready(function () {
var policyId = $('#hldPolicy').val();
var transactionViewModel = new TransactionViewModel(policyId);
ko.applyBindings(transactionViewModel);
});
</script>
}
The problem is this doesn't work because the hidden field is undefined when the script runs. That doesn't make sense to me as I thought that was what the $(document).ready was protecting against. What am I doing wrong here? And is there a better way to pass a parameter from the URL params into the viewmodel?
You can use it like this. Here you dont actually have to pass the parameter instead define a function which will be called on viewmodel initialization and get the data according to your requirements.
#section scripts
{
#Scripts.Render("~/bundles/myBundle")
<script type="text/javascript">
function TransactionViewModel(){
var self = this
self.SomeProperty = ko.observable()
self.LoadData = function(){
var policyId = $('#hldPolicy').val();
self.SomeProperty(policyId)
}
self.LoadData()
}
$(document).ready(function () {
ko.applyBindings(new TransactionViewModel());
});
</script>
}
When knockout model will be initialized it will call self.LoadData() automatically.
EDIT
I found you are missing id attribute at your input
<input type="hidden" id="hldPolicy" name="hldPolicy" value="#ViewData["policyId"]">
Now it should work properly.
EDIT:
You can also do it like this
#section scripts
{
#Scripts.Render("~/bundles/myBundle")
<script type="text/javascript">
function TransactionViewModel(policyId){
var self = this
self.SomeProperty = ko.observable()
self.LoadData = function(policyId){
self.SomeProperty(policyId)
}
self.LoadData(policyId);
}
$(document).ready(function () {
var policyId = $('#hldPolicy').val();
ko.applyBindings(new TransactionViewModel(policyId));
});
</script>
}

How do I reference a Razor variable later in my page in JavaScript or HTML

I have the following Razor code:
#{
if (IsPost)
{
string pn=Request.Form["pn"];
if (!string.IsNullOrEmpty(pn)){
/* my code to call the stored procedure with pn as a parameter*/
}
}
}
And in the page, using JavaScript / HTML I need to tell the user about pn. Be it that it's empty, or report back that the value was inserted in the database.
How do I do that?
You need to insert the result into the rendering. There are a couple of ways of doing that. You could store it in a variable:
<script type="text/javascript">
var pn = '#(pn)';
alert('pn is ' + pn);
</script>
Or you could call a function, sort of like JSONP:
<script type="text/javascript">
parsePn('#(pn)');
<!-- ... extra logic ... -->
function parsePn(pn) {
alert('pn is ' + pn);
}
</script>

Categories

Resources