BackboneJS, having trouble with success and error when saving a model - javascript

For some reason, I cannot enter my success and error blocks when I am saving my model. Wether my response is successful "201" or error "404", my code will not hit the debugger lines. Does anyone know what could be going wrong?
SignInView.prototype.login = function(event) {
event.preventDefault();
return this.model.save(this.credentials(), {
type: 'POST',
url: 'http://localhost:3001/api/v1/users/sign_in'
}, {
success: (function(_this) {
return function(userSession, response) {
debugger;
return window.location.href = "/";
};
})(this),
error: (function(_this) {
return function(userSession, response) {
debugger;
var message;
message = $.parseJSON(response.responseText).error;
return alert(message);
};
})(this)
});
};

The save function only takes two parameters -- you are passing your success and error functions as a third param. Try the following:
SignInView.prototype.login = function(event) {
event.preventDefault();
return this.model.save(this.credentials(), {
type: 'POST',
url: 'http://localhost:3001/api/v1/users/sign_in',
success: (function(_this) {
return function(userSession, response) {
debugger;
return window.location.href = "/";
};
})(this),
error: (function(_this) {
return function(userSession, response) {
debugger;
var message;
message = $.parseJSON(response.responseText).error;
return alert(message);
};
})(this)
});
};

Related

Calling sync ready made async ajax javascript function

