XMLHttpRequest Flashcards

1
Q

When do you use Get vs Post

A

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

  • A cached file is not an option (update a file or database on the server).
  • Sending a large amount of data to the server (POST has no size limitations).
  • Sending user input (which can contain unknown characters), POST is more robust and secure than GET.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you avoid cached results on a GET request?

A

Send a random number as a query parameter the URL

xhttp. open(“GET”, “demo_get.asp?t=” + Math.random(), true);
xhttp. send();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you send data with a GET request?

A

As query parameters on the URL

xhttp. open(“GET”, “demo_get2.asp?fname=Henry&lname=Ford”, true);
xhttp. send();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you POST data?

A

To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method:

xhttp. open(“POST”, “ajax_test.asp”, true);
xhttp. setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
xhttp. send(“fname=Henry&lname=Ford”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you handle the response from an AJAX request?

A

With the XMLHttpRequest object you can define a function to be executed when the request receives an answer.

The function is defined the in the onreadystatechange property of the XMLHttpResponse object:

xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(“demo”).innerHTML = this.responseText;
}
};
xhttp.open(“GET”, “ajax_info.txt”, true);
xhttp.send();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How does jQuery’s ajax method work?

A
$.ajax({
   type: 'POST',
   url: $('#myForm').attr('action'),
   data: $('#myForm').serialize(),   // I WANT TO ADD EXTRA DATA + SERIALIZE DATA
   success: function(data){
      alert(data);
      $('.tampil_vr').text(data);
   }
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly