Modifying controls collection error in VB.net - javascript

I need a function to be performed on the page load, which uses a stored session variable. I have added the following to my <body> tag.
<body onload="doSomething(event,'<%= Session("StartTime") %>')>
This does work. However, it is causing a problem elsewhere, when I try to add a control to my controls collection:
dim myPanel= New Panel
...
Me.Controls.Add(myPanel)
It bombs out at this stage, giving the following error:
"The Controls collection cannot be
modified because the control contains
code blocks (i.e. <% ... %>). "
I've tried the suggestion of using <%#...%> instead of <%=...%>, but this prevents the session variable being found- it is just blank.

Or,
<body onload="doSomething(event,'<asp:PlaceHolder id="starttimePlaceholder" runat="server"</asp:Placeholder>')>
Then, on the server side to populate it:
starttimePlaceholder.Controls.Add(New LiteralControl(Session("StartTime")))

I found a solution that worked
I forced my script to run on a server-control.
<body ms_positioning="GridLayout" onload="callFromDiv(event);">
<div runat="server" ID="serverDiv">
<script type="text/javascript">
//This function must be placed in a separate div, since placing it directly
//in body tag prevents new controls being added later
function callFromDiv(e){
doSomething(e,'<%= Session("StartTime") %>')
}
</script>
</div>

Related

Asp.net:show loading image before page loads for the first time

i am trying to display a loading image when the page is loading.Here is my code.
<body onunload="doHourglass();" onbeforeunload="doHourglass();" onload="setTimeout('show()',2000);">
<div id="divWait" style="display:none" >
<h1>wait...</h1>
</div>
<div id="main" style="display:none">
<asp:Button ID="btnHidden" runat="server" OnClick="code behind handler"
<div/>
<script>
function doHourglass()
{
console.log("inside dohour glass");
var divwait=document.getElementById('divWait');
var divmainpage=document.getElementById('main');
divmainpage.style.zIndex="0";
divwait.style.zIndex="1";
divwait.style.display='inline';
divmainpage.style.display='none';
setTimeout("show()",2000);
}
function show()
{
console.log("inside show");
var divwait=document.getElementById('divWait');
var divmainpage=document.getElementById('main');
divmainpage.style.zIndex="1";
divwait.style.zIndex="0";
divwait.style.display='none';
divmainpage.style.display='inline';
}
</script>
</body>
Problem is, it is not working when the page is loading for the first time.when i checked using console.log() i see for the first time control is not going inside doHourGlass() function.but for button click event it is working perfectly.
Things i tried:checked this link on SO, but i am not putting static html.I am trying to get the id of an html element and then working on that element so i can not use that solution.
Edit:one way i found is to keep divwait visible and hide main division then show main div when the page loads.but this way i can only display static html.i want to be able to call a function when page is loading for first time.
what is happening?is there a way to achieve it?please guide me.

modifying main view from inside partial view

I have a main view that let's say has the following:
<div id='test'>Some Text</div>
<div id='placeholder'></div>
then using ajax I'm replacing the contents of 'placeholder' with a partial view that looks like this:
<div id='ajaxContent'>
// new content
</div>
<script>
$(document).ready(function() {
console.log($('#test').text());
$('#test').css('color','red');
});
</script>
so in my script I'm trying to change the color of the text in div 'test' to red, but I keep getting 'undefined' in the console. How do I access the test div in the main view from the partial view coming into the main view through ajax?
If they're ending up on the same page, shouldn't the html elements be able to see each other?
Your JavaScript fragment is simply removed by jQuery on html(...) call. A similar issue can be found here: jQuery .load() / .ajax() not executing javascript in returned HTML after appended
Thus, you have to insert partial data in this manner (assuming you have your partial respone in result variable):
$(result).find('#ajaxContent').appendTo('#placeholder');
$(result).find('script').appendTo('#placeholder');
Also, as #RolandBertolom said before, you don't need ready() in your partial response in JavaScript.
You actually do not need to use $(document).ready. It's just useless. But it shouldn't break anything. As well as you can access any element on the page from script inserted anywhere in the same document. So problem is somewhere out your question's scope.
Try:
run $('#test').text() from console.
replace $('#test').text() with $('body') or something else in your script.
...
Be deductive when you debugging! ;-)
you should not be using $(document).ready again because you document will already loaded with main page so again using it wont help.
try like this:
suppose this is your test.php:
<script>
jQuery(document).ready(function() {
$.ajax({
type:'post',
url:'submit.php',
success:function(data) {
$('#placeholder').append(data);
}
});
});
</script>
<div id='test'>Some Text</div>
<div id='placeholder'></div>
//this is your submit.php the content to replace
<?php
echo "<div id='ajaxContent'>
</div>
<script>
$(function(){
console.log($('#test').text());
$('#test').css('color','red');
});
</script>";
?>
NOTE: what i exactly mean here is use:
$(function(){
console.log($('#test').text());
$('#test').css('color','red');
});
in script.

