How to reload page in MVC dynamically - javascript

Can someone help me? I want to change my page when some status change. I don't want to see that refresh sign above.
<script type="text/javascript" language="javascript">
var idleInterval = setInterval("reloadPage()", 5000);
function reloadPage() {
location.reload();
}
</script>
<h2>Verlichting</h2>
<div class="Verlichting">
<div class="Border">
Verlichting Garage 1
</div>
<div class="ButtonVerlichting">
#if (Model.Verlichting1 == true)
{
<button class="On">Aan</button>
}
else if (Model.Verlichting1 == false)
{
<button class="Off">Uit</button>
}
</div>
<div class="Border">
Verlichting Garage 2
</div>
<div class="ButtonVerlichting">
#if (Model.Verlichting2 == true)
{
<button class="On">Aan</button>
}
else if (Model.Verlichting2 == false)
{
<button class="Off">Uit</button>
}
</div>
<div class="Border">
Verlichting Garage Grind
</div>
<div class="ButtonVerlichting">
#if (Model.VerlichtingGrind == true)
{
<button class="On">Aan</button>
}
else if (Model.VerlichtingGrind == false)
{
<button class="Off">Uit</button>
}
</div>
</div>
<div class="clear">
</div>
When one of the Models bool change.
My page need to change when some State change. The buttons control some lights.
Now I refresh te page every 5 seconds. But i want when one state change it change?
I work normally with C# MVC but not with javascript of something else.

You cannot refresh the View server side or "dynamically" with your current code.
HTTP is stateless.
HTTP works like this: a client (web browser in your case, like Chrome) has requested a resource from your server (/mywebsite/myview) because you entered a web address/URL/URI into your web browser location bar. That web address is a "mapping" to your server. An HTTP GET request is sent from your browser to your server and your server is running ASP.NET, IIS processes the request and passes the request to your ASP.NET MVC app. Your controller/view route entry matches and your ASP.NET app View code is served back to the web browser in the form of an HTTP response.
Your web browser parses the Response, containing CSS/HTML and Javascript and renders the view/page.
Your browser is now disconnected from the server. Your browser is not going to talk to your server again unless you take an action like pressing a button or entering a different URL into the location bar. On the other side, your server has no current way to talk to the client browser, your server is disconnected from your client/web browser.
This is a standard HTTP request/response.
You are looking for a push notification feature in your software. Since you are using ASP.NET and are not familiar with Javascript, SignalR would be the best way to keep a connection open between the web browser and your server via Web Sockets with a long polling fallback. SignalR is very easy to use and get setup.
Long polling is what you are currently doing, you are checking every 5 seconds for a change. You can continue to this but instead of getting all the HTML/CSS and Javascript again with a reload. Simply check some other Controller/API endpoint for a state change and then reload the whole page only when that state change occurs. This is actually a reasonably scalable solution from the sounds of your current needs.

Related

Send Javascript Push Notification - AFTER Form POST and URL redirection

Use case (Django Project):
I want to log in on my login page -> Therefore I use this form in html (login.html):
<form class="loginform" action="" method="POST">
{% csrf_token %}
<div class="loginform">
{{form.as_p}}
</div>
<br>
<input type="submit" class="btn btn-success loginbtn" value="Login">
</form>
In case of successful log in I will redirect with DJANGO to this URL (localhost/welcome/)-> welcome.html:
LOGIN_REDIRECT_URL = "welcome"
I am able to send javascript notifications with alertify, but only when using simple things such as
click on it or mouseover:
function notification(text) {
console.log(text)
alertify.success(text);
}
I tried it with onsubmit="javascript:notification("")" in the html form tag, however this will
be displayed only BEFORE the URL redirection.
So my question is:
How is it possible to activate /send the push notification AFTER the URL redirection and in
case of successfull POST/ Log in?
I really appreciate your help! Thank you a lot!!
Javascript is client-side. That means your alertify.success(text); will be executed client-side, once server already did his render process.
The authentication process is server-side. So you have to make your server make your alertify a part of the rendered content.
Knowing that, you just have to change your LOGIN_REDIRECT_URL content page to include in it a call to notification:
<!-- your html template comes here -->
<script type="text/javascript">
notification('You are now logged in');
</script>
Be remembered that the notification will then display each time the person visits this page. You may want either to redirect him again, or to introduce a variable in Django to avoid displaying it again.

