Delay the loading of a page until AJAX calls received - javascript

I have a program that calculates bitcoin mining profitability and thus requires the live price of bitcoin, but I also want the user to be able to edit the price after it is initially loaded as the live price.
The problem I'm running into is that when I run my code bpv goes initially as undefined, even though it should be called when the body loads, theres no issue with the ajax call because once run update after the body has loaded, bpv gets defined.
I suspect this is because the ajax call takes longer than the page takes to load, leaving bpv undefined, then when I run update() the code is already initialized so theres no delay.
What I also suspect would fix this would be to make the page wait to load until the ajax call has been sent back, but I can't imagine this being scaleable at all?
I'm very new to this so try and be easy on me, thanks.
<head>
var bpv;
function update(){
getVal();
getPrice();
function getPrice(){
$.ajax({
dataType:"json",
type: 'GET',
url:'https://blockchain.info/ticker',
success: function(data){
bpv = data.USD.last;
}
});
}
}
</head>
<body onload = "update()" >
<script>
function getVal(){
//Current Value of Bitcoin
bpv = document.getElementById("bp").value;
</script>
Value of Bitcoin ($)<br/>
<input type="text" id="bp" onKeyDown="getVal()" onKeyUp="getVal()" value="" ><br/>
EDIT: I used Alex's solution, although it only fixed the input displaying undefined, and not the end result of the calculations, so if implemented a very janky solution in where I run the calculation again, .1 seconds after the page has loaded, if anyone whos smarter than me knows a better solution my ears are wide open

Ajax calls are asynchronous. So the rest of the page will always execute while the call is being done. I'm not exactly sure what you are trying to accomplish, but if you wish to show the value of Bitcoin on the input box and then let users change it after it's been loaded, you could follow something like:
Start with input box disabled;
Load bitcoin with AJAX call;
Set the response price into the field;
Enable the field so users can edit;
That could look like:
(I'm removing part of the code to exemplify, but if you have any questions let me know)
<head>
<script>
var bpv;
document.addEventListener("DOMContentLoaded", function(event) {
getPrice();
});
function getPrice(){
$.ajax({
dataType:"json",
type: 'GET',
url:'https://blockchain.info/ticker',
success: function(data){
bpv = data.USD.last;
setPriceInput(bpv);
}
});
}
function setPriceInput(value) {
var input = document.getElementById('bp');
input.value = value;
input.disabled = false;
}
</script>
</head>
<body>
Value of Bitcoin ($)<br/>
<input type="text" id="bp" value="" disabled>
</body>
https://jsfiddle.net/81oqsk5x/1/
This solution will wait for the page to be rendered, then try to get the price. Once the price is responded from the API, it will set the price on the input and enable it again (if you look at the input element, it starts as disabled)

So a couple things.
Your first tag is this is not valid. The head tag needs to
contain proper contents.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head
Move all the javascript inside of the script tag
function getVal(){ is not properly formatted and has invalid syntax. you are missing a closing bracket
Instead of trying to set bpv after you make the AJAX call, update the value of the DOM document.getElementById("bp").value = data.USD.last

Always put your Jquery code within the Ready function
$(document).ready(function(){
// your code here
});

Related

Refresh razor page without reload using javascript/ jquery in asp.net core

I have one input and script to reload table in my page. In the input if I insert 1000 I want to reload page every second, without clicking any buttons.
This is what I tried :
<input id="txtRefresh" />
<script>
document.redy(function () {
$('tblRefresh').load();
setInterval(function () {
$('#tblRefresh').load();
}, 'txtRefresh');
});
</script>
Its cshtml razor page.
What I want to do is to insert the value of seconds in the input andrefresh the page based of the of the inserted value, without submiting any data.
Is it possible to do this? Any suggestions?
Thanks in advance!
UPDATE
I inserted this script:
<script>
document.ready(function () {
$('#refreshDIV').load('url/url/url');
setInterval(function () {
$('#refreshDIV').load('url/url/url');
}, $('#txtRefresh').val());
});
</script>
But it gaves me error!
refreshDIV is a div that I want to refresh
txtRefresh is the input from I insert the seconds
you can try this:
$(document).ready(function(){
var timeout = $("#txtRefresh").val();
setTimeout(timeout, function() { location.href=""; });
});
but each time you will reload the page you will lose, the input.
You could send it through querystring like this:
location.href="?timeout="+timeout
and populate the input server side
This is just a string:
'txtRefresh'
If you want to get the value of that element, it would be more like this:
$('#txtRefresh').val()
You also have a typo in document.ready and in your first #tblRefresh selector (missing the #), and you aren't supplying .load() with the URL you want to load. All together you appear to be trying to do this:
$(document).ready(function () {
$('#tblRefresh').load('/some/url');
setInterval(function () {
$('#tblRefresh').load('/some/url');
}, $('#txtRefresh').val());
});
A couple things to note:
The value /some/url is of course a placeholder in this sample code. Whatever URL you want to use in your application is up to you.
Calling .load() will place the entire response of that URL into the target element. If you want only a subset of that response, you can add selectors to .load(). For example:
$('#tblRefresh').load('/some/url #someElement');
This would tell .load() to grab all the content from /some/url and then only select from it the content of #someElement to place in #tblRefresh. The performance could still potentially be slow as all of the content from the URL is still downloaded. To address performance or for finer control over data, consider returning JSON data from the server and using .ajax() to fetch that data instead of using .load() to reload all of the HTML (when only the data has changed).

Update Classic ASP DIV without reloading the webpage using jQuery

This should be really simple, so, either I am over thinking it or making it more complicated than it should be.
I would like to update a DIV without having to reload the webpage.
A form on Canvas.asp queries the database and returns the coordinates of a GPS device. The coordinates are updated every minute and would like the script to return the latest coordinates without having to refresh the page. The coordinates are appended to a separate XML file.
I have written this;
<script type="text/javascript">
$(document).ready(function() {
$("#map").load('canvas.asp');
var auto_refresh = setInterval(function() {
$("#map").load('canvas.asp?std=<%=session("7digit")%>&submit=Search&execute=1');
}, 60000);
$.ajaxSetup({ cache: false });
});
</script>
The div to be reloaded;
<div id="map"></div>
The script returns an error by duplicating the header and content, after 60 seconds the map DIV is nowhere to be seen... Simply disappears! The coordinates are appended to the XML file every 60 seconds, even after the error.
What am I doing wrong?
Looks like you are always returning the full result of your canvas.asp page which will always be a full HTML document which will not play nice with your <div>.
The issue here is how you handle passing partial content back and that comes down to how you structure your ASP page. Here is a bare bones template I use often for this type of thing.
<%
Option Explicit
Dim action, def_action
Const BASE_ERROR_VAL = 1000
Const DISPLAY_PAGE = 0
Const DISPLAY_CANVAS_CONTENT = 1
'Without this the page does nothing, this is the gateway to your page.
Call init()
'First code that get's run when page is requested
Sub init()
'Defaults
def_action = DISPLAY_PAGE
'Process query string
action = Request.QueryString("a") & ""
If Len(action) > 0 and Isnumeric(action) then action = CInt(action) Else action = def_action
Select Case action
Case DISPLAY_PAGE
Call load_page()
Case DISPLAY_CANVAS_CONTENT
Call load_canvas()
Case Else
'As we have a default this should NEVER happen, but always worth covering your bases.
Call Err.Raise(vbObjectError + BASE_ERROR_VAL + 1, "canvas.asp", "Action required")
End Select
End Sub
Sub load_page()
>%
<html>
<head>
...
</head>
<body>
<% Call load_canvas() %>
</body>
</html>
<%
End Sub
Sub load_canvas()
%>
<canvas>
...
</canvas>
<%
End Sub
%>
This is purely bare bones and is just designed to give you an idea of how you could approach it, so for example to call just the canvas part of the HTML you would use something like
canvas.asp?std=<%=session("7digit")%>&a=1
and either not pass &a at all (as DISPLAY_PAGE is the default) or pass
canvas.asp?std=<%=session("7digit")%>&a=0
to display the whole HTML.
You might also noticed I included
<% Call load_canvas() %>
inside the load_page() procedure, this is just for the situation where you might want the content of the canvas also rendered on the full pass and then changed later on via a partial pass using a=1 for example.
While the answer provided by #Lankymart demonstrates the desired page template and the correct layout of code which enables greater flexibility, the answer is a simple Ajax function.
setInterval(ajaxRequest, 15000);
function ajaxRequest() {
$.ajax({
type: 'GET',
url: 'xmlUpdateScript.asp',
data: {
7digit: "<%=session("7digit")%>"
}
});
}
The Ajax request executes the 'xmlUpdateScript.asp' and returns the next set of coordinates which are placed inside the XML document and can be rendered to the map.

Reloading a page include every 30 seconds or when user submits form

I have a PHP page with a lot of includes which make up various parts of the page for a video website.
I have a comments section which submits information into a database (Which works fine). But I need to make it so when this is done only the included page/div refreshes.
This is the PHP:
<form id="song-comment-form">
<input type="hidden" value="<?=$rSong->id?>" class="song-id">
<textarea class="editor" id="song-comment-textarea"></textarea><br>
<input type="submit" value="Submit"><input type="button" value="Cancel" id="hide-song-comment-form">
<hr>
</form>
<div id="player-song-comments">
<?php $showComments?>
</div>
Here is my attempt at doing it with Javascript:
<script>
var $comments = $("#player-song-comments");
setInterval(function () {
$comments.load("/template/sections/player_comments.php #player-song-comments");
}, 30000);
</script>
This should reload just the comments section but instead, everything from this point onwards goes blank.
How it looks now when I press submit:
When I reload that page manually:
I don't want the whole page to refresh because it contains a video.
How can I make just that Refresh after submit is pressed OR every 30 seconds?
UPDATE:
I have tried using JQuery to execute this. I'm getting an error:
Fatal error: Call to a member function query() on a non-object in /home/content/58/12052758/html/template/sections/header.php on line 42
<script>
/*wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#song-comment-form').ajaxForm(function() {
alert("Thank you for your comment!");
});
}); */ //THIS IS LINE 42
$(document).ready(function() {
var options = {
url: 'template/sections/player_comments',
target: '#player-song-comments', // target element(s) to be updated with server response
type: 'post' // 'get' or 'post', override for form's 'method' attribute
};
// bind form using 'ajaxForm'
$('#song-comment-form').ajaxForm(options);
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#song-comment-form').ajaxForm(function() {
$("#player-song-comments").load('template/sections/player_comments.php');
alert("Thank you for your comment! The site is currently in maintenance and the comment won't show until you revisit this video");
});
});
});
</script>
For those interested. Here is the whole page: http://pastebin.com/c0kQ3tGp
You seems to load comments in PHP and as far as I know, PHP is only parsed once.
The simplest workaround I know is to use an iframe that you would refresh, but I'm not sure this is a good practice tho.
So there are two parts to your question:
How can I make just that Refresh after submit is pressed
You can use jquery-form for that. In your case, you can initialize your form to something like this:
$(document).ready(function() {
var options = {
url: 'your_form_action',
target: '#player-song-comments', // target element(s) to be updated with server response
type: 'post' // 'get' or 'post', override for form's 'method' attribute
};
// bind form using 'ajaxForm'
$('#song-comment-form').ajaxForm(options);
});
There are many other options you can play with.
OR every 30 seconds?
Try change your
$comments.load("/template/sections/player_comments.php #player-song-comments");
to
$comments.load("/template/sections/player_comments.php"); // remove the selector
According to the docs, the selector is used to insert fragments of the remote document. In other words, when load was executed, jQuery parses the returned document to find the element #player-song-comments. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.... I assume #player-song-comments is not part of your response?

