Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d996808

Browse files
author
AbdulRahmanDbes
committed
Add an explanation about XHttpRequest
1 parent f25a05a commit d996808

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

Week5/REVIEW.MD

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,53 @@ this review covers:
1111

1212
## Callbacks
1313

14-
- JavaScript callback functions tutorial: https://www.youtube.com/watch?v=pTbSfCT42_M&index=17&list=WL
14+
- JavaScript callback functions tutorial: https://www.youtube.com/watch?v=pTbSfCT42_M&index=17&list=WL
15+
16+
## XMLHTtpRequest
17+
**XMLHttpRequest** is an objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. XMLHttpRequest is used heavily in Ajax programming. - [MDN](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)
18+
19+
So what is Ajax?
20+
**Ajax** is a method of exchanging data with a server, and updating parts of a web page without reloading the entire page.
21+
22+
Let's diving a bit deeply into the code:
23+
24+
First, we need to make an instance from 'XMLHttpRequest' class.
25+
```javascript
26+
var http = new XMLHttpRequest();
27+
```
28+
When we are doing a request it goes through 5 states:
29+
* 0 : request not initialized.
30+
* 1 : request has been set up.
31+
* 2 : request has been sent.
32+
* 3 : request is in process.
33+
* 4 : request is complete.
34+
35+
In the code below we are checking if the request is complete or not, and we check the status == 200 just to make sure that we do not get 404 error. - Take a look about [HTTP Status Code](https://httpstatuses.com).
36+
```javascript
37+
http.onreadystatechange = function() {
38+
if ( http.readyState == 4 && http.status == 200) {
39+
console.log(`Response from the server: ${http.response}`);
40+
}
41+
}
42+
```
43+
There are methods to deal with a server like (GET, POST, UPDATE, DELETE…)
44+
45+
* GET: to retrieve data from server.
46+
* POST: to send data to server.
47+
* UPDATE: to update data on the server.
48+
* DELETE: to delete date from the server.
49+
50+
To Initialize a request we use [open][https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open] method. The syntax is:
51+
```javascript
52+
XMLHttpRequest.open(method, url, async, user, password)
53+
```
54+
The parameters 'method' and 'url' are mandatory, 'user' and 'password' are optional. True is a default value for 'async'.
55+
56+
```javascript
57+
http.open("GET", URL, true/false);
58+
```
59+
At the end we have to send our request to the server through [send](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send) method. In our situation we are retriving a data from the server, so we do not have to pass any parameter to the send request.
60+
61+
```javascript
62+
http.send()
63+
```

0 commit comments

Comments
 (0)