1

Why do I get this error:

Cannot read property 'push' of undefined

It seems like I can't push my data to my barcodes array? The console.log(data) works.

var myScanObj = {
  $el: null,
  $res: null,
  $searchButton: null,
  $resetButton: null,
  $hiddenInput: null,
  $scanInput: null,
  $selectType: null,
  barcodes: [],
  init: function() {
    myScanObj.cacheDom();
    myScanObj.bindEvents();
  },
  cacheDom: function() {
    $el = $('.formControl');
    $res = $('#result');
    $searchButton = $el.find('#searchButton');
    $resetButton = $el.find('#resetButton');
    $hiddenInput = $el.find('input[name=hiddenField]');
    $scanInput = $el.find('input[name=myScan]');
    $selectType = $el.find('#myType');
  },
  bindEvents: function() {
    $searchButton.on('click', this.addBarcode.bind(this));
  },
  addBarcode: function() {
    var postForm = {
      'myType': $selectType.val(),
      'myScan': $hiddenInput.val()
    };
    $.ajax({
      url: "test.php",
      type: "POST",
      data: postForm,
      dataType: "text",
      success: this.successAjax
    });
  },
  showBarcode: function() {

  },
  successAjax: function(data) {
    this.barcodes.push(data);
    console.log(data);
  }
};

myScanObj.init();

This is my test.php code:

<?php
  $output = '';
  $output .= $_POST["myType"];
  $output .= $_POST["myScan"]; 
  echo $output
?>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Greg Ostry
  • 1,161
  • 5
  • 27
  • 52
  • 2
    It's because `this` in the `successAjax` function is not referring to your object. – Rory McCrossan May 17 '17 at 08:07
  • 1
    Possible duplicate of [$(this) inside of AJAX success not working](http://stackoverflow.com/questions/6394812/this-inside-of-ajax-success-not-working) – John May 17 '17 at 08:12

2 Answers2

0

this.barcodes is not recorgnized on the moment you push. I think this is reffering to the ajax object and not the myScanObj.

try: myScanObj.barcodes.push(data);

  • While this may work, it's not ideal as it ties the logic within the object to it's variable name. Ideally the two should be entirely separate – Rory McCrossan May 17 '17 at 08:30
0

The issue is because this in the successAjax function is a reference to the jqXHR used in the AJAX call, not your myScanObj object.

To fix this you can change the scope the reference is called under by using bind():

success: this.successAjax.bind(this)

Or, if you don't mind not supporting older versions of IE, an arrow function:

success: data => this.successAjax(data)
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339