Why don't both retrieve them sychronously or both asynchronously? Or, better yet, why is it not vice-versa?
-
AJAX - ASYNCHRONOUS javascript and xml... php isn't multithreaded, and since it's being invoked by http, you can't exactly just shut everything down and wait for an ajax response to arrive. exactly where would PHP GO to tell the client that a response is ready?Marc B– Marc B2015-07-27 20:03:16 +00:00Commented Jul 27, 2015 at 20:03
-
@MarcB i lold. Its good to know what things are short for.user5106417– user51064172015-07-27 20:04:50 +00:00Commented Jul 27, 2015 at 20:04
-
You 'can' do a synchronous XHR requests in JavaScript, but this is deprecated for a good reason: until the request completes the UI is blocked. This same problem occurs in all similar UI-iteraction frameworks where events are run within the same execution context (eg. 'thread'). The UI simply can't continue processing until the event code execution completes. By using an asynchronous workflow the processing is allowed to complete immediately, with events setup to handle 'things that happen later', such as the server response.user2864740– user28647402015-07-27 20:08:39 +00:00Commented Jul 27, 2015 at 20:08
2 Answers
Synchronous, single-threaded programming is almost undoubtedly easier, but it requires "blocking" the main thread during IO and other long-running tasks. When you block the main thread, nothing else happens (including handing other user input).
So, in the context of the browser, we perform network requests asynchronously to make sure that we can keep the page feeling responsive and interactive while we wait on the response.
In PHP, on the other hand, each (incoming) request gets it's own thread (or sometimes even it's own process), so there's less harm to be done by "blocking" (outgoing) network requests. It's not the most efficient solution out there, but it's far more trivial to code against, and it's "good enough" most of the time.
Comments
AJAX works asynchronously because it's normally used in an interactive application, the web browser. This allows the browser to be responsive to other user actions while it's waiting for a response.
PHP runs on the server, and doesn't directly interact with the user. So there's usually nothing else it could be doing while waiting for a response to a network request.