Search code examples
javascriptajaxpug

Running some Ajax code gave an undefined value in the console


I have a gradation project to create a better website to handle student registrations.

I followed a youtube playlist to learn more about node.js and other packages, so when i run this code i get back an undefined value, any ideas why ?

$(document).ready(function(){
  $('.delete-student').on('click', function(e){
    $target = $(e.target);
    const id = $target.attr('data-id');
    $.ajax({
      type:'DELETE',
      url: '/students/'+id,
      success: function(response){
        alert('Deleting Student');
        window.location.href='/';
      },
      error: function(err){
        console.log(err);
      }
    });
  });
});

Error

error

PUG code:

extends layout

block content
h1= student.first_name + " " + student.last_name
hr

.container
    h4 More infomation:
    ul.list-group
        li.list-group-item  First name    : #{student.first_name}
        li.list-group-item  Last name     : #{student.last_name}
        li.list-group-item  Parents Email : #{student.parentEmail}
        li.list-group-item  School        : #{student.school}

hr
h5 School : #{student.school}
hr 
a.btn.btn-default(href='/student/edit/'+student._id) Edit
a.btn.btn-danger.delete-student(href='#',data.id=student._id) Delete

Solution

  • Update and "real" answer™

    PUG attributes are interpreted as-is so instead of

    (href='#',data.id=student._id)
    

    you should have

    (href='#',data-id=student._id)
    

    Assuming your .delete-student element is the same one having data-id="...", alter your code to

    $target = $(this)
    

    jQuery automatically binds the element handling the bound event to the lexical scope of the event handler, ie this.

    You might even want to change your selector to

    $('.delete-student[data-id]')
    

    to ensure there is definitely the required attribute present.


    The issue with using event.target is that if the event originated further down the document hierarchy, event.target refers to the originally clicked element.

    Consider this structure

    <button class="i-really-want-clicks-on-me" data-id="required">
      <span>I'm the label</span>
    </button>
    

    If you bind an event handler on the <button> but click on the <span>, event.target will be the <span>.