express.js how to update UI without refresh all page using handlebars

It's one of the first time that I use express.js and Handlebars.
I need to autocomplete this field: <input type="text" id="myInput" autocomplete="on" placeholder="Search here...">. When everyone digit to this text, I need to make a POST and after a GET without refreshing the content in the page. The problem is, when I do the GET, Handlebars refresh all page. This is the command that I use:
res.render('home',{ items:typeOfCategory});
and this is the structure of the hbs:
{{#if items}}
<ul>
{{#each items}}
<li>{{this.title}}</li>
{{/each}}
</ul>
{{/if}}
My question is: how to avoid the refreshing of the all page?
Thanks
I had read something like that in another question. Based on this tutorial: I found the answer to all my problems.
this tutorial explain how to use a PJAX library that manages both the client and server side.
Thanks to 3 rows of code you can obtain a speed navigation without reload the page.
Install client side library from jQuery-pjax page
into your html page that send the request add: <a href='/yourLink' data-pjax='main'>YourLink</a>
where main is the div that will content yout change. In my case is:
<div id="main" class="main">
{{{body}}}
</div>
In your.js file add $('a[data-pjax]').pjax(); This command 'simply call the pjax extension on every element that contains the data attribute ‘data-pjax’'
Install inside express the depency with the command: npm install --save express-pjax
Set your server:
var app = express();
var pjax = require('express-pjax');
...
app.use(pjax())
Replace the normal rendering:
res.render('index', {title: "Index"});
with
res.renderPjax('index', {title: "Index"});
UPDATE
Alternatively you can obtain the same result. Consider that the structure of the project is as follows:
views
|-> partials
| |-> addtest.hbs
|
|-> index.hbs
For example, image that in your index.hbs you have a sidebar with different items, described in this way:
<li>
<a href="#testDB" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
<img src="../img/database-data.svg" class="svg icon">Test</a>
<ul class="collapse list-unstyled select-specific" id="testDB">
<li value="addTest" class=" ">
Add Test
</li>
....
....
</ul>
</li>
Inside the partials directory you have a simply form.
Now for manage the form you have to do two operations:
Server side: For switching from one partial to another without refresh the page, you specify:
router.get('/addtest', function (req, res) {
res.status(200);
res.header("Content-Type", "text/html");
res.render('partials/addtest', {title: "Add Test"});
});
Client side: In your client side file, you add make a simple get request:
$('#add-new-test').click(function (event) {
$.get('/addtest').then(function (data) {
$('#main').html(data);
});
});
In this way, when you make a get request with the same address (i.e in this case /addtest) the client add a part of code inside your view without refresh all.
NOTE: Keep in mind that, if you needed a some file.js in your partial, for load the file, use this:
<script>
var url = "/scripts/script.js";
$.getScript(url);
</script>
This is used for avoid: “Synchronous XMLHttpRequest on the main thread is deprecated…” because the call is asynchronous. For more info..
The problem here is that you're making the browser request a new resource each time. This is triggering your templating and serving up a brand new page every time.
You'll want to make an express endpoint which returns JSON, and then send up a request to that endpoint using something like AJAX (found in jQuery) or a similar library. This way you can make a call up to your web server, express can return you some data in a JSON format (res.json({}) and your frontend can then interpret that response and decide how to display it on the DOM.
This sort of partial updating is where you start to need frontend JS along side programatic endpoints that return JSON. This is often where some of these big frontend frameworks like Vuejs and Angular thrive, but if you're new to this sort of thing I'd recommend using jQuery to make a HTTP call to your server and return the JSON down to the frontend.

jQuery Load XML and Refresh Based on XML Variable

I am building a player for an online radio station. The stream is providing an XML file that displays the current song information. This XML file is hosted on the stream server which is NOT the server the website is running on.
Here is a sample of whats in the XML. Lets pretend it comes from http://randomserver/station.xml
<playlist>
<stationCallSign>KCXR</stationCallSign>
<programType>PGM</programType>
<mediaType>AUD</mediaType>
<title>Break Free</title>
<artist>Decyfer Down</artist>
<album>End of Grey</album>
<cover>
http://cdnrf.securenetsystems.net/file_radio/album_art/O/1/5/51Oo0rBqATL.jpg
</cover>
<duration>199</duration>
<campaignId/>
<fileId/>
<programStartTS>30 Sep 2015 17:48:22</programStartTS>
<adBlockPos>1</adBlockPos>
</playlist>
I need to pull that data to display it on the webpage and then refresh everything based on how many seconds are in the "duration" field. Essentially refresh all of this when the song changes.
Here is the html output I need.
<div id="playerDiv" class="player-div" style="display: block;">
<div id="album-art">
<img id="now-playing-album-art" src="http://cdnrf.securenetsystems.net/file_radio/album_art/e/1/5/51eeZTxMYuL.jpg" class="player-div-img cP" width="250" height="250" title="">
</div>
<div id="now-playing" class="now-playing tS">
<span id="now-playing-title" class="menuHeader f15em">Lights Out</span> - <span id="now-playing-artist">Silverline</span>
<div id="now-playing-album">Lights Out</div>
</div>
[playercode]
</div>
I was hoping to use the mobile jquery so that this functions well on mobile devices.
It sounds like you might need to do a little more research into ajax requests.
setTimeout(function() {
jQuery.ajax('http://randomserver/station.xml', {
success: function() { //Parse xml and update document },
error: function() { //handle error }
}
}, songDuration);
With jQuery you can easily download your xml file and update the song
In the above code setTimeout(callback,timeInMillis) allows you to set a time in milliseconds for the callback to occur. The callback then makes an XMLHTTPRequest to the url of your choice and then updates the page if it is successful in getting the page.
You can use the default Javascript XML parser to parse the response you get from the server.
Resources Used:
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
http://api.jquery.com/jquery.ajax/

On toggle Hide/show

I have this code.
If a user press on lets say burger and add it into session basket. The reload of page doesn't open the current Window View(Toggle)
How can I make it open the current again on reload...
<script type="text/javascript">
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
</script>
This is how to show/hide the text.
<div id="sandwich" class="hidden">
Here you go 1 </div>
<div id="burger" class="hidden">
Here you go 2 </div>
Things like this are not persistent across page reload / refresh.
There are two basic approaches to it:
Session cookie and session on server, communication via AJAX
Store all in a cookie
Both require some extra work, but it's unavoidable.
For the cookie part, there's a nice jQuery plugin called jquery.cookie.

How to display status message on web page

I have a bash script that checks for and deploys new .ear files to the JBoss server.I have linked this script to a web page, so that users can deploy their applications by clicking on the link.
I have also been able to set a status message that the application is being deployed, when a user clicks on the link.(Done using Javascript inside the HTML file).However I am not able to set a 'Deployment completed' message when the script completes execution.
Searching on the net was of little help,though I realized that what I wanted could be achieved using AJAX and requesting for the exit code of the script from the server.Being a system admin and having no knowledge of programming, I wish if somebody could help me out.Below is a part of my HTML file, if that would be of any help:
</table>
<FORM METHOD="LINK" ACTION="/cgi-bin/auto.sh">
<!--<INPUT TYPE="submit" VALUE="Deploy">--!>
<input type="submit" value="Deploy" onClick="showStatusMessage();">
<div id="statusMessage" style="display:none;">
<h3>Your application is being deployed.Please wait.</h3>
</div>
</FORM>
<script>
function showStatusMessage()
{
document.getElementById("statusMessage").style.display = "block";
}
function hideStatusMessage()
{
document.getElementById("statusMessage").style.display = "none";
}
</script>
</body>
</html>
Thanks.
The only way (i know of) to "know" once a server side deployment is complete. Would be to poll the server (with ajax) to check the status.

Categories