Unable to update class variable after ajax call - javascript

After getting two integer upon the ajax request has been completed, this.N and this.M are not getting set by storeDims() even if the dims has correctly been decoded. So it seems that I cannot acces this.N and this.M declared in the constructor.
This is the code
class MapModel {
constructor() {
this.N; // need to initialize this after an ajax call
this.M;
this.seats = new Array();
this.remote_seats = new Array();
}
init(callback) {
let _this = this;
$.when(
_this.getDims(),
_this.getSeats(),
).then(this.initMap(callback))
}
initMap(callback) {
console.log(this.N); // prints undefined
console.log(this.M); // this as well
callback(this.N, this.M, this.seats);
}
getDims() {
let _this = this;
$.ajax({
url: 'src/php/data.php',
type: 'POST',
data: {action: 'getDims'},
success: function (result) {
let dims = JSON.parse(result); // dims[0] = 10, dims[1] = 6
_this.storeDims(dims);
}
});
}
storeDims(dims) {
console.log(dims);
this.N = parseInt(dims[0]);
this.M = parseInt(dims[1]);
console.log(this.N);
console.log(this.M);
}
getSeats() {
let _this = this;
$.ajax({
url: 'src/php/data.php',
type: 'POST',
data: {action: 'getSeats'},
success: function (result) {
let seats = JSON.parse(result);
_this.storeSeats(seats);
}
});
}
storeSeats(seats) {
this.remote_seats = seats;
console.log(this.remote_seats);
}
}

You need to return the ajax promises from the getDms and getSeats functions
getDims() {
let _this = this;
return $.ajax({
url: 'src/php/data.php',
type: 'POST',
data: {action: 'getDims'},
success: function (result) {
let dims = JSON.parse(result); // dims[0] = 10, dims[1] = 6
_this.storeDims(dims);
}
});
}
you can even pass the values directly to the initMap
init(callback) {
let _this = this;
$.when(
_this.getDims(),
_this.getSeats()
).then(function(dims,seats) {_this.initMap(dims,seats,callback)})
}
initMap(dimsRaw,seatsRaw, callback) {
let dims = JSON.parse(dimsRaw);
console.log(dims[0]);
console.log(dims[1]);
callback(dims[0], dims[1], this.seats);
}

The init promise callback is being called on the chain declaration, try adding a function wrapper:
init(callback) {
let _this = this;
$.when(
_this.getDims(),
).then(function() {_this.initMap(callback)})
}

Related

Defining function without calling it immediately without events (on click/hover...)

I have a really huge jquery function, and to make it easier to read, I'd like to know how can I put it somewhere else and call it only inside another function (to be more specific, inside an ajax call, where I have it defined right now).
The problem is that when I define the function, it runs automatically, and I don't want that. I want it to run inside the ajax call, but not define it there.
Here's a sample code of what I have:
$.ajax({
type: 'post',
url: 'api/'+$("#id").val()+"/"+$("#from").val()+"/"+$("#to").val(),
data: {},
success: function generateChart(data) {
var results = JSON.parse(data);
if (results.error == true) {
var errCode = results.code;
alert(errCode);
}
else {
var chartjsTemp = [];
var chartjsDate = [];
for (var i = 0; i < results.length; i++) {
chartjsTemp.push(results[i].probeTemp);
chartjsDate.push(results[i].dateProbe);
}
var ctx = document.getElementById('myChart').getContext('2d');
var button = $("#submitButton");
submitButton.addEventListener("click", function(){
myChart.destroy();
});
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: chartjsDate,
datasets: [{
label: 'temp',
data: chartjsTemp,
backgroundColor: "rgba(240,240,240,0.5)"
}]
}
});
}
}
});
I want to put my "generateChart" function somewhere else. If I put it "somewhere else" and do just "success: generateChart()" it won't work, and instead run when the page loads.
You should call an external function, like this:
function extFunc(data){
...
}
$.ajax({
type: 'post',
url: 'xxx',
data: {},
success: function generateChart(data) {
extFunc(data);
}
});
You should be able to save all your functions in variables without actually calling them.
Here's an example:
var myFunc = function(param1) {
console.log(param1);
}
$(function() {
myFunc('test');
myFunc('test2');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Edit:
With your code sample it's basically the same.
Just define the success function outside and then call it on success.
If you success: generateChart(data) you could also try:
success: function(data) { generateChart(data); }.
Just move the definition outside an ajax call:
function generateChart(data) {
var results = JSON.parse(data);
if (results.error == true) {
var errCode = results.code;
alert(errCode);
} else {
var chartjsTemp = [];
var chartjsDate = [];
for (var i = 0; i < results.length; i++) {
chartjsTemp.push(results[i].probeTemp);
chartjsDate.push(results[i].dateProbe);
}
var ctx = document.getElementById('myChart').getContext('2d');
var button = $("#submitButton");
submitButton.addEventListener("click", function(){
myChart.destroy();
});
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: chartjsDate,
datasets: [{
label: 'temp',
data: chartjsTemp,
backgroundColor: "rgba(240,240,240,0.5)"
}]
}
});
}
}
$.ajax({
type: 'post',
url: 'api/'+$("#id").val()+"/"+$("#from").val()+"/"+$("#to").val(),
data: {},
success: function(data) {
generateChart(data);
}
});

