Javascript Auto Update - javascript

In my stream page, I have one current song script, but it doesn't update... The user needs to refresh the page.
the script is:
<script name="whasong" id="whasongid" src="http://xxxx.xxxx.net/js/song/u4:2134" type="text/javascript">
You appear to have javascript turned off.
</script>
src="http://xxxx.xxxx.net/js/song/u4:2134" code:
document.write('SONG NAME');
Is it possible to autoupdate just this script without refreshing the whole page ?

You might be in need of Ajax functionality. Do you mean that, at the end of a song playing, you want to modify the page content to reflect the song change? If it is so, you might gain a lot by looking into a JavaScript framework like jQuery or Backbone.js and bind some behavior to the state change in question. So you will want the song change (for example) to trigger a certain function you will have prepared, which will use jQuery to query the server via Ajax to update the page, and change the DOM accordingly.
EDIT: If instead of waiting for an explicit state change in your web page, you wanted to update it periodically, you might be looking for such a strategy :
function updatePage(/* arguments */) {
// Call the server to get some data ...
// Update the page accordingly ...
if (/* continue updating the page? */) setTimeout(60000 /* 60 seconds */, updatePage);
}
If you were using jQuery for your Ajax needs for instance, that function could look like so :
function updatePage(/* arguments */) {
jQuery.get("/your/url", {foo: "bar"}, function(data) {
// Update the page accordingly ...
if (/* continue updating the page? */) setTimeout(60000 /* 60 seconds */, updatePage);
});
}
If you want some more specific help, don't hesitate to be more precise as to what your issue is.

Related

Can I use ActionCable to refresh the page?

I've recently been trying to create a live-scoring system for squash matches. I've managed to use ActionCable with Rails 5 to auto-update the score on the page, but I'd like to know if it's possible to tell Rails to refresh the page if a certain condition is met.
For example, if the game has finished, a different page is shown to say that the players are having a break between games. I need the page to refresh completely for this to happen.
In my database the boolean 'break' is marked as true when a game ends, and then the view uses a conditional if/else statement to decide what to show.
The code I use to update the score is attached below, I was thinking something along the lines of if data.break == true then the page will automatically refresh.
// match_channel.js (app/assets/javascripts/channels/match_channel.js)
$(function() {
$('[data-channel-subscribe="match"]').each(function(index, element) {
var $element = $(element),
match_id = $element.data('match-id')
messageTemplate = $('[data-role="message-template"]');
App.cable.subscriptions.create(
{
channel: "MatchChannel",
match: match_id
},
{
received: function(data) {
var content = messageTemplate.children().clone(true, true);
content.find('[data-role="player_score"]').text(data.player_score);
content.find('[data-role="opponent_score"]').text(data.opponent_score);
content.find('[data-role="server_name"]').text(data.server_name);
content.find('[data-role="side"]').text(data.side);
$element.append(content);
}
}
);
});
});
I don't know if this sort of thing is possible, and I'm not much good at anything Javascript related so I'd appreciate any help on this.
Thanks.
Reloading the current page is relatively straightforward. If you are using Turbolinks, you can use Turbolinks.visit(location.toString()) to trigger a revisit to the current page. If you aren't using Turbolinks, use location.reload(). So, your received function might look like:
received: function(data) {
if (data.break) {
return location.reload();
// or...
// return Turbolinks.visit(location.toString());
}
// your DOM updates
}
Either way is the equivalent to the user hitting the reload button, so it will trigger another GET, which calls your controller and re-renders the view.

Alternatives to using a submit button with jQuery

