const d = document;
const $table = d.querySelector(".crud-table");
const $form = d.querySelector(".crud-form");
const $title = d.querySelector(".crud-title");
const $template = d.getElementById("crud-template").content;
const $fragment = d.createDocumentFragment();
const ajax = (options) => {
let {url,method,success,error,data} = options;
const xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", e =>{
if(xhr.readyState !== 4) return;
if(xhr.status >= 200 && xhr.status < 300){
let json = JSON.parse(xhr.responseText);
success(json);
}else{
let message = xhr.statusText || "Ocurrio un error";
error(`Error ${xhr.status}: ${message}`);
}
});
xhr.open(method || "GET", url);
xhr.setRequestHeader("Cotent-type","application/json; charset=utf-8");
xhr.send(JSON.stringify(data));
}
const getAll = () => {
ajax({
url:"http://localhost:5551/santo",
success: (res) => {console.log(res)},
error: (err) =>{
//console.log(err);
$table.insertAdjacentHTML("afterend", `<p><b>${err}</b></p>`);
}
})
}
d.addEventListener("DOMContentLoaded", getAll)
I am doing a CRUD exercise with ajax. The request was made to a local server (db.json). The else condition inside the getAll () function doesn't work. throws an error: crud_ajax.html: 83 Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null at error at XMLHttpRequest.