0
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.

  • The error message implies that `$table` is null. Have you confirmed that the target HTML element exists? – David Feb 09 '21 at 14:23
  • The error has nothing to do with ajax. You haven't shown us the `error` function (which you're using in the `else`, so I'm wondering if it writes to an element), but the error message is quite clear: You're trying to call `insertAdjacentHTML` on `null`. Apparently you got `null` when you were expecting to get an element. See the answers to the [linked question](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) for why. – T.J. Crowder Feb 09 '21 at 14:23
  • there I managed to find the error, the $ table selector was selected wrongly. Thank you for your answers. – Vanesa Morilla Feb 09 '21 at 18:07

0 Answers0