calling ajax function from knockout value undefined

I have a view model in knockout as follow. What i intend to achieve here is to make the ajax call into a reusable function as follow (and include it into separate js file).
However, I got the error message showing self.CountryList is not defined. How could this be resolved?
// Working
var ViewModel = function() {
var self = this;
self.CountryList = ko.observableArray([]);
self.LoadCountry = function() {
$.ajax({
url: '/api/MyApi',
type: 'GET',
dataType: 'json',
success(data): {
$.each(data, function (index, value) {
self.CountryList.push(value);
});
}
});
}
}
ko.applyBindings(new LoadCountry());
// Not working
function LoadCountryList() {
$.ajax({
url: '/api/MyApi',
type: 'GET',
dataType: 'json',
success(data): {
$.each(data, function (index, value) {
self.CountryList.push(value);
});
}
});
}
var ViewModel = function() {
var self = this;
self.CountryList = ko.observableArray([]);
self.LoadCountry = function() {
LoadCountryList();
}
}
ko.applyBindings(new LoadCountry());
Your LoadCountryList function in the second version has no concept of the object it should be operating on - ie it has no idea what self is, hence the error. The simple solution is for you to pass the object in when calling the function:
function LoadCountryList(vm) {
$.ajax({
url: '/api/MyApi',
type: 'GET',
dataType: 'json',
success(data): {
$.each(data, function (index, value) {
//reference the parameter passed to the function
vm.CountryList.push(value);
});
}
});
}
var ViewModel = function() {
var self = this;
self.CountryList = ko.observableArray([]);
self.LoadCountry = function() {
//pass ourselves to the function
LoadCountryList(self);
}
}
well clearly self.ContryList does not exist in your external file. One easy way to solve this is to pass in a reference to the appropriate "list" to push values to:
function LoadCountryList(countryList) {
$.ajax({
url: '/api/MyApi',
type: 'GET',
dataType: 'json',
success(data): {
$.each(data, function (index, value) {
countryList.push(value);
});
}
});
}
and in your view model:
var ViewModel = function() {
var self = this;
self.CountryList = ko.observableArray([]);
self.LoadCountry = function() {
LoadCountryList(self.CountryList);
}
}

AJAX sending object with functions throws error at function

