简体   繁体   中英

AJAX call is broken, NodeJS, Express, Handlebars

I've been working on this for a couple of days. I'm certain its something really stupid, but I'm at the end of my sanity.

The public files are set up properly.

Error Message:

Uncaught ReferenceError: togDefine is not defined

Front End HTML:

<li class="list-group-item list-group-item-dark">
   <div class="row">
     <div class="col-md-4"><strong>Heating:</strong> {{#if heating}} {{this.heating}} {{else}} N/A {{/if}}</div>
     <div class="col-md-4"><strong>Cooling:</strong> {{#if cooling}} {{this.cooling}} {{else}} N/A {{/if}}</div>
     <div class="col-md-4">
       <input type="checkbox" id="pvt{{this.id}}" checked="{{this.private}}" onchange="togDefine({{this.id}}, {{this.private}});" data-toggle="toggle" data-on="Private" data-off="Public" data-onstyle="success" data-offstyle="danger" />
     </div>
   </div>

AJAX Call:

$(function() {

//  Private-Public toggle
let togDefine = (id, pvt) => {
  $.ajax({
    type: "POST",
    url: "/api/pvtToggle",
    data: {
      id: id,
      newState: (pvt === 'true') ? false : true
    },
    success: function(text) {
      if (text === 'ok') {
        pvtSuccess(id, pvt);
      } else {
        console.log('updatePvt failed');
      }
    }
  });

};


let pvtSuccess = (id, pvt) => {
  $('#pvt' + id).attr('checked', (pvt === 'true') ? 'false' : 'true');
};


});

Back End:

//TOGGLE Private vs Public PROPERTY
app.put('/api/pvtToggle/', isAuthenticated, function(request, response) {
  db.Prop.update({
    private: request.params.newState
  }, {
    where: {
      id: request.params.id
    }
  }).then(data => {
    response.send('ok');
  }).catch(error => {
    console.log(error);
  });

});

Please help me figure out why the request isn't working properly. :D

Your function togDefine() is defined inside this block:

$(function() { /* in here */ })

Therefore, that function name is only available inside that block and is not available to your HTML. Since just defining a function doesn't actually execute anything, there is really no reason to define a function inside of that kind of block unless you ONLY want the symbol available inside that block.

Since you explicitly don't want that here, just move the definition of togDefine() outside that block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM