Search code examples
javascriptnode.jsjsoncrudput

Edit a user in a JSON storage JSON file using XMLHttpRequest


I have a problem, which I hope someone in here can help me solve. I'm trying to edit one user in my JSON-file. Therefore I have created a button in HTML with the ID "editBtn". My users are stored in the file storage.JSON. The user that is logged in is saved in LocalStorage as "currentUser". The username is the unique ID, therefore it is set at readonly in HTML.

I have written the following code but it, unfortunately, doesn't work. When I console.log throughout the code it seems as if it stops reacting after the xhr.addEventListener. Furthermore, I am not sure whether or not my logic is right when starting off my splicing my array and afterward making a PUT-request.

I am new to coding, so there might be a lot of flaws.

API-CRUD:

app.get('/editProfile', (req, res) => {
    
    var allUsers = JSON.parse(fs.readFileSync("storage.JSON"))
    res.json(allUsers)
})


app.put('/editProfile', (req, res)=> {
    let reqData = req.body;
    console.log('Post request virker')
    console.log(reqData) 
    var storage = JSON.parse(fs.readFileSync("storage.JSON"))
    storage.push(reqData);
    fs.writeFileSync("storage.JSON", JSON.stringify(storage, null, 2));

    //console.log(reqData);
    res.send(JSON.stringify({message: 'the user is updates as', storage}));
})

editProfile.js

var currentUser = JSON.parse(localStorage.getItem("currentUser"));

document.getElementById("username").value = currentUser.username;
document.getElementById("editPhone").value = currentUser.phone;
document.getElementById("newCity").value = currentUser.city;
document.getElementById("newZip").value = currentUser.zip;
document.getElementById("newAddress").value = currentUser.address;
document.getElementById("newEmail").value = currentUser.email;
document.getElementById("newPassword").value = currentUser.password;



editUser = document.getElementById("editBtn")

editUser.addEventListener('click', ()=> {
    
        const xhr = new XMLHttpRequest();
        xhr.responseType = "json"

        
       
         const username = document.getElementById('username');
         const phone = document.getElementById('editPhone');
         const city = document.getElementById('newCity');
         const zip = document.getElementById('newZip');
         const address = document.getElementById('newAddress');
         const email = document.getElementById('newEmail');
         const password = document.getElementById('newPassword');
 
         var data = {
             username : username.value, 
             phone : phone.value,
             city : city.value,
             zip : zip.value,
             address : address.value,
             email : email.value,
             password : password.value,
         }

        xhr.addEventListener("readystatechange", function() {
        if(this.readyState === 4) {
            var allUsers = this.response;
    
    
            for (i = 0; i < allUsers.length; i++) {
                if (allUsers[i].username === username){
                    allUsers.splice(i,1); 
                    console.log(allUsers)
           
                  
                } }};
    
        xhr.open("PUT", "http://localhost:2500/editProfile", true);
            
        xhr.setRequestHeader("Content-Type", "application/json");
            
  
        xhr.send(JSON.stringify(data));
       
    }) 
})

Thank you for taking a look at my question


Solution

  • You should be cautious about nesting code. Your code will be much easier to read and understand if you write functions and call them from your event handlers.

    The issue you face is that you've missed a ) in your code. Here is a version written as I suggest:

    editUser.addEventListener('click', retrieveAndSendUpdate);
    
    function retriveAndSendUpdate() {
      const username = document.getElementById('username');
      const phone = document.getElementById('editPhone');
      const city = document.getElementById('newCity');
      const zip = document.getElementById('newZip');
      const address = document.getElementById('newAddress');
      const email = document.getElementById('newEmail');
      const password = document.getElementById('newPassword');
    
      var data = {
        username: username.value,
        phone: phone.value,
        city: city.value,
        zip: zip.value,
        address: address.value,
        email: email.value,
        password: password.value,
      }
    
      sendUpdate(data);
    }
    
    function sendUpdate(data) {
      const xhr = new XMLHttpRequest();
      xhr.responseType = "json"
      xhr.addEventListener("readystatechange", processResponse);
      xhr.open("PUT", "http://localhost:2500/editProfile", true);
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.send(JSON.stringify(data));
    }
    
    function processResponse(e) {
      if (e.readyState === 4) {
        var allUsers = e.response;
        for (i = 0; i < allUsers.length; i++) {
          if (allUsers[i].username === username) {
            allUsers.splice(i, 1);
            console.log(allUsers)
          }
        }
      }
    }
    

    You should also consider testing if you actually got any users back from the server before processing them.