How to update web page multiple times as server-side task progresses? - javascript

I would like to create a page that will allow the IT guys to select some servers from a list and an operation to perform on the them and then click go. Then have the textarea on the page update with the status of each operation as it completes. Each server maintenance task can take a minute or two. They would like to see updates on the page as each server completes the selected task.
Not sure which technologies to use on the front-end. The back-end is not a problem at all. I can easily take the full list of servers, perform the operation on each server then return the full list, with the result from each server. However, no one wants to wait for all the servers to complete before getting updates.
Normally I would use ajax to update a portion of a page but that is just for a single call/response. I think if I use a javascript loop to call a php script via ajax for each server, then the javascript loop will block the UI updates until the javascript function completes.
Any ideas?

Jquery has a method to perform an asynchronous HTTP Ajax request (http://api.jquery.com/jquery.ajax). Create a recursive javascript function to make the ajax call. Once you get the list of servers and desired operation selected by the user on the UI, call the RecursiveAjax function. With each result, call another function to update the UI.
function RecursiveAjax(serverArray, currentIndex, operation)
{
var operationResult = "";
$.ajax({
type: "GET"
url: "ServerOperation.php",
data: {Operation: operation, Server: serverArray[currentIndex]},
success: function (result) {
operationResult = JSON.stringify(result);
UpdateUI(operationResult);
}
});
var nextIndex = currentIndex + 1;
if(nextIndex < serverArray.length) {
RecursiveAjax(serverArray, nextIndex, operation);
}
}

You can use two technologies for this.
1- websocket https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications
2- push notification https://developers.google.com/web/fundamentals/engage-and-retain/push-notifications/
In websocket the browser tab has to stay open. In push notification not. Websocket supports many browsers, push notification is only chrome and chromium.

Related

How to send request to another page and let the second page grab the request and do something

I wanted to program a sort of panel from where i can send command to user For a live game that came to mind using jquery, javascript and php.
I take as a reference for every user using SESSION of php.
The initial user will have a
setInterval(function(){
var xml = new xmlHTTPRequest();
xml.open('GET','http://samepage.php?data= I don't know',false)
xml.send()
if(xml.responseText=="color"){
hideloader();
ShowFavoriteColorForm();
}
}, 3000);
The point is that I can't figure out how to use ajax to do a function that is waiting for something from another page (a string for example) and then perform other operations.
If there were examples or documentation in this regard, thank you very much.

Stop AJAX XHR call but still continue with PHP

Good afternoon,
I have the following functions that shows and hides a page busy loader:
busyStatusDelay = 1000; //milliseconds
var timer = null;
var show = false;
function busyShow(nodelay,delay) {
timer = setTimeout('busyDelayShow()',busyStatusDelay);
}
function busyDelayShow() {
if ($.active > 0) {
$('#json-overlay').css('display', 'table');
show = true;
}
}
function busyHide() {
clearTimeout(timer);
timer = null;
show = false;
$('#json-overlay').css('display', 'none');
}
This works great for normal ajax queries, we however have a new function that should send emails with SMTP, but this SMTP connection takes a few seconds too long to connect and send the emails.
To avoid this I want the ajax function to not trigger this loader, the function does not call the function to open the loader, but the issue is that when another function gets called that should open the loader, it picks up that there is an active connection so the loader comes back up and does not go away.
I tried to use the following so that the JS does not see it as an active request:
xhr.abort(); busyHide();
but when the ajax gets aborted the php aborts with it.
Note that the functions to send the emails should run in the background and should not wait for a response.
I have been searching for a way to disconnect from the server request without affecting the server's functions running and send the email.
I saw ignore_user_abort in another post so will be doing some reading up on this to see if this will work without affecting the rest of the system.
Thanks in advance for any tips on how to continue!
A good approach to this would be to execute your SMTP as a background process using some sort of queuing mechanism. So basically, whenever a JS triggers AJAX to mail, the PHP push the email request to a queue and send a response back to the XHR immediately. This way, your AJAX execution won't be blocked for long.
If you are using some sort of PHP framework like Laravel, it makes easier to manage queues otherwise have a look at this post.

How to submit value to database with jquery?

so basically i want to make a webpage to detect how many times user clicked on it and send that value to database. I know i should use ajax but just can't figure out how to use it.
var count = 0;
$("body").click(function() {
$("#track").text("you clicked " + count + " times");
count++;
});
$.ajax({
url: "index.html",
cache: false,
success: function(html){
$("#results").append(count);
}
});
Assuming the following things. You:
have AMP Stack installed with PHP & MySQL.
have a working DataBase in MySQL (most commonly used with PHP).
are running the web server and looking at HTTP version and not file version in Chrome.
I would go by this method:
On load, I'll get the current count from DataBase using a PHP backend.
In the PHP backend, I'll write a code to query MySQL and get the current value.
Use a single file, say count.php as a file to get and set the counts.
Using GET method, the file responds with the count.
Use an AJAX code and get the count data.
Using jQuery with the AJAX's response, update the DOM with the current count.
Once you load the page and update the value, set the event listener on click.
Update the current count in the UI by adding one more.
Use the same code as you have to update the UI to increment the count.
Fire a POST request using AJAX to the count.php and send the new value.
In the count.php, write an UPDATE query to update the count.
Send a success message.
When you reload the page or look at the database, the count will be preserved.

how to monitor instance variable from ruby controller pass to view html using AJAX

Hi I want to create a page where it monitors(view) or render the value of the variable inside the controller dynamically as the iteration of variable goes by.
view.html.erb
<a id='get_value' class="btn">Run</a>
<ul id="value_variable_from_controller"><ul>
<script>
var getTheValue=function(){
$.ajax({
type:'GET',
url:'/run/results',
success:function(data,status){
<!--how to dynamically UPDATE the value_variable_from_controller?-->
alert("Successfully");
}
});
}
$(document).on("click","#get_value",getTheValue);
</script>
And here's my controller where i iterate the value of x,
results.rb
x=0
5.times do
x++
sleep(1)
#HOW TO RETURN THE VALUE OF VAR X EVERY UPDATE?
#render :json => x, :status => :ok #do i need to have a loop in js?
end
Many Thanks.
If I understand you correctly you want to update the value in the HTML document every time it is updated on the server, correct? There are ways to accomplish this, although the transitioning of state between client and server is usually initiated by the client. 1
To combat this, websockets are currently the most popular approach - basically opening up a two-way communication pipe between the client and the server. Of course, for your simple example this might be overkill (unless you require heavy real-time interactions between the client and the server - then it's certainly worth taking a gander at) - and something like polling might be more suitable (which is indeed initiated by the client), although it will generate a large number of requests.
You might also consider long polling which only opens one connection.
Polling is a technique in which the client calls the server requesting data at a certain interval, which would work for your situation. From the code you posted it also seems like you want it to be possible to fetch the value by clicking on the #get_value link, which can utilise the same method as the long polling service. Here's an example:
// in your view/javascript
$(document).ready(function() {
function getValue(trigger) {
$.ajax({
type: 'GET',
url: '/run/results/',
success: function(data, status) {
$('#value_variable_from_controller').text(data.x);
if(trigger) {
setTimeout(getValue(true), 1000); }
}
)} // end AJAX
} // end getValue
// binding the action to your link as well
$('#get_value').on('click', function(event) {
event.preventDefault();
getValue(false);
});
// start the polling
getValue(true);
});
# in your controller
#x = 0 # initial value
def results
#x++ # increment every time this action is called
render #x.to_json
end
This way the client initialises the data flow, and the server mutates state in response to a client request - which is the norm in a client/server architecture.
1 The client–server characteristic describes the relationship of cooperating programs in an application. The server component provides a function or service to one or many clients, which initiate requests for such services. (http://en.wikipedia.org/wiki/Client%E2%80%93server_model)

jquery two ajax call asynchrounsly in asp.net not working

I developed an web application in asp.net. In this application I have used jquery ajax for some pages. In this application, when I make two ajax call asynchronously that would not do as I expected. what is happening is even the second ajax call finishes I can see the result when the maximum time out ajax call finished. I mean I can see the both results in the same time, not one by one.
for an example. I have 3 pages
main.aspx - for make two ajax request.
totalCount.aspx - to find the total count.
(max it takes 7 seconds to return, as corresponding table contains 300k records)
rowCount.aspx - to find the row details. (max it takes 5 seconds to return result).
due to this scene, I have planed to make asyn call in jquery ajax in asp.net.
here is my code:
function getResult() {
getTotalCount();
getRows();
}
// it takes max 7 seconds to complete
// as it take 7 seconds it should display second.( I mean after the rows dispaying)
// but displaying both at the same time after the max time consuming ajax call completed.
function getTotalCount() {
$.ajax({
type : "POST",
async : true,
url : "totalCount.aspx?data1=" + document.getElementById("data").value,
success : function(responseText) {
$("#totalCount").attr("value", responseText);
}
})
}
// it takes max 5 seconds to complete.
// after finished, this should display first.( i mean before total count displays)
// but displaying both at the same time after the max time consuming ajax call completed.
function getRows() {
$.ajax({
type : "POST",
url : "getrows.aspx?data1=" + document.getElementById("data").value,
async : true,
success : function(responseText) {
$("#getRows").attr("value", responseText);
}
});
}
I would like to know, If there is any possible to make asyn call in jquery ajax in asp.net.
I searched in net, I got some points that says we cannot do this in asp.net
ref link: http://www.mail-archive.com/jquery-en#googlegroups.com/msg55125.html
if we can do this in asp.net How to do that?
I'm not a asp.net developer but in general ajax terms I can explain this issue as given below
As ajax stands it is asynchronous, so you to expect the two request in some particular oder will not be wise.
The timings given by will be the time taken by the db server to execute some queries but there are more to the request like network traffic etc, so your assumption that 1 request will return before other is not correct.
The .NET session state will cause all requests for a particular session to be queued up.
If session state is not required, you can disable it.

Categories