I am using angular js for my project. Currently I am getting data using below function. This is my function.
$scope.loadMoreDetails = function () {
$http({
method: "GET",
url: appConfig.apiUrl + "/results/" + $scope.resultId + "/details/"
}).then(function (response) {
$scope.sourceData = response.data.sources;
$scope.sourceList = $scope.sourceData.split(', '); // split string on comma space
console.log($scope.sourceList);
}, function (response) {
$log.error(response);
});
};
My console log inside the function is working well, but I am trying to access that $scope.sourceList in another function.
$scope.saveAp = function () {
console.log($scope.sourceList)
}
This console.log is undefined. Actually I need to know, how I access $scope.sourceList outside the function. How I do it.
Related
I am writing on a service call in my method. Once ajax call is getting fire I am getting the response. But after getting the response I am losing the other variable of the method in ajax success,
Here is my code.
refreshClick: function(options) {
let _this = this,
selectedrecord = this.getView().getStore().getAt(options.rowIndex);
let reqObj = {
url: options.url + selectedrecord.data.val,
method: 'get',
};
_this.getGridService().loadGridStoreData(reqObj).then({
success: function(response) {
debugger;
},
failure: function(response) {
Ext.Msg.alert('Failed', result);
_this.getView().getStore().load();
return false;
}
});
}
Now after getting success in debugger line, I am not getting the value of options or selectedRecs.
That's probably the debugger removing unused variables from the scope, reference the variables inside the function:
console.log(options,selectedRecs);
debugger;
And you should be able to access its values.
This is really strange to me. After AJAX call, some of the variables are no longer defined. Some are, some are not. Why?
If you look at the sentence 'THIS IS THE POINT WHERE I NEED MY VARIABLES' - at this point:
cMobile is defined and value is in it
cShowAlertsDesktopApp is also defined and has value in it
cIN_SRT is defined and has value in it
- $divMessage is not defined. But it was defined before ajax call. Why is that? How can I use this variable in return from ajax?
var DeleteTableJEREIN = function (e, iREIN_KEY) {
var cMobile = $("#cMobileApplication").val();
var cShowAlertsDesktopApp = $("#hiddenShowAlertsDesktopApp").val();
if (!confirm("IzbriĆĄem?")) {
return;
}
var cIN_SRT = $("#hidden_hIN_SRT").val();
var $divMessage = $(e).closest('td').find('div.divMessage');
$.ajax({
url: '/Warehouse/InsertUpdateJEREIN/',
type: 'POST',
data: {
iREIN_KEY: iREIN_KEY,
cTask: '4'
},
success: function (msg) {
**THIS IS THE POINT WHERE I NEED MY VARIABLES**
var json = JSON.parse(msg);
if (json.error) {
if (cMobile === "1") {
fInventoryShippingReceiving.HideMessages();
I am making an ajax form submission inside an object.
When I try call the other object methods within the jQuery.ajax.success callback, this line throws an error...
Is this a scoping issue?
this.DisplayError(data.error);
this.DisplayError is not a function
Code:
var toolsform = new function() {
this.sumbitUrl = 'submit.php';
this.DisplayError = function(errorMsg) {
jQuery('#trialFormError').html('<strong>Error: </strong>' + errorMsg);
}
this.AjaxSumbit = function() {
let formData = jQuery("#trialsToolsRegisterForm").serialize();
formData += '&toolsFormSumbit=1';
jQuery.ajax({
type: "POST",
url: this.sumbitUrl,
dataType: 'json',
data: formData,
success: function(data) {
if(data.success === false) {
this.DisplayError(data.error);
}
console.log(data); // show response from the php script.
}
});
}
}
Use arrow function:
success: () => {
}
This happens because you are loosing context, Ajax assigns different context when calling success function. You can also save context in New variable:
var self = this;
And use it inside success function instead of this.
Or you can define function context:
success: (function() {
}).bind(this)
this inside the success function is not equal to this outside. The simplest way to handle this is using arrow function.
var toolsform = new function() {
this.sumbitUrl = 'submit.php';
this.DisplayError = function(errorMsg) {
jQuery('#trialFormError').html('<strong>Error: </strong>' + errorMsg);
}
this.AjaxSumbit = function() {
let formData = jQuery("#trialsToolsRegisterForm").serialize();
formData += '&toolsFormSumbit=1';
jQuery.ajax({
type: "POST",
url: this.sumbitUrl,
dataType: 'json',
data: formData,
success: data => {
if(data.success === false) {
this.DisplayError(data.error); // now `this` should be equal to the one outside
}
console.log(data); // show response from the php script.
}
});
}
}
The magic is, arrow function does not has its own this. When you call this, it will refer to the outside one. But normal function has its own this, therefore when you call this, it will refer to its own this instead of the outside one.
For details, you may take a look on the MDN web docs
I have searched this site and tried, but I am still not coming right. I have searched these threads (among others):
How to get return value in a function with inside Ajax call - JQuery
get return value of jQuery get().done() function
I have one page on my app. I have one dxSelectBox on my page. I need to display a list of depots inside the dxSelectBox. My Webservice works. I am trying this to show the results in the dxSelectBox but it does not show anything:
App.FirstScreen = function (params) {
// "use strict";
var viewModel = {
dsDepots: ko.observableArray([]),
GetDepots: getDepots (),
};
return viewModel;
};
function getDepots() {
// this will generate another thread to run in another function
jQuery.ajax({
url: 'connection_string + "/rest/_getDepots"',
type: 'get',
success: function (data) {
if (data != "") {
var _result = JSON.parse(data.childNodes['0'].childNodes['0'].data);
viewModel.dsDepots(_result);
}
return (data);
},
error: function () {
return "Hello";
}
});
}
I am writing a class in JavaScript for the first time and I am having some trouble writing new data to a class variable. I've been trying all sorts for hours but nothing seems to work!
function ClassName(productId) {
//create variables
this.productId = productId;
this.shop = [];
this.product = [];
//method that calls for response. On success will return {"status" : "success", "shop" : "someshop.com"}
this.auth = function() {
$.ajax({
url: "http://website.com/api/auth/",
dataType: "jsonp",
success: function(data) {
authCallback(data); //use callback to handle response
},
error: function() {
console.log("bad auth");
}
});
}
var authCallback = function(r) {
//using console.log(r) output the response OK
this.shop = r; //this runs with no errors
}
}
Now, as yo can see in the authCallback method I'm setting this.shop = r; but then if i refer back to this variable its still at its default value of [] .
var class = new ClassName(1);
class.auth();
console.log(class.shop); //this outputs []
I've also tried this in the Javascript console writing each line after each stage had been completed(waited for a response from class.auth() and output from authCallback() before then calling console.log(class.shop);
So, what am I doing wrong? Why isn't the variable updating to its new value?
When you just write:
authCallback(data);
then within authCallback you will have the wrong value of this, it'll either be null or the global object (depending on whether you're in strict mode or not).
Use:
success: authCallback.bind(this)
to ensure that this inside the callback actually represents your object.
You should also note that you cannot access this.shop until after the callback has completed. A more idiomatic implementation using modern jQuery techniques would be this:
this.auth = function() {
return $.ajax({
url: "http://website.com/api/auth/",
dataType: "jsonp"
}).done(this.authCallback.bind(this)).fail(function() {
console.log("bad auth");
});
};
this.authCallback = function(r) {
this.shop = r;
return this;
}
followed by:
var clazz = new ClassName(1);
clazz.auth().then(function(c) {
console.log(c.shop);
});