Smooth Smooth - 2 months ago 9
Javascript Question

Running javascript function from ajax success call

I'm currently working with google maps and I want to save some locations in a database and retrieve them through an ajax call, after which I make JavaScript objects from the locations.

As for the code I am not really sure why this is not working, can someone clear this up for me?

Chrome Console:
Uncaught TypeError: this.processData is not a function



var Locations = {
count: 0,
location: [],
processData: function (data) {
console.log(data);
},
getData: function () {
'use strict';

jQuery.ajax({
type: 'get',
url: '../../php/functions/getLocations.function.php',
dataType: 'json',
success: function (data) {
this.processData(data);
}
});
}
};




About the comment Kevin B posted, the done part should run when the async call is complete right?
Last edit:

function getLocation() {
return $.ajax({
type: 'get',
url: '../../php/functions/getLocations.function.php',
dataType: 'json'
});
}

getLocation().done(function(result) {
console.log(result);
return result;
});

Answer

The keyword this refers to the scope it was initialized in. So in your case it is the scope of the success-function. It doesn't refer to the object itself.

For this to work you have to cache the reference to the object to use it inside the success-function or reference the object itself.

Object reference:

jQuery.ajax({
  type: 'get',
  url: '/echo/json/',
  dataType: 'json',
  success: function(data) {
    Locations.processData(data);
  }
});

Cached this

getData: function() {
    'use strict';
    let _this = this;
    jQuery.ajax({
      type: 'get',
      url: '/echo/json/',
      dataType: 'json',
      success: function(data) {
        _this.processData(data);
      }
    });
  }

Fiddle

Comments