Currently I'm studying JS and pretty familiar with the vanilla JS, but JQuery syntax seems a little bit weird for me. So I have the following code on JS and it works just fine:
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
questions = JSON.parse(this.responseText);
loadQuestionsData();
}
};
xhttp.open("GET", "http://localhost:8080/questions", true);
xhttp.send();
Here I create new XMLHttpRequest to my localhost and get JSON of questions and when the responce is ready, the function loadQuestionsData() is executed (it inserts the list of questions into the table). I've tried to rewrite this with JQuery, but it doesn't work and I do not get why. Here is my n-th try to do this:
$(document).on('readystatechange', function() {
$.ajax({
url: "http://localhost:8080/questions",
type: 'GET',
success: function() {
questions = JSON.parse(this.responseText);
loadQuestionsData();
}
})
})
I've also tried the following, but it doesn't work too:
$(document).on('readystatechange', function() {
questions = JSON.parse($.ajax({
url: "http://localhost:8080/questions",
type: 'GET',
})).responseText;
})
I suppose the problem is with syntax? Code stops running on responseText.
The document object does not have an onreadystatechange
event - that's part of the XHR object. The jQuery AJAX methods will handle state changes for you (part of the simplicity of it).
Also, the success handler has a parameter that is the response text, so you need to add that to the function signature so you can access it in the function.
Change it to this instead...
$.ajax({
url: "http://localhost:8080/questions",
type: 'GET',
success: function(responseText) {
questions = JSON.parse(responseText);
loadQuestionsData();
}
})