Currently I am using a ajax post back to pass data to a my controllers, wherein I do my magic from there. The problem I am having right now is that we have removed a submit button and instead attached a handler using .keyup(), on a smaller database this works great! However when moving it to a larger database, as you might of guessed, it causes all sorts of issues, from delayed responses to crashes etc. So it won't work. My question to stack overflow would but this: What's a user-friendly version to submit a form?
Since the front end user could potentially be searching for single character values (e.g 6 as in userid 6) I can't limit it to a minimum character submission. We don't want a delay timer as that could back fire in a couple different ways. so basically I've ruled out .delay(), .blur(), and .keyup().
If your requirement is to not use a submit button but rather process the input as the user types then I have used solutions like this in the past.
First define a function to manage the delay, something like this:
var inputDelay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
Then for your actual ajax-call do something like this in your onkeyup event:
inputDelay(function () {
//AJAX-call goes here
}, 400)
Please note that this is not a universal solution for handling the order of responses from the server though. You might very well get several AJAX requests sent to the server and this code does nothing to make sure you only handle the latest call.
The best way to handle your situation would be to use a form, complete with a submit button. You would then add your event listener to the submit event of the form, cancel the post-back, and then do your processing. This would handle both the user clicking the submit button as well as pressing the enter key from inside the form.
I had the same issue as you.. What I did is the following:
I used on keyup.. and I fire the search if the user stayed still for .. say 300 millisecond or 500 millisecond..
While the user is typing I clear and reset the setTimeout().. so if the user stayed still for the timeout time the search will fire.
Additionally you can take the reference of the xHR object and cancel it if another request was to take place..
Do I understand your question correctly? if you need a written example I can write you a fiddle.

History.js getState() at pageload

I'm a little confused about how History.js works at page-load. I've done a few experiments but the results seem indeterministic.
My website is a search engine and the query is stored in the URL parameters: ?Query=cats. The site is written purely in javascript. History.js works great when I do a new search, the new query is updated, and the state is pushed.
My problem is how to create an initial state if the user manually enters in a URL including a Query parameter. Every way I try to do this ends up resulting in running the search query twice in some case. The two use-cases that seem to conflict are:
User manually enters URL (mydomain.com?Query=cats) into address bar and hits enter.
User navigates to an external page, and then clicks the back button
In both cases, the javascript loads, and therefore looks to the URL parameters to generate an initial state.
However, in the second case, History.js will trigger the statechange event as well.
Necessary code:
History.Adapter.bind(window,'statechange',function() { // Note: We are using statechange instead of popstate
var s = History.getState();
if(s.data["Query"]){
executeQuery(s.data);
}
});
and in $(document).ready I have
// Get history from URL
s = getQueryObjectFromUrl(location.href);
if(s["Query"]){
History.pushState(s,'',$.param(s))
}
Is there a better way to handle creating an initial state from URL parameters?
As I had a similar problem to to yours, what i did was to define the function bound to a statechange as a named function, and then all I had it running when the page load as well.
It worked better than trying to parse the URI or anything else, hope it helps.
This is the way I chose to do it (based on Fabiano's response) to store the initial state parameters
var renderHistory = function () {
var State = History.getState(), data = State.data;
if (data.rendered) {
//Your render page methods using data.renderData
} else {
History.replaceState({ rendered: true, renderData: yourInitData}, "Title You Want", null);
}
};
History.Adapter.bind(window, 'statechange', renderHistory);
History.Adapter.onDomLoad(renderHistory);
Of course if you are using a different on DOM load like jquery's you can just place renderHistory(); inside of it, but this way doesn't require any additional libraries. It causes a state change only once and it replaces the empty initial state with one containing data. In this way if you use ajax to get the initData inside the else, and it will not need to get it the next time the person returns to the page, and you can always set rendered to false to go back to initial page state / refresh content.

Continually check for an Oracle record at page load

I basically have a page that when loads, reads an Oracle SQL table for a specific record id that may not currently exist at the point as it may take up to a minute to insert this specific record into the table.
Based on this, I need a means of showing a "Loading Image" while it waits for the record to exist, so has to wait. Once it does, I want to remove the loading image and present the user with the record details. I am using Oracle Application Express 4.2 for this.
My question is not so much the loading/hiding of the image but how to continually check for the record within the Oracle table, during page load.
Either I receive the record successfully and then hide the image or say after 1 minute, I dismiss the checking of the record and present the user with a message indicating that no record was found.
Sorry for my english. I will try help you.
Make your "Loading image" always visible on the page. There is no need to show it on load, you only need to hide it at proper moment.
Add Application Process to your application. Name it for example "GET_MY_ROW". Process must check your event, and return some flag, for example 1 or 0.
Example:
declare
l_cnt number;
begin
select count(*)
into l_cnt
from table1 t
where id = 12345;
if l_cnt > 0 then
htp.p(1);
else
htp.p(0);
end if;
end;
3.3 Add javascript code as page load event (for example by Dynamic Actions):
Javascript code:
var myInterval = setInteral(function {
var get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=GET_MY_ROW',$v('pFlowStepId'));
get.GetAsync(function(pRequest) {
if (pRequest.readyState == 4) {
if (pRequest.responseText == 1) {
alert('Record loaded successfully');
// add function call, hiding your "Loading image" here
clearInterval(myInterval);
}
};
});
get = null;
}, 5000); //check every 5 seconds
setTimeout(function() {
alert('Sorry, no record was found. Try again later.');
clearInterval(myInterval);
}, 60000); // fail after 1 minute
Since NoGotnu already answered, I'll put this here:
Is there any reason for the procedure to be called through a job? Is it the only way to create the required record? Is the job called anywhere else? Why not call the procedure directly when the required page has been submitted and show the loading icon there? When it finishes, the user knows it has finished. That would involve a lot less fiddling around as you can make apex show a processing graphic on page submit. You could then just inform the user on the other page that the process has not been ran yet and they'd have to do that first.
Secondly, while NoGotnu's answer will work, I'd like to point out that in apex 4.2 you should use the apex.server namespace instead of the never documented htmldb_Get construction. apex.server.process is a clean implementation of the jQuery ajax setup.
NoGotnu's code translated:
apex.server.process( "GET_MY_ROW"
, null
, { dataType: text
, success: function(pData){
if (pData == 1) {
clearInterval(myInterval);
alert('Record loaded successfully');
};
}
}
);
The call doesn't really need to be async though, but ok.
Another option would be to implement a "long poll" instead of firing the ajax event every 5 seconds. A long poll will just initiate a call to the server and wait for a response. As long as the server is busy, the client will wait. To achieve this you could use dbms_alert, as suggested in Waiting for a submitted job to finish in Oracle PL/SQL?
You'd signal an alert in the plsql code of the job, and in the ondemand process code register an interest in the alert and use waitone/any with a 60 second timeout. Presto long poll.

Asynchronous AJAX Calls in orderd manner

Hi firstly sorry for my bad English. I Already searched in SO. but i didn't get the exact answer i needed.
My issue is i need to synch the Ajax request. i know we can use the "asynch : false ".
but this will make browser locked. I have a folder tree(i am using "tafel tree" js) in my web. the tree nodes are generated at run-time. each time
user click a node it will send request to server and add the node to the tree.
but issue is if the page is refreshed by clicking f5 then i need to load the tree structure that i already selected previously.
i implemented it using "asynch : false ". but this will makes browser too slow.
and here what i have
function loadPage() {
/* some other codes are here*/
/* here i call an ajax for get the inside folder list in correct order.(i am usig protoype)*/
new Ajax.Request(ajaxGetInsideFolderIdsUrl,
{
parameters: {branchId: CurrentSelectfolderId},
onSuccess: function(res) {
/* onSuccess i call another function*/
var brs = res.responseText.split(","); // branch ids in correct order.
syncFolder(brs)
}
}
function syncFolder(brs){
for(var i= 0 ; i < brs.length; i ++){
var tempbranch = tree.getBranchById(brs[i].getId());
selectAfterChange( tempbranch)
/*
selectAfterChange function is used for selecting current branch. calling "tafle tree" select() function in side it.
i just created an copy of "select()","_openPopulate()" functions used in "tafle tree" and modified it with "asynch : false ".and now its working fine.
*/
}
}
function selectAfterChange(brs){
brs.chk_select();
/* for selecting the branch (created a copy of current "select()" function used in "tafle tree" js
and modified it with "asynch : false "and now its working fine.) */
showList();// for listing items in side that folder (in another Ajax page).
}
My problem is if a user opened a long branch.
And then refresh the page it will take too much time to load because of synch Ajax call.
Taking too much time is not an big issue to me. but the browser is get locked until all the request executed.
is there any other way to do this.
I'm not familiar with the tree library you're using, but in general, the way you'd solve this is to store the currently expanded path(s) in the browser (local storage, or cookies, or wherever), and when you refresh the page, load just the nodes that are visible.
Let's say that the user is currently looking at path one/two/three/four. You save that path somewhere, and then when the page loads again, you create a queue of paths to request from the back end, by splitting the path, and appending the components of the path one by one:
["one", "one/two", "one/two/three"]
You then send the AJAX request for "one", and when you get the result back, update that node in the tree, and send a request for "one/two". When that request returns, update the tree, and send the request for "one/two/three".
Depending on your design, you can then start filling in the rest of the tree with more async requests...

Categories

Resources