How to refresh or reload a div's content using Ajax

This is somehow. i normally use jquery's load to load content from page A into page B , so loading a div's content into itself in order to just refresh it doesn't make much sense. What's the solution for this?
$('#A').load('pageX.php #A');
Please note that both #As are on pageX making it the same #A
This somehow interferes with the JavaScript in a bad way after that "load" i don't know why.
So these is simply to refresh a div.
An id must to unique in html document otherwise you'll end up having expected results for JavaScript.
In your case you need to remove duplicate id's
Something like this
$('#A').load('pageX.php #B');
or this will work:
$('#B').load('pageX.php #A');
Because of people coming to this question, if I were to do this again now, I would do it like this.
HTML
<html>
<body>
<div class="divToRefresh"></div>
</body>
</html>
JavaScript(JQuery)
<script>
$(document).ready(function(e) {
$.refreshDiv = function(arg){
var d = {someVariable_you_can_send:arg}
$.ajax({
url:'url_to_div_content',
data:d,
type:"POST"}).done(function(result){
$('.divToRefresh').html(result);
});
};
//////////call this for the first time//////////
$.refreshDiv('some value');
//////////////////////////// and then refresh it after a certain interval if you need to
window.setInterval(function(){
$.refreshDiv('some value');
}, 1000*60*60*60);
});
</script>

