Here is a 'hypothetical' situation.
Let's say I have :
a websocket who tell's me to send a ajax on a url like http://localhost/Whatever every 10 sec.
The ajax call on http://localhost/Whatever will take 45 seconde to reply (exagerate number for the situation).
I wonder how will the browser react? in my mind 3 case:
(good one): Browser is really smart : He understand we ajax
the same url so he won't stack ajax call until the current call
finished.
Browser understand we ajax the same url and make an abort() on the
Ajax 1st call and start a new one (if the browser really does that, it
would be rubbish in my mind).
(worst case): Browser send a ajax on the url each time websocket ask
him to and wait for the answer. Moreover, I suppose there will be a
problem with limitation of parralel ajax request? (i wonder how the
browser if this case happens ?)
So, Which case will happen and why ?
The answer is case 3.
The browser will send all requests in the order you make them. Generally speaking a computer will carry out your instructions in the order your issue them. If you want or need special behavior such as throttling the rate of the requests or not sending the subsequent requests until prior ones have finished you will need to implement that your self.
Imho, this pseudocode might help you.
var requestLock = false;
function pollFromSocket() {
if (someCondition) {
sendRequest();
}
}
function sendRequest() {
if (requestLock) {
return;
}
requestLock = true;
$.get('/whatever')
.done(function(response) {
// process response
})
.always(function() {
requestLock = false;
});
}
Related
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.
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.
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.
I have a simple social networking site with chat functionality. I have used $.post a lot in multiple pages.
The code works well on all pages except message.php where the user message is posted and fetched multiple times with
$.post
(used to work well on local server).
When the messaging between users occur simulateously, the website stops to respond. On reload, the server goes down and ERR_EMPTY_RESPONSE message is shown. The website again comes into operation after a couple of minutes. To what I learnt, this is happening on pages that use $.post frequently.
To summarize the situation, I have created a live test page. An ERR_EMPTY_RESPONSE occurs when input is given continuously for some seconds.
The page contents:
a.php
<script>
$(document).ready(function(e) {
$(".abc").keyup(function(){
var a = $(this).val();
$(".showoff").text("wait..");
$.post('bbs.php',{a:a},function(abc){
$(".showoff").html(abc);
});
});});
</script>
<input type="textbox" class="abc">
<div class="showoff">Type to Change Me!</div>
bbs.php
<?php
echo $_POST['a'];
?>
I am hitting my head hard on the wall for a week. So, Please help me with this problem.
Thanks in Advance.
Sorry for my lame English as well.
As you appear to want an autocomplete type setup, use a timer. Reset it on each keypress and after a delay send your post. In this example it will send 3 seconds after the last keypress.
$(document).ready(function(e) {
var timer;
$(".abc").keyup(function() {
var $input= $(this);
// Start timer
clearTimeout(timer);
// Start a new 3 second timer
timer = setTimeout(function() {
// Once the
var a = $input.val();
$(".showoff").text("wait..");
$.post('bbs.php', {
a: a
}, function(abc) {
$(".showoff").html(abc);
});
}, 3000);
});
});
JSFiddle: https://jsfiddle.net/TrueBlueAussie/Locpnk35/
This will avoid overloading your server as no more than 1 request every 3 seconds can come from the same user. If the response is slower than 3 seconds you may also need to disable the key handler while an Ajax request is in progress.
Simplest answer would be you allow your server to be spammed to the point that it stops responding (yet still recieving new connections). If the connections are not closed(resolved) in time you will also hit limitation of concurrent browser connections to domain (which I think is really happening - browser blocking you in making those request).
You either switch to sockets, or send text to server on set interval of time. Alternatively you dont allow next post, till previous is resolved.
Instead of allowing your server to be spammed, you can remove the handler before the first post and set it back again when the post returns.
$(document).ready(function(e) {
var $abc = $('.abc'); //good idea to cache those jQuery selectors!
function abcPost() {
$abc.off('keyup', abcPost)
var a = $(this).val();
$(".showoff").text("wait..");
$.post('bbs.php', {
a: a
},
function(abc) {
$(".showoff").html(abc);
$abc.on('keyup', abcPost)
});
}
$abc.on('keyup', abcPost);
});
Ajax syncronous: Make the ajax call syncronous. This will stop its thread untill the response is back, easy to implement but comes with the downside that the user cannot type anymore untill request is solved
$.ajax({
url: 'bbs.php',
data: {a:a},
success: function(abc){
$(".showoff").html(abc);
},
async: false
});
Global variable check: make a global variable that checks the state of previous request and doesn't allow future ones until it is resolved:
var waiting=false;
$(".abc").keyup(function(){
if(!waiting){
waiting = true;
// code
$.post('bbs.php',{a:a},function(abc){
$(".showoff").html(abc);
waiting=false;
});
}
});
This is good.
var waiting=false;
$(".abc").keyup(function(){
if(!waiting){
waiting = true;
// code
$.post('bbs.php',{a:a},function(abc){
$(".showoff").html(abc);
waiting=false;
});
}
});
Is there any way to get the http status of the current web page from javascript?
Spent some time searching on the web, but no luck at all... Seems like it's not possible, but wanted to check with Stack Overflow for maybe some fancy workaround.
(Providing it from the server as part of the response body is not acceptable, the status is supposed to be only available via the http header)
This is not in any way possible, sorry.
Yes You can
Simply request the same page, i.e. URI, using the XMLHttpRequest. Suppose that your page on /stop.php in stop.php you may do something like:
<script>
function xhrRequest(){
console.log(this.status);
// Do some logic here.
}
function getReq(url){
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", xhrRequest);
oReq.open("GET", url);
oReq.send();
}
getReq("/stop.php");
</script>
Checkout this DEMO
🕯 Note:
You have to note that, it is a copy of the page not the page itself.
I, already, have used this solution on a page in which the server may
generate Forbidden HTTP status code when the request is come from
unauthorized IP address, so the condition here is very simple and
there is no much difference between the original and the copy page
that you have simulate its visit.
As a one liner:
fetch(location.href).then(response => console.log(response.status));
This is asynchronous, if you need a synchronous solution use XMLHttpRequest (as in the other answer) together with async: false or use async/await which feels synchronous, but is still asynchronous under the hood.
Alternatively
An approach without an extra call would need to include the status code in the page on the server side (e.g. in a meta tag), then read it on the client side via JavaScript.
Java + Thymeleaf:
<meta name="statuscode" th:content="${#response.status}">
PHP (unverified):
<meta name="statuscode" content="<?php echo http_response_code() ?>">
It is not beautiful, but you can use:
t = jQuery.get(location.href)
.success(function () { console.log(t.status) })
.error(function() { console.log(t.status) });
That When Eric says, this solution will make a new request from the same paga, and not show status of current request.
you can only check status of page loading
try:var x = document.readyState;
The result of x could be:
One of five values:
uninitialized - Has not started loading yet
loading - Is loading
loaded - Has been loaded
interactive - Has loaded enough and the user can interact with it
complete - Fully loaded