0

I am trying to delete a json object from the json file when that object values are displayed in a form using the AJAX Delete function. I am using express to generate a route for the json file like below:

app.get('/users', (req, res) => {
    var userData = json;
    
    res.send(userData);
        
        }), 
        
app.delete('/users/delete/:id', (req, res) => {
    var key = req.params.id;
    var deletedData = json;
    
    deletedData.splice(key, 1);
    res.send(deletedData);

});

      $(document).on('click', '#delete', function () {
             $.ajax({
                    type: "DELETE"
                    , url: "users/delete/"+data[key]  
                    , datatype: "datatype"
                    , success: function (data) {
                        console.log(data);
       
                        }   
                });
            });

I know I havent declared the data[key], that is just context for what i would like to do. My issue is trying to select the specific json object rather than just selecting the first object with what I have now "users/delete/0', would anyone know how to do this?

EDIT

I am trying to get the "users/delete/:id" specific to the object that is displayed in my form in the html

                <div class="col-md-5 col-sm-12">
                    <div id="full_details">
                        <ul class="details">
                            <h2>Contact Details</h2> <img src="" alt="Avatar" id="avatar">
                            
                            
                            <li>Name
                                <input type="text" id="name" class="form-control mr-sm-2" disabled>
                            </li>
                            <li>Address
                                <input type="text" id="address" class="form-control mr-sm-2" disabled>
                            </li>
                            <li>Contact Number
                                <input type="text" id="phone" class="form-control mr-sm-2" disabled>
                            </li>
                            <li>Email
                                <input type="text" id="email" class="form-control mr-sm-2" disabled>
                            </li>
                            <li>Postcode
                                <input type="text" id="postcode" class="form-control mr-sm-2" disabled>
                            </li>
                            <li>City
                                <input type="text" id="city" class="form-control mr-sm-2"disabled>
                            </li>
                            <li>Country
                                <input type="text" id="country" class="form-control mr-sm-2" disabled>
                            </li>
                            <div class="row">
                                <div class="col-md-6">
                                    <div id="editbutton">
                                        <p class="btn btn-primary">Edit Details</p>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div id="savebutton">
                                        <p class="btn btn-danger">Save Details</p>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div id="delete">
                                        <p class="btn btn-danger">delete</p>
                                    </div>
                                </div>
                            </div>
                        </ul>
                    </div>
                </div>
John
  • 51
  • 7
  • I'm not sure I understand the question. What do you mean *the first object with what I have now*? – Katie.Sun Dec 07 '18 at 00:58
  • If i put "users/delete/0" as the url in the ajax delete function, it will delete the first object in my json file, I am trying to make the function delete the specific object pulled in the form if that makes sense? – John Dec 07 '18 at 01:10
  • 1
    Ah, yes. You need to loop through the array (I am assuming your user data is an array) and find the index of the object with the matching id, and splice from that index instead. See if this helps: https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript – Katie.Sun Dec 07 '18 at 01:13

2 Answers2

0

The JSON data needs to be made available in the location where you want to perform operations. If you have not already done so outside of the snippet, your JSON needs to be required into the file where your Express delete route is located.

In your current delete route, the .splice method is only available for Strings and Arrays (unless you define the method on Object.prototype).

This is an example of what a delete route might look like, if your JSON data was an object:

let userJSON = require('./users.json');

app.delete('/users/delete/:id', (req, res) => {
    let key = req.params.id;
    if( delete userJSON.key ){
        res.send(`User ${key} deleted`);
    }
}

The delete operator in the if statement returns true if the object's key was successfully deleted. There are some instances where you cannot use this operator, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete to check whether it is compatible with what you want to do.

Edit 1: Misunderstood question so here is the correct delete method

let userJSON = require('./users.json');

app.delete('/users/delete/:id', (req, res) => {
    let key = req.params.id;
    for( let i=0; i<userJSON.length; i++){
        if( userJSON[i].id === key ){
            userJSON.splice(i,1);
        }
    }
});
achacttn
  • 163
  • 2
  • 9
  • Thanks for this achacttn, however I need to be the ":id" to be specific to the object that is in a form in my html, would you know how to do this? I will edit my question to show my html. – John Dec 07 '18 at 01:07
  • Correct me if I am mistaken, is the `:id` that you want to delete a property of the user object (user's name or phone etc), or deleting an entire user with a unique id, from a list or array of users? – achacttn Dec 07 '18 at 01:23
  • yeah I would like to delete an entire user from the list – John Dec 07 '18 at 01:26
  • The HTML form snippet you have provided does not indicate how the `data[key]` or `:id` is generated. The snippet looks like a user creation form. – achacttn Dec 07 '18 at 01:37
  • The users details are inserted into the input values when their name is clicked. – John Dec 07 '18 at 01:40
  • Is the user's `:id` on the url of the page, or stored somewhere (such as `localStorage`)? – achacttn Dec 07 '18 at 01:43
  • Yes so if i called `users/delete/0` i would get the first object of the file – John Dec 07 '18 at 01:48
  • Ok, I think I see what has been going on. When you call `users/delete/0`, `key` does equal `0`. I am guessing your users in JSON is in an array. When you call the `splice` method, it is checking the index of your array, not the user id nested within each user array element. Therefore, you may want to loop through your users, and check each user id until there is a match. – achacttn Dec 07 '18 at 01:51
  • How could i do this? – John Dec 07 '18 at 02:01
  • I've edited answer to show how you can loop through your users array, and `.splice` out only the user whose `user.id` matches the `:id` sent in your delete request. – achacttn Dec 07 '18 at 02:05
  • Almost there.. is there a way to define the json object in a variable? – John Dec 07 '18 at 02:41
  • Yes. You can declare a variable outside the scope of the `delete` route (i.e. `var jsonObject` or `let jsonObject`). Then after the `userJSON.splice(i,1)` line, `jsonObject = userJSON`. – achacttn Dec 07 '18 at 02:52
0

While you are populating the data in to the fields , I assume you will be having the id of that record.

store it in a variable/or you can directly get it from the fetched object (object.id)

Time being I'll store it in a variable.

assume below is the object data you pulled and displayed:

var obj = {
   id:1,
   name: "Test",
   address:"Test Address"   
}
var objId = obj.id; //I'll use this id in AJAX request.

Then call AJAX request.

 $.ajax({
             type: "DELETE"
            , url: "users/delete/"+objId  
            , datatype: "datatype"
            , success: function (data) {
                 console.log(data);

                }   
                });

Node Js:

app.delete('/users/delete/:id', (req, res) => {
       let deleteId = req.params.id; //Get the id through req.params.id of the object you are going to delete
       let deleteObj = userJson.find(user => user.id == deleteId); // As you have only Id of the object, we want to get the entire object from the array. find() will fetch the object from the array whose id is equal to deleteId and assign it to deleteObj.
       let deleteIndex = userJson.indexOf(deleteObj); //Find the index of the object fetched from the JSON array.
       userJson.splice(deleteIndex,1); // Splice/ remove the object from the JSON Array.
      res.send(deleteObj); // Send the deleted object as response.
});
Tej
  • 175
  • 7
  • This worked thanks! I just needed to change some of the variables and I didnt have a value "id" in my file so I just called the "name field instead :) – John Dec 07 '18 at 10:36