How to show loading message while sending angularj http request - javascript

I want to show a loading message while sending http request and hide loading on request complete, and i want to use this for all the http request. Is there any global function in angular to do this..

A JavaScript HTTP request will not block and you will provide a callback which is called when the request is complete. This means that you could do this (pseudocode, since you didn't provide example code):
function callback(httpResponse) {
hideLoadingMessage();
dostuffWithResponse(httpResponse);
}
// callback is callled when HTTP request is complete
doHttpRequest(params, callback);
// the code after continues to execute despite the HTTP request not being ready
showLoadingMessage();
So the code execution continues after the HTTP request is sent. The callback will be called when the HTTP request is complete. In practice you need to also handle errors.

Quick Google search returned a fair amount of results for Angular:
Loading spinner you can implement onClick.
http://ngmodules.org/modules/angular-loading-spinner
Previously asked question with similar circumstances:
Showing Spinner GIF during $http request in angular
And finally, codepen.io examples (might be broken now though)
http://codetunnel.io/how-to-do-loading-spinners-the-angular-way/
I would highly recommend trying before asking in future. We need code examples of what you've tried or where you are at right now. This isn't a simple piece of code unless you're using a plugin (which you could have found yourself).
I'd recommend in future, try providing some context and examples.

Related

jQuery $.get() is blocking other requests

I'm developing a web application and use jQuery to make asynchronous HTTP requests to my API. I have a detail view where you can see a lot of information of a specific object stored in the database. Because there is a lot of information and data that is linked to other objects, I make different calls to my API to gather different information for my views.
In the 'detail view' I have some kind of widgets that show the requested information. For that, I make about 5-7 HTTP GET requests to my API. When using the debugger (both Safari and Firefox), I can see that some requests are blocking other requests and the page takes a lot of time until everything is loaded and shown to the user.
I make a request like this:
$.get("api/api.php?object=myobject&endpoint=someendpoint", function(data) {
// data is JSON formatted
$("#my-widget input").val(data["name"]);
});
And another one e.g. like this:
$.get("api/api.php?object=anotherobject&endpoint=anotherendpoint", function(data) {
// data is JSON formatted
$("#other-widget input").val(data["somekey"]);
});
If the first request takes a little longer to finish, it blocks the second request until the callback function of the first request finished. But why? I thought that those calls are asynchronous and non-blocking.
I want to build a fast web application for a company where the requests are only made inside the local network, so a request should only take about 10-50ms (or even less). But the page takes about 10 seconds to show up with all information.
Am I doing something wrong? Or is there a JavaScript framework that can be used for exactly this problem? Any help is appreciated!
EDIT: As you can see in the screenshot, the requests have to wait some seconds, and if the request is fired, it takes a few seconds until a response comes back.
If I call the URL directly in my browser or do a GET request using curl it is a lot faster.
EDIT2: Thanks #CBroe! The session file write lock was the problem. As long as the session file is locked, no other script can run until the previous script finished. I just called session_write_close() immediately after session_start() and it runs a lot faster now.
Attention: Use session_write_close() only if you don't need to write to the $_SESSION array. Reading is possible after that, but writing not. (See this topic for further details: https://stackoverflow.com/a/50368260/1427878)

At what point in a function call is an AJAX request actually initiated by the browser?

Let's say I have a function that does a standard AJAX request:
function doXHR() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts');
xhr.send();
xhr.onreadystatechange = () => {
console.log('ready state change');
};
}
doXHR();
console.log('done');
This code will cause the browser to start an AJAX request, but at what point in the function does the request actually start? According to this post: https://blog.raananweber.com/2015/06/17/no-there-are-no-race-conditions-in-javascript/
[Calling xhr.onreadystate() after send()] is possible, because the HTTP request is only executed after the current scope has ended its tasks. This enables the programmer to set the callbacks at any position he wishes. As JavaScript is single-threaded, the request can only be sent when this one single thread is free to run new tasks. The HTTP request is added to the list of tasks to be executed, that is managed by the engine.
But when I add a breakpoint in devtools right after the send call:
I do get a network request, albeit in a pending state:
At the breakpoint, the XHR's readystate is 1, which is XMLHttpRequest.OPENED. According to MDN's documentation, XMLHttpRequest.OPENED means that xhr.open() has been called: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
But if I comment out xhr.send() so that only .open() is called:
Then I get no pending network request:
Thinking that perhaps I need the function scope to end in order for the request to actually be sent out, I moved the breakpoint to after the function call (and modified the code a bit to see the XHR readyState):
But I still get the pending network request:
It seems like the debugger not only freezes code execution, but also any network requests. This makes sense, as you don't want network requests to complete while you're on a breakpoint, but this also makes it impossible to tell when the network request is actually initiated.
My question is, at what point does the request actually get sent out? Does calling xhr.send() merely set up the request, but requires that the function scope end before the request is initiated? Does xhr.send() immediately initiate the request before the function scope ends? Or is there something else going on here?
send immediately initiates the request. This is at least hinted at by MDN's documentation for send.
The author of the blog you link to is correct that there are no race conditions per-se, but that does not keep you from having things happen out-of-order. An example of this would be if you load multiple <script> tags in with the async=true set on them. In this case, if one script depends on the other, you could end up in a situation where you have an unpredictable sequence of events (which is very similar to a race condition) because two asynchronous events finish at different times.
It is true that you can set onreadystatechange after calling send because even if the request request failed immediately, the event won't get dispatched until the function scope completes. The delay here is not in the dispatching of the network request, but in the dispatching of the event to say that the network request completed.
It is important to note, that networking itself is not handled in JavaScript, but rather by the browser implementation, which is native code, and could be multi-threaded (although I do not know if it is). This means that the browser is perfectly capable of handling network tasks while your javascript is running.