function variable not passing to global variable

Good day all, I've two pages of php file and an external javascript file. I want to pass a selected radio button's value to a jquery global variable so that I can view the div element which has the same id as selected radio button's value. Whenever I click PLAY! button I don't see my div element on the next page. Here are my codes:
player-choose.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body>
<div id="player-list">
<input type="radio" name="player" value="fighter" id="fighter-radio"><label for="fighter-radio"><img src="images/heroes/fighter-01.png" width="74" height="70"></label>
<input type="radio" name="player" value="pakhi" id="pakhi-radio"><label for="pakhi-radio"><img src="images/heroes/pakhi.png" width="95" height="70"></label>
</div>
<button id="play">PLAY!</button>
</body>
mycustom.js script:
var playerID;
function start(){
spawnhero();
}
$(function(){
$("#play").click(function(){
window.location.href = 'index.php';
playerID = $('input[name=player]:checked').val();
});
})
function spawnhero () {
$("#content").append($("<div>").attr('id', playerID));
}
index.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body onload="start()">
<div id="content">
<div id="galaxy"></div>
</div>
</body>
It's a very simple thing but I don't know why it's not working. Am I doing something wrong here? Please if anyone finds a solution enlighten me. Tnx!
If you're moving to a new page (window.location = ...), you'll need some slightly more complicated way of transferring information between those pages - for the most part, HTTP/HTML is "stateless", with the exception of technologies like cookies. JavaScript variables get wiped out entirely - it's actually re-parsing the entire JQuery library on each new page (not to say that's something to avoid)
For a video game, as long as player information doesn't include server components (I could be wrong) my recommendation would be saving player information in sessionStorage.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
However, if this is a server-based game in which your choice of player matters beyond the local computer, you'd likely want to send the player ID to the server, either by structuring the page request differently:
window.location.href = 'index.php?playerId=' + playerId;
Or by POSTing the data as a form; most easily accomplished by structuring your submit button as an <input type="submit">, and wrapping all your <input> elements in a <form method="POST"> object.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
From there, your server software could write the second page's response out differently based on the given information - you can even customize what JavaScript is written inside of a <script> tag using PHP directives.
var playerId = "<?php print($_POST['playerId']); ?>";
Hopefully that helps get you started.
global variables are not persistent across pages. Once you load your index.php , it will have the new global scope(window variable).
I suggest passing a parameter.
$("#play").click(function(){
playerID = $('input[name=player]:checked').val();
window.location.href = 'index.php?id=' + playerID;
});
afterward, inside your index.php script , read the parameter and assign accordingly.
Alternative solution is you could you use JavaScript or jQuery cookie or localstorage. You can get/set values across page loads/redirects but these are not passed to server.
jQuery Cookie
var playerID = $('input[name=player]:checked').val();
$.cookie("playerId", playerID);
LocalStorage
var playerID = $('input[name=player]:checked').val();
localStorage.setItem("playerId", playerID);

jQuery Auto-submit form inside of a <div> loads in new page