I want to call this function on button click after login and wait for result, to get token value. This function cannot be changed, it is async and supplied from other currently unavailable team.
I already tried something like this, but with no success. I get web service results, but I can't write appropriate sync call to wait to return token.
function getToken() {
param1 = "123456";
ajax_oauth(param1, function (success, response) {
success: return response.token;
});
}
function ajax_oauth(param1, callback) {
APP.debug("oauth login with param1 " + param1);
try {
APP.blockUI();
var DeviceID = APP.readRegistry(APP_CONFIG.REGISTRY.DeviceID);
//---------------------------------------------------------------
$.ajax(
auth_token_url,
{
method: "GET",
accept: 'application/json',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
'param1': param1,
'deviceId': DeviceID
}),
xhrFields: {
withCredentials: false
},
statusCode: {
201: function (response) {
APP_STATE.hasOauth = true;
APP.debug('got response 200 from oauth');
auth.login(response.token); //TODO read expiration from token
try {
var decoded = jwt_decode(response.token);
APP_STATE.uid = decoded.uid;
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
},
401: function () {
},
500: function () {
},
503: function () {
}
},
success: function (response) {
APP.unblockUI();
APP_STATE.restAvailable = true;
},
error: function (jqXHR, textStatus, errorThrown) {
APP.unblockUI();
APP_STATE.restAvailable = false;
APP.restError(auth_token_url, jqXHR, errorThrown, textStatus);
APP.callback(callback, false);
}
}
);
} catch (err) {
APP.error("unable to do oauth login, " + err);
}
};
After user clicks on login button, I want to call function ajax_oauth and to return token if params ok. If not, to return login error. Login can't be async, as far as I can see.
For whatever reason you can't tap into the original ajax response, you could intercept the request using $.ajaxPrefilter.
From your code it looks like auth_token_url has a global reference. You could use this to intercept the call by matching the outgoing request on the resource URL.
$.ajaxPrefilter('json', function(options, originalOptions, jqXHR) {
if (options.url === auth_token_url) {
jqXHR.done(function(response) {
try {
var decoded = jwt_decode(response.token);
console.log(decoded);
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
});
}
});
Note that this needs to be declared well before the request is made preferably after jQuery is loaded.

How to re render a .ejs page with new data after ajax request

I need to re render my homepage.ejs with new data on the server side after an ajax request. I know you can (somehow) re render the elements in the ajax callback but I was wondering if I could just re render my homapage.ejs since I have if statements that look for vacations, and current_user variables to set the right partialview.ejs
my ajax method:
function user_login(email, password) {
var data = {};
data.email_login = email;
data.password_login = password;
var message_header = $("#message_header");
$.ajax({
url: "/sign_in",
method: 'POST',
data: data
}).done(function (res) {
if (!res.success) {
message_header.text("Incorrect email of password. Please try again.").css("color", "red");
$("#username_textfield").val("");
$("#password_textfield").val("");
}
if (res.success) {
console.log("user logged");
}
});
my server side (inside of a query callback)
get_all_vacations(function (error, vacations) {
if (error) {
console.log("error when getting vacations " + error);
response.json({ success: false });
} else {
request.session.vacations = vacations;
response.render('the_vacation.ejs', { vacations : vacations, current_user : new_current_user }, function() {
response.json({success : true});
console.log("in render method");
});
}
});
i tried this but it does not work.
response.render('the_vacation.ejs', { vacations: vacations, current_user: new_current_user });
I think the simplest way, based on how your code is written would be to use window.location.reload(); when the login is successful.
function user_login(email, password) {
var data = {};
data.email_login = email;
data.password_login = password;
var message_header = $("#message_header");
$.ajax({
url: "/sign_in",
method: 'POST',
data: data
}).done(function (res) {
if (!res.success) {
message_header.text("Incorrect email of password. Please try again.").css("color", "red");
$("#username_textfield").val("");
$("#password_textfield").val("");
}
if (res.success) {
console.log("user logged");
window.location.reload(); // <--- Cause the browser to reload the EJS
}
});

Close modal in ajaxStop

I have the following code:
var menuButtonClick = {
onReady: function () {
$(document).on('click', '.menu-button', function () {
menuButtonClick.clickedButton($(this).html());
});
},
clickedButton: function (val) {
switch (val) {
case 'CheckModelBank':
modelBankHandler.get();
break;
}
}
}
var modelBankHandler = (function () {
var get = function () {
var selectedCellData = handsonTable.selectedCellData.get();
var webGrid = handsonTable.WebGrid.get();
$.ajax({
type: 'POST',
url: "http://localhost:56292/api/Data/CheckModelBank",
data: { "": selectedCellData },
success: function (response) {
if (response != null) {
serverResult = JSON.parse(response);
printModelBank(serverResult, webGrid);
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus == "error") {
modalHandler.printErrorModal();
}
}
});
}
var printModelBank = function (serverResult, webGrid) {
///
}
return {
get: get
}
})();
var fileHandler = {
onReady: function () {
var documentType = "";
$('.upload-file').click(function () {
$('[data-remodal-id=documentModal]').remodal().open();
});
$('.document-option').click(function () {
//Need to get the type of document the user is going to work with so we can parse the document correctly to the webgrid
documentType = $(this).html();
$('#fileUpload').click();
});
$('#fileUpload').change(function () {
fileHandler.upload(documentType);
});
$('.save-to-excell').click(fileHandler.saveDocument);
},
upload: function (documentType) {
var formData = new FormData();
var totalFiles = document.getElementById("fileUpload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("fileUpload").files[i];
formData.append("fileUpload", file);
}
$.ajax({
type: 'post',
url: 'http://localhost:59973/Home/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
jsonData = JSON.parse(response.data);
if (jsonData != null) {
if (documentType == "Infolog") {
fileHandler.printDocument(jsonData); //This is used for pickinglist and infolog
} else {
var webGrid = handsonTable.WebGrid.get();
webGrid.loadData(jsonData);
}
}
},
error: function (error) {
if (textStatus == "error") {
modalHandler.printErrorModal();
}
}
});
},
}
$(document).ready(function () {
handsonTable.init();
menuButtonClick.onReady();
fileHandler.onReady();
buttonClicks.onReady();
}).ajaxStart(function () {
$('[data-remodal-id=modalAjax]').remodal().open();
}).ajaxStop(function () {
$('[data-remodal-id=modalAjax]').remodal().close();
});
When I upload a file (fileHandler), the modal shows during ajaxStart and closes on ajaxStop. However, If I click on a button in my menu (menuButtonclick) which trigger my modelBankHandler function, the modal shows during ajaxstart, but does not close on ajaxStop.
Why? All the data are retrieved as expected in my modelBankHandler, so why does not the modal closes?
If you have pressed F12 in the browser and looked at the console you would probably have found an error there. This video might help you to figure out basic problems yourelf.
I think printModelBank might throw an error, if the success or error functions throw an error then jQuery crashes and does not execute the ajaxStop handler:
$(document)
.ajaxStart(function () {
console.log("open model");
}).ajaxStop(function () {
console.log("close model");
});
$.ajax({
type: 'GET',
url: "/none",
data: {},
success: function (response) {
console.log("success");
throw new Error("now stop won't execute");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
throw new Error("now stop won't execute");
}
});
You could solve this by having success and error as promise handlers, errors in promise handlers should not crash jQuery (but it does):
$(document)
.ajaxStart(function () {
console.log("open model");
}).ajaxStop(function () {
console.log("close model");
});
$.ajax({
type: 'GET',
url: "/none",
data: {}
})
.then(
response => {
console.log("success");
throw new Error("now stop won't execute");
},
(jqXHR, textStatus, errorThrown) => {
console.log("error");
throw new Error("now stop won't execute");
}
);
You could try native promises (jQuery still doesn't get promises right) and have it not crash on error in handler:
$(document)
.ajaxStart(function () {
console.log("open model");
}).ajaxStop(function () {
console.log("close model");
});
Promise.resolve()
.then(_ =>
$.ajax({
type: 'GET',
url: "/none",
data: {}
})
)
.then(
response => {
console.log("success");
throw new Error("now stop WILL execute");
},
(jqXHR, textStatus, errorThrown) => {
console.log("error");
throw new Error("now stop WILL execute");
}
);
IE does not support native promises so you will need a polyfill or try babel with ES2016

passing error message from service to controller in angularjs

Controller.js
var vm = this;
vm.admin = {};
vm.add = function () {
API.addAdmin(token, vm.admin)
.then(function (resp) {
vm.hideForm = true;
vm.showButton = true;
Notify.green(resp);
}, function (resp) {
Notify.red(resp);
});
};
API.js
function addAdmin(token, dataObj) {
return Constant.getApiUrl()
.then(function (url) {
$http({
method: 'POST',
url: url + '/client/admin',
headers: {
'Token': token
},
data: dataObj
}).then(handleResp);
function handleResp(resp) {
var responseStatus = (resp.status >= 200 && resp.status < 300) ? 'good' : 'bad';
if (responseStatus === 'good') {
console.log("Success" + resp);
return resp;
} else {
console.log("Failed" + resp);
return resp;
}
}
})
}
If I get a success response in API then i need to connect it to success function in my controller and if i get error message in my API, then i need it to connect it to error function in my controller.How should I evaluate the response status from my API(is either success or error).
I don't want to pass successfn, errorfn from my controller to API(only if there's no alternative).
I need to get the response data from API to controller to show it in Notify message.
Thank You!
In service (assign response values in "originalData"):
angular.module('appname').service('myserviceName', function(yourExistingService){
this.myFunction= function(originalData) {
//for next line to work return promise from your addAdmin method.
var promise = yourExistingService.getResponseFromURL(originalData);
return promise;
}
});
And in your controller :
var promise = myserviceName.myFunction($scope.originalData);
promise.$promise.then(function() {
console.log($scope.originalData);
});
And then you can check you "originalData" and write code according to your need.For more detail you can have a look on this http://andyshora.com/promises-angularjs-explained-as-cartoon.html.

Binding a service response in Angular JS

I am trying to send the http response as a JSON body to an error handler if an error occurs. I am not really sure how to do this as I am a little inexperienced in this area. Here is the relevant code that I have currently:
Controller:
for (var prop in $scope.applicants) {
var applicant = $scope.applicants[prop];
$scope.sendApplicantsToSR(applicant).then(null, $scope.sendATSError.bind(null, applicant));
}
$scope.sendATSError = function (applicant, error) {
return AtsintegrationsService.applicantErrorHandling(applicant.dataset.atsApplicantID);
};
$scope.sendApplicantsToSR = function(applicant) {
return AtsintegrationsService.sendApplicantsToSR(applicant);
};
Service:
srvc.sendApplicantsToSR = function (applicant) {
var applicantURL = {snip};
return $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
url: applicantURL,
data: applicant
});
};
srvc.applicantErrorHandling = function (applicantID, error) {
var url = srvc.url + {snip};
return $http({
method: 'POST',
url: url,
data: { "error_message": error }
});
};
So, ideally, I would like to pass the result of $scope.sendApplicantsToSR to $scope.sendATSError only when an error occurs.
Inside your controller
YourService.getdatafromservice().then(function(SDetails) {
//response from service
console.log(SDetails);
});
Inside your service
return {
getData: getData
};
function getData() {
var req = $http.post('get_school_data.php', {
id: 'id_value',
});
return req.then(handleSuccess, handleError);
function handleSuccess(response) {
response_data = response.data;
return response_data;
}
function handleError(response) {
console.log("Request Err: ");
}
}

Categories

Resources