I am trying to refresh a page at a interval of 5 seconds which should update the view with latest data from the SQL Server. Below is the code.
#model Test.Data.Domain.ManufacturingCdMachine
#{
ViewBag.Title = "Rimage Details";
ViewBag.JobId = Model.CurrentManufacturingJobId;
}
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top" id="navbar">
<div class="container">
<div class="navbar-header">
</div>
</div>
</div>
<div id="CdMachineDetails">
#if (#Model.CurrentManufacturingJobId != null)
{
<div>
#{Html.RenderPartial("_CdMachineJob");}
</div>
}
else
{
<div>
#{Html.RenderPartial("_MachineInIdle");}
</div>
}
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
</body>
</html>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor(Math.random() * 100);
$.ajax({
type: "GET",
url: "/Mobile/CdMachine/Details/" + #Model.ManufacturingCdMachineId,
data: {
},
success: function (result) {
//Sets your content into your div
$('#CdMachineDetails').html(result);
}
});
}, 5000);
});
</script>
The URL of my page is http://localhost:28886/Mobile/CdMachine/Details/1
However the page not seem to be refreshing. What am I doing wrong?
-Alan-
you have syntax error in your JS. I think you are missing bracket at the end of your JS code.
Ajax doesn't refresh page - you just get content which you can of course place on the DOM or can manipulate it as you wish.
URL pointing to your localhost server will not work of course - must be placed public.
Related
I trying to navigate between 3 pages which contain the same header and footer but each page has different content.
I want to load different contents html on hash change.
The problem is that when I click on the same page again, the content.html loaded again.
How can I use the content without loading the html again and again, using java script/html/jquery?
Code example:
Navigationbar.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Navigation Bar</title>
<link rel="stylesheet" type="text/css" href="css/navigationbar.css">
</head>
<body>
<nav>
<img id="navigation-bar-logo" class="logo" src='images/flybryceLogo.png'>
<ul class="navigation-bar-ul">
<li class="navigation-bar-li"><a id="navigation-bar-contact-page-tab" href="#contact.html">CONTACT</a></li>
<li class="navigation-bar-li"><a id="navigation-bar-about-us-page-tab" href="#aboutus.html">ABOUT US</a></li>
<li class="navigation-bar-li"><a id="navigation-bar-home-page-tab" href="#home.html">HOME</a></li>
</ul>
</nav>
</body>
</html>
initial.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>One Page Test</title>
<link rel="stylesheet" type="text/css" href="css/homepage.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div id="main-container" class="main-container">
<div id="header" class="header">
</div>
<div id="content" class="content"></div>
<div id="footer" class="bot"></div>
</div>
<script>
document.onreadystatechange = function(){
if (document.readyState == 'complete') {
window.onhashchange=hash_change;
window.onload=hash_change;
if(window.location.hash==''){
//default hash
window.location.replace('#home.html');
}
//load the header
$("#header").load("fragments/navigationbar.html");
//load the footer
$("#footer").load("fragments/footer.html");
}
}
function hash_change()
{
//get the new hash
var newHashCode = window.location.hash.substring(1);
if (newHashCode === "home.html"){
$("#content").load("home.html");
} else if (newHashCode === "aboutus.html") {
$("#content").load("aboutus.html");
} else if (newHashCode === "contact.html"){
$("#content").load("contact.html");
}
}
</script>
</body>
</html>
A longer but suitable solution would be to build a content cache on your own.
For example asking to the server just once the html and then setting it to the $('#content') element. You can use this helper function.
var contentsCache = {};
var getAndCache = function(url, callback) {
var cachedContents = contentsCache[url];
if (!cachedContents) {
$.get(url, function(serverContents) {
cachedContents = serverContents;
contentsCache[url] = cachedContents;
callback(cachedContents);
});
} else {
callback(cachedContents);
}
};
And then replace the $('#content').load calls by calls to this new asynchronous way.
function hash_change()
{
var fillContentCb = function(s) {
$('#content').html(s);
};
//get the new hash
var newHashCode = window.location.hash.substring(1);
if (newHashCode === "home.html"){
getAndCache("home.html", fillContentCb);
} else if (newHashCode === "aboutus.html") {
getAndCache("aboutus.html", fillContentCb);
} else if (newHashCode === "contact.html"){
getAndCache("content.html", fillContentCb);
}
}
As suggested in some comments, consider using native HTML navigation instead. Another suggestion is to use a client-side JS framework which supports routing if this application is likely to grow.
Add an if condition that checks whether the current hash location matches with the one that's been clicked on, and if it does just return. You'd have to store it in a global JS variable, and set it every time you navigate.
Hello i'm building an application where i want to dynamically change the source of an image in order to force reload it . The problem is that in order of this i only get a broken image on the browser. Instead , if a run the function manually by a button it runs perfect .
HTML document
<!DOCTYPE html>
<html lang="en" ng-app='cameraApp'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Node JS Camera</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src='https://code.angularjs.org/1.4.4/angular-sanitize.min.js'></script>
<script src="cameraApp.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="jumbotron">
<h1>Welcome to NodeJS Camera v1</h1>
</div>
<div ng-controller="HomeController">
<div class="cameraControl col-md-5">
<p>Here is the camera control</p>
<button class="btn btn-default" ng-click="getSnapshot()">Snapshot</button>
<button class="btn btn-info" ng-click="intervalFunction()">Start Feed</button>
</div>
<div class="lifeFeed col-md-7">
<p>Here is the live feed</p>
<p><button class="btn btn-default" ng-click="readSnapshot()">Snapshot Read</button></p>
<img width='600' height='600' ng-src="{{snapshot}}" alt="SnapShot taken">
</div>
</div>
</div>
</body>
</html>
cameraApp.js
var cameraApp = angular.module('cameraApp',[]);
cameraApp.controller('HomeController', function($scope,$http,$timeout) {
function updateImage() {
var img = 'snapshots/camera.jpg'+ '?decache=' + Math.random();
console.log('Snapshot Loaded');
$scope.snapshot = img;
};
$scope.readSnapshot = updateImage;
$scope.getSnapshot = function() {
$http.get('/api/getSnapshot')
.then(function(response) {
// this callback will be called asynchronously
// when the response is available
console.log('Snapshot captured');
$scope.readSnapshot();
}, function(response) {
console.log('Error in capturing...');
});
}
$scope.intervalFunction = function() {
$timeout(function() {
$scope.getSnapshot();
$scope.intervalFunction();
}, 2000);
};
// Kick off the interval
$scope.intervalFunction();
});
There are two solutions I've used for this in the past.
1) Use an ng-if/ng-show on your img tag. This will prevent the broken image from displaying.
<img ng-if='snapshot'>
2) Set a default image that will load and then be replaced once the other images load.
$scope.snapshot = 'snapshots/default.png';
I have a webpage with tabs inside it, and when I click on a tab it should load a text editor then get the text from a file and put it inside the text editor.
However, the text doesn't load synchronously, it behaves asynchronously. Even though I made something that should be synchronous.
here's the code :
function init(){
$( "#accordion" ).accordion({heightStyle: "content",collapsible: true});
$( "#tabs" ).tabs(
{
activate: function(click,ui) {
ui.oldPanel.children("#editor").remove();
ui.newPanel.load("be.htm",function(response, status, xhr){
$("#editor").css("width","100%");
$("#editor").css("height","500px");
$.ajax(
{
url: "./load_content.php",
async: false,
data: "name="+ui.newTab.text(),
success: loadContent
});
});
}
}
);
}
function loadContent(contenu){
alert(contenu);
$("#textBox").html(contenu);
}
as requested, i tried to make a MCVE
here is be.htm , the "editor" (i took out all that wasn't necessary)
<!doctype html>
<html>
<head>
<title>Rich Text Editor</title>
</head>
<body>
<div id="textBox" contenteditable="true"><p>Lorem ipsum</p></div>
</body>
</html>
here is bv.html, the webpage where the code must appear (the jquery script are lcoally stored on my computer so you'll have to input your own paths, sorry
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Projet</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<!-- <link rel="stylesheet" href="YOURPATHHERE/Projet/jquery-ui.css">- -->
<script src="YOURPATHHERE/Projet/jquery-2.1.3.js"></script>
<script src="YOURPATHHERE/Projet/jquery-ui.js"></script>
<script src="YOURPATHHERE/Projet/bv.js"></script>
<script src="YOURPATHHERE/Projet/jstree.js"></script>
<link rel="stylesheet" href="./bv.css">
<script>
$(function() {
init();
});
</script>
</head>
<body id="body">
<div id="tabs">
<ul>
<li>Onglet1</li>
<li>Onglet2</li>
<li>Onglet3</li>
</ul>
<div id="tabs-1">
</div>
<div id="tabs-2">
</div>
<div id="tabs-3">
</div>
</div>
</body>
</html>
i gave you the full javascript code i have so far.
and finally here's the php called by ajax :
<?php
$filename=$_GET['name'];
$data = file_get_contents("./".$filename);
echo $data;
return $data;
?>
and btw, i'm sorry if you find this code ugly, but i'm a starter as i already told.
I've been attempting to put together a website that requires obtaining xml data from another website. So far, using only html and javascript (no twitter bootstrap), I can access the website XML and populate a select dropdown menu. Here is the non-bootstrap html code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/getXML.js"></script>
</head>
<body>
<h1>Test App</h1>
<button id="button1">submit</button>
<select id="selectState"></select>
</body>
</html>
and here is the bootstrap html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS-->
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">
<!-- jQuery and JavaScript files -->
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/getXML.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<div class="container-fluid">
<div class="row-fluid">
<div class="span4 col-xs-3">
<form class = "well">
<h2 class="page-header">Inputs</h2>
<label class="control-label" for="selectState">Select State:</label>
<select id="selectState"></select>
<button type="submit" class="btn btn-default" id="button1" >submit</button>
</form>
</div>
</div>
</div>
</html>
and here is the getXML.js script:
var HttpClient = function() {
this.get = function(aUrl, aCallback) {
anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
$(document).ready(function(){
$( "#button1" ).click(function () {
aClient = new HttpClient();
aClient.get('http://www.waterqualitydata.us/Station/search?characteristicName=Caffeine&mimeType=xml&bBox=-92.8,44.2,-88.9,46', function(data) {
xmlDoc = $.parseXML( data ),
$xml = $( xmlDoc ),
$LocName = $xml.find( "MonitoringLocationName" );
var arr = [];
$.each($LocName,function() {
arr.push( $(this).text() );
});
for ( var i = 0; i < arr.length; i = i + 1 ) {
$('#selectState').append('<option>'+arr[i]+'</option>');
}
alert( "success" );
});
});
});
Now, when I try and using the Twitter bootstrap html, I am getting a Cross-Origin Request Block due to the Same Origin Policy.
Is there any reason why the scripts that don't use Twitter Bootstrap can get around the SOP, while the twitter bootstrap version can't?
Modify the Bootstrap script to include the 'type' attribute, like so:
<script src="js/bootstrap.min.js" type="text/javascript"></script>
The 'type' parameter here is key - it is what allows the remote request to happen. CSS and JS are allowed to do this kind of cross domain linking, as it is judged by the W3C gods to be a low security risk (at least last I checked).
Check these links out for more information on CORS:
IE's explanation: http://msdn.microsoft.com/en-us/library/ie/gg622939%28v=vs.85%29.aspx
Mozilla's thoughts: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
OK, I think I found the problem. I was placing the <button> inside a <form> element. This apparently raises the SOP block. Without the <form> element, no SOP block was raised.
I haven't looked at the exact reason behind this, but maybe its related to a security feature baked into the <form> element, since <form> elements can be used to pass sensitive information (passwords, etc.)?
in this project im using jquery and phonegap
i have a link that if clicked , changes the page:
$('#statsButtonmain').on('click', function() {
$.mobile.changePage("stats.html", { transition: "slideup"}, true, true);
});
this works fine, but i would like to run a function (playMusic()) when the transition is done, something like this:
$('#statsButtonmain').on('click', function() {
$.mobile.changePage("stats.html", { transition: "slideup"}, true, true);
playMusic();
});
i found out that there is a pageshow event that gets triggered on the page being shown, after its transition completes, but im not sure how to use it
this doesn't seem to work, any ideas?
Thanks
I've not done a lot a jQuery mobile development so this might not be the most efficient solution. As you said, the pageshow event is what you need to use. Here are the 2 HTML files I ran locally in which I see the alert after the stats.html page transition is completed. The .live() is bound to the #stats element's page pageshow event.
HTML
(saved as index.html)
<!doctype html>
<html>
<head>
<title>Home</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#statsButtonmain').on('click', function() {
$.mobile.changePage('stats.html', { transition: 'slideup'}, true, true);
});
$('#stats').live('pageshow', function(event, ui) {
playMusic();
});
function playMusic() {
alert('playing music');
}
});
</script>
</head>
<body>
<div data-role="page" id="home">
<div data-role="header">
<h1>Callback test</h1>
</div>
<div data-role="content">
click me
</div>
</div>
</body>
</html>
(saved as stats.html)
<!doctype html>
<html>
<head>
<title>Stats</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.js"></script>
</head>
<body>
<div data-role="page" id="stats">
<div data-role="content">some stats</div>
</div>
</body>
</html>
I hope this helps someone. It also retains the query string between pages too.
async function loadPage(_url) {
let promise = new Promise((resolve) => {
var _query = "";
if (window.location.href.includes("?")) {
if (window.location.href.split("?").length >= 2) {
_query = "?" + window.location.href.split("?")[1];
}
}
$.mobile.changePage(_url + _query);
var currentPage;
function checkCurrentPage() {
if (typeof $("body").pagecontainer != "undefined") {
currentPage = $("body").pagecontainer("getActivePage");
if (currentPage[0].baseURI.includes(_url)) {
clearInterval(loadPageInt);
resolve();
}
}
}
var loadPageInt = setInterval(function () {
checkCurrentPage();
}, 100);
});
return await promise;
}
Usage:
loadPage('file.html')
.then(() => {
// do some stuff now the page has changed to file.html
});