I'm developing a project of "prettifying" of a part of an existing web application. There is a need of putting the existing code: search criteria form in one div, and search results in another div (forming a kind of tabs, but that's another story).
Using jQuery I was able to manage that, but right now I am struggling with the results page, which by itself is yet another form that auto-submits to another file (using document.form.submit()), which is the final search results view. This auto-submit causes that the final view quits the destination div and loads as a new page (not new window).
So, the flow is like that:
First file, let's call it "criteria.html" loads the search criteria form (inside of a div) + another div (empty) destined to be filled with search results.:
<div id="criteria">... form with search criteria here...</div>
<div id="results"></div>
On submit, using jQuery's "hide()" method, I hide the first div (surrounding the search criteria form), and make Ajax call to the second file, let's call it "results.php":
<script>
$("#criteria").hide();
$.ajax({
...,
url: "results.php",
success: function(data){
$("#results").html(data);
},
...
});
</script>
results.php searches according to given criteria, and displays an "intermediary form" (which returns as a data result of the ajax query above) with a lot of hidden fields, and at the end executes:
<script>document.form.submit();</script>
which submits to another file, let's call it "resultsView.php"
This line causes that a result page shows outside the div "results", as a new page.
As there is a lot of logic in those files (more than 700 lines each), the idea of rewriting this monster just gives me creeps.
And now the question: is this a normal behavior (opening the result outside div)?
I tried removing the document.form.submit() code and everything works fine (well, without showing the results from "resultsView.php"). It's this line that causes the viewport to reset. I also tried with empty pages (to eliminate the possibility of the interaction with contents of the pages) - still the same result.
I hope there is not too much text and the problem is clearly stated. Every suggestion of how to fix this will be greatly appreciated.
If I understand your question correctly, you need to process the final submit using ajax instead of <script>document.form.submit();</script> so that you can handle the results on-page. Traditional form submits will always reload/open the action page. If you want to avoid that you'll have to control the form submit response via ajax and handle the results accordingly... like you are doing with the first submit.
The only alternative I can think of is to make div id="results" an iframe instead, so that it contains the subsequent form submit. Of course, that unleashes further restrictions that may cause other troubles.
I am not sure if I understood your question, but maybe u can do something like this.
This is my JQuery script: [I just wait for the submission search. When it happens, I use the $.Post method to call a function that should return the Html results (You can include somenthing to hide any field you want using JQuery or css)].
<script type="text/javascript" src="http://code.jquery.com/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("form#searchForm").submit(function() {
var theCity = $("select#chooseCity").val();
var theName = $("input#searchInput").val();
$.post("callProvideSearchResults.php", {theCity: theCity, theName: theName}, function(data) {
$("div#searchResults").html(data);
});
return false
});
});
</script>
This is my Body: {it consists of the choice of a city, the a form to provide the name of the person you are lookng for and the place to provide the results.
<body>
<FORM id="searchForm">
<h2>Select the city: </h2>
<select id="chooseCity">
<?php
$theCitiesOptionsHTML = "cityOptions.html";
require($thePathDataFiles.$theCitiesOptionsHTML); / A large list of cities
?>
</select>
<h2> What is the name of the person </h2>
<P> <INPUT id="searchInput" TYPE="TEXT" SIZE=50></P>
<P><INPUT TYPE="submit" VALUE="search"></P>
</FORM>
<div id="searchResults">
<!-- Here: Search results -->
</div>
</body>
// Function callProvideSearchResults.php // Just call the function that makes all the job and echo the $Html page
<?php
include "provideSearchResults.php";
$theName=$_POST['theName'];
$theCity=$_POST['theCity'];
echo provideSearchResults($theName, $theCity);
?>
// provideSearchResults.php // Database connection and search
<?php
function provideSearchResults($theName, $theCity) {
include "databaseConnection.php";
//database Queries
// Generate $theHtml using strings or ob_start, for instance
return $theHtml;
}
?>

Javascript form.submit() works only when debugging

I have a weird problem when I try to submit a form. My page contains a html table and one column has a link that deletes the line from the DB calling a js function.
The html/php line is the following one:
<input type="hidden" name="deleteid" value=0>
print ", delete";
The javascript function is the following one:
function delete_line(team_id) {
if (confirm('<?php echo $txt_confirm_del_team;?>')){
document.formName.elements.deleteid.value = team_id;
document.formName.submit();
}
}
If I put a breakpoint on the line "document.formName.submit();", the called page can read the parameter "deletedid". If not, the parameters are not passed to the page called by the submit.
Btw, I have another issue if I use getElementById() to retrieve the element or the form in the javascript function: it says the getelementbyid is null (and it's not because I can retreive it using the syntax document.formName.elements.deleteid)
thanks
There may be some other event handlers there, you can open the page in Chrome and right click the anchor, then choose "inspect element" and then check out the event handlers in the "event listeners" tab.
As far as the code you posted; there is nothing wrong with it. The following works just fine for me:
<html>
<head>
<title>test</title>
</head>
<body>
<a onclick="javascript:delete_line(22);">delete</a>
<script>
function delete_line(nr){
console.log(nr);
}
</script>
</body>
</html>

Categories