Show "In Progress" during http request (long running) execution in javascript/jquery/php

I would like to have "Loading.." / "In Progress.." message during regular http request. This should be shown only during the http request cycle, and once you get the request is completed and you get the response, it should go off. I am keen about regular HTTP Request, and HTTP Request that take longer time and not AJAX. Code blocks, examples, pointers appreciated. Here is one approach, I would like to have common approach, so that it can be used for any http request.
You should use beforeSend and complete events:
$.ajax({
...
beforeSend: function(){
//Here you loading SHOW
},
complete: function(){
//Here you loading HIDE
}
...
});
Basically when executing a normal HTTP request (not AJAX), the client browser already provides a progress indicator. This indicator will vary between browsers and platforms and you cannot rely act on it.
Your javascript stops working once you navigate away from the page so don't look for a javascript solution to show such progress indicator. Depending on how this HTTP request is triggered there might be different ways to achieve that. For example if you have an anchor tag in your markup that triggers a normal HTTP request, you could subscribe to the click handler of this anchor and show an animated spinner using javascript and then let the browser do the redirect.
And as far as AJAX requests are concerned you could subscribe to the .ajaxStart() and .ajaxComplete() global handlers to respectively show and hide some spinner.
Of course everything will depend on the implementation. There's no magic solution that will handle all the possible cases. So basically you will have to find a solution that's adapted to your specific context which unfortunately you haven't detailed.
You could have an element on the page that gets hidden once the page has been fully loaded. E.g.:
<img id="loading" src="loading.gif" alt="Loading..." />
<script type="text/javascript">
$(function() {
$('img#loading').hide(); // Called when whole page has been loaded
});
</script>
I think it is not possible to render any information during pure javascript HTTPRequest synchronous call (not the case in JQuery). If you change a style, class.. just before calling the send method, this info will not be rendered.
To fix this issue, I changed call to asynchronous call, then the style, class .. changes can be rendered before the call returns (using onreadystatechange to get the result and reset style)

Ajax Requests Chaining/Nesting?

I'm writing a script that uses Ajax. The script will call an API, and then use that data to call the API again, and then based on that a final request to the API a third time.
Currently the Ajax requests are chained, so if response status is 200, it will perform the other Ajax request and if that one is 200 it will do another. So basically nested requests.
They are asynchronous requests. Is this the correct way to do this? I cant help but think its a little messy, and wrong.
With ajax request, chaining them with callbacks is the right way... its the best way to make sure the second call initializes only after the first one finished successfully.
asyncCall1( function(){
asyncCall2(function(){
asyncCall3();
})
})
On javascript-side I would say it's a correct way.
But on API-side instead of multiple requests your api could/should be able to respond with the end-result (or merged results) on the first request, when the following requests are just based on data retrieved by previous requests.

From ELements Loaded or not?

Hi I make randomly calling multiple ajax calls.how i can check all ajax calls are completed and values get loaded in combox and multiple boxes,PLease give any solution other than ajax status,Any javascript event which triggers when all elements loaded???,I tried prototype document.observe("dom:loaded", function() but its not working for ajax calls
how i can check all ajax calls are completed and values get loaded in combox and multiple boxes,PLease give any solution other than ajax status
Why? What's wrong with using the AJAX request status, which is the canonical way to determine the status of the request (and thus success or failure)?
There might be a legitimate reason for this restriction (though at first glance it appears not), but if so then it's because you're doing something unusual, such as making requests that you expect to "fail". If this is the case, then you'd need to make clear exactly what the constraints are anyway.
Failing that, just check the status and ensure that the remote server is returning the right status for requests (if it's under your control).

Categories

Resources