I have the following Ajax:
$.ajax({
type: 'POST',
url: '/Jeopardy/saveCategoryData',
dataType: 'json',
data: {
name: this.name,
questions: this.question_array,
sort_number: this.sort_number,
game_id: game_id
},
success: function (data)
{
this.id = data;
}
});
Update This is the full class the ajax is apart of:
function Category(name, sort_number)
{
this.name = name;
this.sort_number = sort_number;
this.question_array = [];
this.id = 0;
/*
Functions
*/
}
Category.prototype.saveCategory = function()
{
$.ajax({
type: 'POST',
url: '/Jeopardy/createCategory',
dataType: 'json',
data: {
request: 'ajax',
name: this.name,
sort_number: this.sort_number,
game_id: game_id
},
success: function (data)
{
this.id = data;
}
});
$('.category_'+this.sort_number).each(function()
{
$(this).css('opacity', '1');
$(this).addClass('question');
})
}
Category.prototype.submitCategory = function()
{
$.ajax({
type: 'POST',
url: '/Jeopardy/saveCategoryData',
dataType: 'json',
data: {
request: 'ajax',
name: this.name,
questions: this.question_array,
sort_number: this.sort_number,
game_id: game_id
},
success: function (data)
{
this.id = data;
}
});
}
Category.prototype.addQuestion = function(question,index)
{
this.question_array[index] = question
}
Where this.question_array is an array of question objects:
function Question(question, score)
{
this.question = question;
this.score = score;
this.answer = [];
}
Question.prototype.getScore = function()
{
return this.score;
}
Question.prototype.addAnswer = function(answer)
{
this.answer.push(answer)
}
My answer object:
function Answer(answer, is_correct)
{
this.answer = answer;
this.is_correct = is_correct;
}
When my Ajax submits i get an error at the function addAnswer saying: Cannot read property 'push' of undefined
Can anyone tell me why this might be happening (i am fairly new to OOP in JavaScript)
Update create.js (script that controls the objects)
save question function:
function saveQuestion() {
var question = new Question($('#txt_question').val(), current_money);
var array_index = (current_money / 100) - 1;
$('.txt_answer').each(function ()
{
var answer = new Answer($(this).val(), $(this).prev().find('input').is(':checked'));
question.addAnswer(answer); // <-- Add answer
})
if(current_element.find('.badge').length == 0)
{
current_element.prepend('<span class="badge badge-sm up bg-success m-l-n-sm count pull-right" style="top: 0.5px;"><i class="fa fa-check"></i></span>');
}
addQuestionToCategory(question, array_index);
questionObject.fadeOutAnimation();
}
function addQuestionToCategory(question, index) {
switch (current_category_id) {
case "1":
category_1.addQuestion(question, index);
break;
case "2":
category_2.addQuestion(question, index);
break;
case "3":
category_3.addQuestion(question, index);
break;
case "4":
category_4.addQuestion(question, index);
break;
}
}
And the function that calls the ajax on each category object:
function saveGame()
{
category_1.submitCategory();
category_2.submitCategory();
category_3.submitCategory();
category_4.submitCategory();
}
Debug callstack:
Question.addAnswer (question.js:25)
n.param.e (jquery-1.11.0.min.js:4)
Wc (jquery-1.11.0.min.js:4)
Wc (jquery-1.11.0.min.js:4)
(anonymous function) (jquery-1.11.0.min.js:4)
n.extend.each (jquery-1.11.0.min.js:2)
Wc (jquery-1.11.0.min.js:4)
n.param (jquery-1.11.0.min.js:4)
n.extend.ajax (jquery-1.11.0.min.js:4)
Category.submitCategory (category.js:47)
saveGame (create.js:116)
onclick (create?game_id=1:182)
*UPDATE
Okay something odd is going on if i change the addAnswer function to the following:
Question.prototype.addAnswer = function(answer)
{
if(this.answers != undefined)
{
this.answers.push(answer)
}
}
It works fine?
Looks like Alexander deleted his response, here is what I would suggest:
function Question(question, score)
{
this.question = question;
this.score = score;
this.answer = [];
}
Question.prototype.getScore = function()
{
return this.score;
}
Question.prototype.submitQuestion = function()
{
}
Question.prototype.addAnswer = function(answer)
{
this.answer.push(answer)
}

Does jQuery.ajax() not always work? Is it prone to miss-fire?

I have an $.ajax function on my page to populate a facility dropdownlist based on a service type selection. If I change my service type selection back and forth between two options, randomly the values in the facility dropdownlist will remain the same and not change. Is there a way to prevent this? Am I doing something wrong?
Javascript
function hydrateFacilityDropDownList() {
var hiddenserviceTypeID = document.getElementById('<%=serviceTypeID.ClientID%>');
var clientContractID = document.getElementById('<%=clientContractID.ClientID%>').value;
var serviceDate = document.getElementById('<%=selectedServiceDate.ClientID%>').value;
var tableName = "resultTable";
$.ajax({
type: 'POST',
beforeSend: function () {
},
url: '<%= ResolveUrl("AddEditService.aspx/HydrateFacilityDropDownList") %>',
data: JSON.stringify({ serviceTypeID: TryParseInt(hiddenserviceTypeID.value, 0), clientContractID: TryParseInt(clientContractID, 0), serviceDate: serviceDate, tableName: tableName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
a(data);
}
,error: function () {
alert('HydrateFacilityDropDownList error');
}
, complete: function () {
}
});
}
function a(data) {
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
var tableName = "resultTable";
if (facilityDropDownList.value != "") {
selectedFacilityID = facilityDropDownList.value;
}
$(facilityDropDownList).empty();
$(facilityDropDownList).prepend($('<option />', { value: "", text: "", selected: "selected" }));
$(data.d).find(tableName).each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
$(facilityDropDownList).append(option);
});
if ($(facilityDropDownList)[0].options.length > 1) {
if ($(facilityDropDownList)[0].options[1].text == "In Home") {
$(facilityDropDownList)[0].selectedIndex = 1;
}
}
if (TryParseInt(selectedFacilityID, 0) > 0) {
$(facilityDropDownList)[0].value = selectedFacilityID;
}
facilityDropDownList_OnChange();
}
Code Behind
[WebMethod]
public static string HydrateFacilityDropDownList(int serviceTypeID, int clientContractID, DateTime serviceDate, string tableName)
{
List<PackageAndServiceItemContent> svcItems = ServiceItemContents;
List<Facility> facilities = Facility.GetAllFacilities().ToList();
if (svcItems != null)
{
// Filter results
if (svcItems.Any(si => si.RequireFacilitySelection))
{
facilities = facilities.Where(f => f.FacilityTypeID > 0).ToList();
}
else
{
facilities = facilities.Where(f => f.FacilityTypeID == 0).ToList();
}
if (serviceTypeID == 0)
{
facilities.Clear();
}
}
return ConvertToXMLForDropDownList(tableName, facilities);
}
public static string ConvertToXMLForDropDownList<T>(string tableName, T genList)
{
// Create dummy table
DataTable dt = new DataTable(tableName);
dt.Columns.Add("OptionValue");
dt.Columns.Add("OptionText");
// Hydrate dummy table with filtered results
if (genList is List<Facility>)
{
foreach (Facility facility in genList as List<Facility>)
{
dt.Rows.Add(Convert.ToString(facility.ID), facility.FacilityName);
}
}
if (genList is List<EmployeeIDAndName>)
{
foreach (EmployeeIDAndName employeeIdAndName in genList as List<EmployeeIDAndName>)
{
dt.Rows.Add(Convert.ToString(employeeIdAndName.EmployeeID), employeeIdAndName.EmployeeName);
}
}
// Convert results to string to be parsed in jquery
string result;
using (StringWriter sw = new StringWriter())
{
dt.WriteXml(sw);
result = sw.ToString();
}
return result;
}
$get return XHR object not the return value of the success call and $get function isn't synchronous so you should wait for success and check data returned from the call
these two lines do something different than what you expect
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
change to something similar to this
var facilityDropDownList;
$.ajax({
url: '<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>',
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
facilityDropDownList= data;
}
});