How can I fix my JavaScript page refresh

I'm trying to use jQuery to make a slightly more sophisticated page refresh. With a meta refresh, if a page fails to load once, it won't load again. I am trying to make something that will repeatedly try to load--if it fails to load once, it will try again the next time so that if the last load is successful I will see a fresh version of the page, whether or not there were intervening faults.
My code at present is:
<script language="JavaScript" type="text/javascript" src="/include/jquery.js">
</script>
<script language="JavaScript">
var delay=5*1000;
function load(){
setTimeout(load, delay);
jQuery("#content").load("calendar_internal.cgi?days=40", function(){
jQuery("#preload").hide("slow");
});
delay = 15*60*1000;
}
jQuery("#content").load("calendar_internal.cgi?days=40", load);
</script>
So far as I can tell, this is functioning as a noop. It doesn't refresh.
How can I get this to work at least at a basic level so it refreshes but one bad refresh doesn't mean that I have to reload if I want to see the page at all?
--EDIT--
What I have now is apparently working (after light testing):
<script language="JavaScript">
var placeholder = jQuery('<div></div>');
function load(){
setTimeout(load, 15*60*1000);
placeholder.load("logistic_ajax.cgi", function(){
if (placeholder.html())
jQuery('#content').html(placeholder.html());
})
}
load();
</script>
var $placeHolder = $('<div />');
$placeHolder.load(yourURL,function() {
if ($placeHolder.html()) {
$("#content").html($placeHolder.html());
}
});
or something like that. This way you are not doing all or nothing type of thing. If something messes up with the HTML coming back, you can check in your "if" condition. Not sure the particulars of the response so you would need to hash that out on your own or let me know more detail.
Cheers.

Categories