Home > Enterprise >  jquery error when use my ajax setting with url/${} to delete dynamic row
jquery error when use my ajax setting with url/${} to delete dynamic row

Time:11-14

when I put the url with ${id}, i got an error saying the id is not defined

  var settings = {
  "async": true,
  "crossDomain": true,
  "url": `https://example.restdb.io/rest/example/${id}`,
  "method": "DELETE", // delete based on ID
  "headers": {
    "content-type": "application/json",
    "x-apikey": APIKEY,
    "cache-control": "no-cache"
  }
}

//[STEP 0]: Make sure our document is A-OK
$(document).ready(function () {
  //what kind of interface we want at the start 
  const APIKEY = "32187321dkasahjsdaaj"; // fake
  getContacts();
  $("#update-contact-container").hide();
  $("#add-update-msg").hide();
  //[STEP 1]: Create our submit form listener = SEND
  $("#contact-submit").on("click", function (e) {
    //prevent default action of the button 
    e.preventDefault();
    //[STEP 2]: ONCE CLICK 
    // let's retrieve form data
    //for now we assume all information is valid
    //you are to do your own data validation
    // get the value from html's elements
    let contactName = $("#contact-name").val();
    let contactID_1 = $("#contact-ID-1").val();
    let contactMentor = $("#contact-mentor").val();
    let contactClass = $("#contact-class").val();
    let contactEmail = $("#contact-email").val();
    let contactPhone = $("#contact-phone").val();
    //[STEP 3]: get form values when user clicks on SEND
    //Adapted from restdb api
    let jsondata = {
      "name": contactName,
      "student_id": contactID_1,
      "mentor": contactMentor,
      "class": contactClass,
      "email": contactEmail,
      "phone": contactPhone
    };
    //[STEP 4]: Create our AJAX settings. Take note of API key
    let settings = {
      "async": true,
      "crossDomain": true,
      "url": "https://example.restdb.io/rest/studentcrud",
      "method": "POST", // we will use post to send info to server to update
      "headers": {
        "content-type": "application/json",
        "x-apikey": APIKEY,
        "cache-control": "no-cache"
      },
      "processData": false,
      "data": JSON.stringify(jsondata),
      "beforeSend": function () {
        //beforeSend - what to do before request is sent
        //@TODO use loading bar instead
        //disable our button or show loading bar
        $("#contact-submit").prop("disabled", true);
        //clear our form using the form id and triggering it's reset feature
        $("#add-contact-form").trigger("reset");
      }
    }
    //[STEP 5]: Send our ajax request over to the DB and print response of the RESTDB storage to console.
    $.ajax(settings).done(function (response) {
      console.log(response);
      $("#contact-submit").prop("disabled", false);
      //@TODO update frontend UI 
      $("#add-update-msg").show().fadeOut(3000); //Contact record successfully added
      //update our table 
      getContacts();
    });
  });//end click 
  //[STEP] 6
  //let's create a function to allow you to retrieve all the information in your contacts
  //by default we only retrieve 10 results
  function getContacts(limit = 10, all = true) {
        //[STEP 7]: Create our AJAX settings
    let settings = {
      "async": true,
      "crossDomain": true,
      "url": "https://example.restdb.io/rest/studentcrud",
      "method": "GET", //[cher] we will use GET to retrieve info
      "headers": {
        "content-type": "application/json",
        "x-apikey": APIKEY,
        "cache-control": "no-cache"
      },
    }
    //[STEP 8]: Make our AJAX calls
    //Once we get the response, we modify our table content by creating the content internally. We run a loop to continously add on data
    //RESTDb/NoSql always adds in a unique id for each data, we tap on it to have our data and place it into our links 
    $.ajax(settings).done(function (response) {
            let content = "";
      for (var i = 0; i < response.length && i < limit; i  ) {
                content = `${content}<tr id='${response[i]._id}'>
        <td>${response[i].name}</td>
        <td>${response[i].student_id}</td> 
        <td>${response[i].mentor}</td>
        <td>${response[i].class}</td>
        <td>${response[i].email}</td>
        <td>${response[i].phone}</td>
        <td><a href='' class='delete' data-id='${response[i]._id}'>Del</a></td>
        <td><a href='#update-contact-container' class='update' data-id='${response[i]._id}' data-student_id='${response[i].student_id}' data-mentor='${response[i].mentor}' data-class='${response[i].class}' data-phone='${response[i].phone}' data-name='${response[i].name}' data-email='${response[i].email}'>Update</a></td></tr>`;
      }
      //[STEP 9]: Update our HTML content
      //let's dump the content into our table body
      $("#contact-list tbody").html(content);
      $("#total-contacts").html(response.length); // update the no. of contacts
    });
    // this entire is getContact;
  }
  //[STEP 10]: Create our update listener
  //here we tap onto our previous table when we click on update
  //this is a delegation feature of jquery
  //because our content is dynamic in nature, we listen in on the main container which is "#contact-list". For each row we have a class .update to help us
  $("#contact-list").on("click", ".update", function (e) {
    e.preventDefault();
    //update our update form values
    //UPDATE FORM
    let contactName = $(this).data("name");
    let contactID_1 = $(this).data("student_id");
    let contactId = $(this).data("id");
    let contactMentor = $(this).data("mentor");
    let contactClass = $(this).data("class");
    let contactEmail = $(this).data("email");
    let contactPhone = $(this).data("phone");
    //[STEP 11]: Load in our data from the selected row and add it to our update contact form 
    $("#update-contact-name").val(contactName);
    $("#update-contact-ID-1").val(contactID_1);
    $("#update-contact-id").val(contactId);
    $("#update-contact-mentor").val(contactMentor);
    $("#update-contact-class").val(contactClass);
    $("#update-contact-email").val(contactEmail);
    $("#update-contact-phone").val(contactPhone);
    $("#update-contact-container").show();
  });//end contact-list listener for update function
  //[STEP 12]: Here we load in our contact form data
  //Update form listener
  $("#update-contact-submit").on("click", function (e) {
    e.preventDefault();
    //retrieve all my update form values
    let contactName = $("#update-contact-name").val();
    let contactID_1 = $("#update-contact-ID-1").val();
    let contactMentor = $("#update-contact-mentor").val();
    let contactClass = $("#update-contact-class").val();
    let contactEmail = $("#update-contact-email").val();
    let contactPhone = $("#update-contact-phone").val();
    let contactId = $("#update-contact-id").val();
    //[STEP 12a]: We call our update form function which makes an AJAX call to our RESTDB to update the selected information
    updateForm(contactId, contactName, contactID_1, contactMentor, contactClass, contactEmail, contactPhone);
  });//end updatecontactform listener
  //[STEP 13]: function that makes an AJAX call and process it 
  //UPDATE Based on the ID chosen
  function updateForm(id, contactName, contactID_1, contactMentor, contactClass, contactEmail, contactPhone) {
    //@TODO create validation methods for id etc. 
    var jsondata = { "name": contactName, "student_id": contactID_1, "mentor": contactMentor, "class": contactClass, "email": contactEmail, "phone": contactPhone };
    var settings = {
      "async": true,
      "crossDomain": true,
      "url": `https://example-95e6.restdb.io/rest/studentcrud/${id}`,//update based on the ID
      "method": "PUT",
      "headers": {
        "content-type": "application/json",
        "x-apikey": APIKEY,
        "cache-control": "no-cache"
      },
      "processData": false,
      "data": JSON.stringify(jsondata)
    }
    //[STEP 13a]: send our AJAX request and hide the update contact form
    $.ajax(settings).done(function (response) {
      console.log(response);
      $("#update-contact-container").fadeOut(5000);
      //update our contacts table
      getContacts();
    });
  }//end updateform function
  //[STEP 14]: Create EVENT LISTENER ON delete 
  $("#contact-list").on("click", ".delete", function (e) {
    e.preventDefault();
    console.log("hello")
    var settings = {
      "async": true,
      "crossDomain": true,
      "url": `https://example-95e6.restdb.io/rest/studentcrud/${id}`,
      "method": "DELETE", // delete based on ID
      "headers": {
        "content-type": "application/json",
        "x-apikey": APIKEY,
        "cache-control": "no-cache"
      }
    }
    $.ajax(settings).done(function (response) {
      console.log(response);
      console.log('hi hi');
      //update our table 
      getContacts();
    });
  });
}) // end
html, body {
  height: 100%;
  width: 100%;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<div >
  <h1>Simple Contact Form System</h1>
  <div id="add-update-msg">
    <!-- will be hide away -->
    <div  role="alert">Contact record successfully added</div>
  </div>
  <div  id="add-contact">
    <form id="add-contact-form">
      <!-- Input -->
      <!-- Name -->
      <div ><label for="contact-name">Name</label><input type="text" id="contact-name"
           required></div><!-- Student ID -->
      <div ><label for="contact-ID-1">Student ID</label><input type="tel" id="contact-ID-1"
           required></div><!-- Mentor -->
      <div ><label for="contact-mentor">Student Mentor</label><input type="text" id="contact-mentor"
           required></div><!-- Class -->
      <div ><label for="contact-class">Class</label><input type="text" id="contact-class"
           required></div><!-- Email -->
      <div ><label for="contact-email">Email</label><input type="email" id="contact-email"
           required><small id="contact-email-help" >We'll never share
          your email with anyoneelse.</small></div><!-- Phone -->
      <div ><label for="contact-phone">Phone Number</label><input type="tel" id="contact-phone"
          ></div><input type="submit" value="Send"  id="contact-submit">
    </form>
  </div>
</div><!-- end add container -->
<div >
  <h2>Table information of Contacts (<span id="total-contacts"></span>)</h2>
  <table  id="contact-list">
    <thead>
      <th>Name</th>
      <th>Student ID</th>
      <th>Student Mentor</th>
      <th>Student Class</th>
      <th>Email Address</th>
      <th>Phone Number</th>
      <th colspan="2">Actions</th>
    </thead><!-- This will be filled with information later -->
    <tbody></tbody>
  </table>
</div><!-- Update -->
<div  id="update-contact-container">
  <div id="add-update-msg">
    <div  role="alert">Contact record updated sucessfully</div>
  </div>
  <h4>Update Contact</h4>
  <div  id="update-contact">
    <form id="update-contact-form">
      <div ><label for="update-contact-name">Name</label><input type="text" id="update-contact-name"
           required></div><!-- Student ID -->
      <div ><label for="update-contact-ID-1">Student ID</label><input type="tel"
          id="update-contact-ID-1"  required></div><!-- Mentor -->
      <div ><label for="update-contact-mentor">Student Mentor</label><input type="text"
          id="update-contact-mentor"  required></div><!-- Class -->
      <div ><label for="update-contact-class">Class</label><input type="text"
          id="update-contact-class"  required></div><!-- Email -->
      <div ><label for="update-contact-email">Email</label><input type="email"
          id="update-contact-email"  required><small id="update-contact-email-help"
          >We'll never share your email with anyoneelse.</small></div><!-- Phone -->
      <div ><label for="update-contact-phone">Phone</label><input type="text"
          id="update-contact-phone" ><input type="hidden" id="update-contact-id"></div><input
        type="submit" value="Update Contact Details"  id="update-contact-submit">
    </form>
  </div>
</div><!-- DELETE -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.1.3/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
  integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU 6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
  integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>

CodePudding user response:

The variable idis indeed undefined in the context of the event handler function. We need to get the information from somewhere else.

As the delete action is triggered by a click on a .delete element in your #contact-list you should get the id to be deleted directly from that element. And, indeed, it can be found there:

<a href='' class='delete' data-id='${response[i]._id}'>Del</a>

The data-id holds the id as received from the AJAX server earlier. It can be referenced by looking at the .dataset.id attribute of the clicked element e.target. So, your .on("click", ".delete", function (e) {...} should look something like this:

$("#contact-list").on("click", ".delete", function (e) {
  e.preventDefault();
  if (confirm("Do you want to delete this item?")){
    var settings = {
      "async": true,
      "crossDomain": true,
      "url": `https://example-95e6.restdb.io/rest/studentcrud/${e.target.dataset.id}`,
      "method": "DELETE", // delete based on ID
      "headers": {
        "content-type": "application/json",
        "x-apikey": APIKEY,
        "cache-control": "no-cache"
      }        
    $.ajax(settings).done(function (response) {
      console.log(response);
      //update our table 
      getContacts();
    });
  }
})
  • Related