How to initialize knockoutjs view model with .ajax data

The following code works great with a hardcoded array (initialData1), however I need to use jquery .ajax (initialData) to initialize the model and when I do the model shows empty:
$(function () {
function wiTemplateInit(winame, description) {
this.WIName = winame
this.WIDescription = description
}
var initialData = new Array;
var initialData1 = [
{ WIName: "WI1", WIDescription: "WIDescription1" },
{ WIName: "WI1", WIDescription: "WIDescription1" },
{ WIName: "WI1", WIDescription: "WIDescription1" },
];
console.log('gridrows:', initialData1);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{UserKey: '10'}",
url: "WIWeb.asmx/GetTemplates",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
initialData.push(new wiTemplateInit(data.d[i].WiName,data.d[i].Description));
}
//console.log('gridrows:', initialData);
console.log('gridrows:', initialData);
}
});
var viewModel = function (iData) {
this.wiTemplates = ko.observableArray(iData);
};
ko.applyBindings(new viewModel(initialData));
});
I have been trying to work from the examples on the knockoutjs website, however most all the examples show hardcoded data being passed to the view model.
make sure your "WIWeb.asmx/GetTemplates" returns json array of objects with exact structure {WIName : '',WIDescription :''}
and try using something like this
function wiTemplateInit(winame, description)
{
var self = this;
self.WIName = winame;
self.WIDescription = description;
}
function ViewModel()
{
var self = this;
self.wiTemplates = ko.observableArray();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{UserKey: '10'}",
url: "WIWeb.asmx/GetTemplates",
success: function (data)
{
var mappedTemplates = $.map(allData, function (item) { return new wiTemplateInit(item.WiName, item.Description) });
self.wiTemplates(mappedTemplates);
}
});
}
var vm = new ViewModel();
ko.applyBindings(vm);
If you show us your browser log we can say more about your problem ( Especially post and response ). I prepared you a simple example to show how you can load data with ajax , bind template , manipulate them with actions and save it.
Hope this'll help to fix your issue : http://jsfiddle.net/gurkavcu/KbrHX/
Summary :
// This is our item model
function Item(id, name) {
this.id = ko.observable(id);
this.name = ko.observable(name);
}
// Initial Data . This will send to server and echo back us again
var data = [new Item(1, 'One'),
new Item(2, 'Two'),
new Item(3, 'Three'),
new Item(4, 'Four'),
new Item(5, 'Five')]
// This is a sub model. You can encapsulate your items in this and write actions in it
var ListModel = function() {
var self = this;
this.items = ko.observableArray();
this.remove = function(data, parent) {
self.items.remove(data);
};
this.add = function() {
self.items.push(new Item(6, "Six"));
};
this.test = function(data, e) {
console.log(data);
console.log(data.name());
};
this.save = function() {
console.log(ko.mapping.toJSON(self.items));
};
}
// Here our viewModel only contains an empty listModel
function ViewModel() {
this.listModel = new ListModel();
};
var viewModel = new ViewModel();
$(function() {
$.post("/echo/json/", {
// Data send to server and echo back
json: $.toJSON(ko.mapping.toJS(data))
}, function(data) {
// Used mapping plugin to bind server result into listModel
// I suspect that your server result may contain JSON string then
// just change your code into this
// viewModel.listModel.items = ko.mapping.fromJSON(data);
viewModel.listModel.items = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
});
})

Categories

Resources