My javascript function is working in angular, but I want to have an error function to determine of there is an error when a bad request is sent. How could I put the error function in this kind of format of code in javascript? Thanks in advance to those who want to help me.
$scope.submitLogin = function()
{
var request = {};
request.url = '/account/users/login';
request.method = 'POST';
request.data = angular.toJson($scope.students);
var onSuccess = function(data, status, headers, config, statusText)
{
alert('success!');
$location.url('/examdirection/');
};
httpRequest(request, $scope.response, onSuccess);
};
Related
So I am learning Angular , and I would like to make a web Application which consumes a Restful Web service . So my page looks like this :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html ng-app="Tripeew">
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tripeew</title>
</head>
<body ng-controller="region">
<h1>Hello World !!</h1>
<p>Id : {{All.id}}</p>
<p>Nom :{{All.nom}}</p>
<br/>
<script type="text/javascript">
var myapp = angular.module('Tripeew',[]);
myapp.controller('region',function($scope,$http){
$http.get('http://localhost:9090/Tripeew_V1.0/webresources/tripeewws.regions/3').succes(function(){
$scope.All = response.data ;
});
});
</script>
</body>
</html>
But I can't have the result of the ws , which is working via URL , all I get is this :
Hello World !!
Id : {{All.id}}
Nom :{{All.nom}}
Use this syntax:
$http.get('http://localhost:9090/Tripeew_V1.0/webresources/tripeewws.regions/3').then(function(response) {
$scope.All = response.data ;
});
Error is occured because AngularJS version that author uses is 1.6.9, but success()/error() was deleted in 1.6.0-rc.0 version (see Changelog).
BREAKING CHANGE:
$http's deprecated custom callback methods - success() and
error() - have been removed. You can use the standard
then()/catch() promise methods instead, but note that the method
signatures and return values are different.
success(fn) can be replaced with then(fn), and error(fn) can be
replaced with either then(null, fn) or catch(fn).
Before:
$http(...).
success(function onSuccess(data, status, headers, config) {
// Handle success
...
}).
error(function onError(data, status, headers, config) {
// Handle error
...
});
After:
$http(...).
then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
}, function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
});
// or
$http(...).
then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
}).
catch(function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
});
Note: There is a subtle difference between the variations showed above. When using $http(...).success(onSuccess).error(onError) or
$http(...).then(onSuccess, onError), the onError() callback will
only handle errors/rejections produced by the $http() call. If the
onSuccess() callback produces an error/rejection, it won't be
handled by onError() and might go unnoticed. In contrast, when using
$http(...).then(onSuccess).catch(onError), onError() will handle
errors/rejections produced by both $http() and onSuccess().
The success syntax is deprecated since Angular 1.4.3. If you're using a newer version of Angular you should use the then syntax.
Well, there are two problems with your code. First one is obvious as everbody have told you to correct the typo of sucess to success and second you're not passing response to your handler function that you wrote in success. I mean you should pass the data like .success((response)=> $scope.All = response.data).
Notice, I am passing response to success callback.
Moreover, you better use the following syntax to make http requests with angularjs
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I have a string that is used to display text. It is initially set to null, then is updated throughout a function with status updates. I want to make sure the string is set to the correct status updates throughout the function's lifetime.
Jasmine's spies seem focused on testing functions and their interactions. I specifically want to test a string's history. Assuming the following code:
(function() {
$this.loggingIn = false;
$this.submit = function () {
$this.loggingIn = "Requesting access...";
$this.errorMessage = "";
var aThing = {};
var aSecondaryThing = {};
$http.post(aThing)
.success(function (data, status, headers, config) {
$this.loggingIn = "Validating credentials...";
$http.post(aSecondaryThing)
.success(function (data, status, headers, config) {
$this.loggingIn = "Done!";
})
.error(function (data, status, headers, config) {
$this.errorMessage = data.error_description || "Invalid username or password.";
$this.loggingIn = false;
});
})
.error(function (data, status, headers, config) {
$this.errorMessage = data.error_description || "Invalid username or password.";
$this.loggingIn = false;
});
return false;
};
})();
This function is abridged from our original Angular code. Nothing's missing aside from the wiring to make the controller work and the post actions.
Is there a way to test that loggingIn is set to "Validating credentials..." and then "Done!" without writing a setter function to handle it?
Ultimately we went with a setter function to handle the string management and testing. Although testing what the string actually says probably isn't needed, at the time it was required enough to need verification. That way we can verify if the function was being called, and then later verify the function changes the string correctly, which is proper testing in any case.
This is my first attempt at using Angularjs framework. I am trying to follow this example: http://jsfiddle.net/SAWsA/11/
I am successfully able to get the data in the Json format and it works fine.
json data:
[{"Activity_Matrix_ID":"163","Activity_ID":"131","Activity_Date":"2062-02-16","Activity_Category":"Maintanence","Activity_Project":"All Projects","Activity_Description":"Json data ","Activity_Hours":"2"},{"Activity_Matrix_ID":"161","Activity_ID":"129","Activity_Date":"2044-02-25","Activity_Category":"Tech Support","Activity_Project":"All Projects","Activity_Description":"Dummy dummy ","Activity_Hours":""}]
So basically, I want to load the data in $scope.items. I am not sure if it is the good method. I can visit the url and the data looks fine. I am stuck at getting the json correctly from the URL to the angular scope.
I tried following
<script type="text/javascript">
var sortingOrder = 'Activity_Projects';
</script>
<script>
function ctrlRead($scope, $filter) {
$scope.myData = function(item, event) {
var responsePromise = $http.get({method: 'GET', url: 'https://url_root_same_domain/timesheet/timesheet_info_table_json.php'}).success(function(data, status, headers, config) {
$scope.items = data;
console.log(data);
}).
error(function(data, status, headers, config) {
alert("No data");
});
}
</script>
Try this:
var responsePromise = $http.get('https://url_root_same_domain/timesheet/timesheet_info_table_json.php').success(...rest of your code here
The $http.get() function's first argument is a URL; not an object; and the method of a get call is already get, so you shouldn't have to do any other changes.
I have mulled over this for days and can still not figure out what I'm doing incorrectly so any ideas or even shots in the dark are appreciated. I am trying to display the response from a rest service to the user using the using the AngularJS $http get method, but when I print the data object to the console, I consistently receive the number 200 (I'm fairly certain it is giving me the status code). I hit success every time and, upon sending the request, the Chrome debug tool shows me the response with all the correct data. I just can't seem to get it to appear in a variable for display. Let me know if you think of anything! Thanks!
My javascript:
$scope.resendDestinations = [];
$scope.resendDestGet = function () {
var omtTypeCodeString = '';
for(var i = 0; i < $scope.mySelections.length; i++){
if(omtTypeCodeString == ''){
omtTypeCodeString = $scope.mySelections[i].orderHeader.omtOrderTypeCode;
}
else{
omtTypeCodeString = omtTypeCodeString + ',' + $scope.mySelections[i].orderHeader.omtOrderTypeCode;
}
}
$http({
method: 'GET',
url: restService.pom + //service url,
respondType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials': true
},
params: {
orderTypeCode: omtTypeCodeString,
transactionCode: 3
}
}).success(function (status, data, response, header) {
console.log("Success!");
//TODO see if this is being used... has to be
status = parseInt(status);
$scope.resendDestinations = data.multipleOrders;
if (status == 200 && $scope.resendDestinations.length == 0) {
$scope.bigAlert.title = 'Error',
$scope.bigAlert.header = 'Search Error';
$scope.bigAlert.content = 'Current search parameters do not match any results.';
$scope.showBigAlert();
}
else{
$scope.resendDestinations = data;
console.log("Data DestinationList here: ");
console.log($scope.resendDestinations);
console.log(data.multipleOrders);
console.log(data);
}
$scope.isSearching = false;
}).error(function (response, data, status, header) {
//Do error things
});
return $scope.resendDestinations;
};
And the service response:
[{"destCode":3,"destDescr":"Repository","attributes":null},{"destCode":4,"destDescr":"Pipeline","attributes":null},{"destCode":1,"destDescr":"Processor","attributes":null},{"destCode":2,"destDescr":"DEW","attributes":null},
{"destCode":7,"destDescr":"Management System","attributes":null},
{"destCode":8,"destDescr":"Source","attributes":null}]
You have the arguments in the wrong order. It should be: success(function(data, status, headers, config)
See the docs here (click).
Also, the .then() method is generally preferred. If you switch to that, you would access the data like this:
.then(function(response) {
var data = response.data;
var status = response.status;
//etc
});
I am overriding the JQuery Ajax XHR object with my custom implementation in order to 'fake' serquest to server and response from server.
I created simple example of what I try to achive in JS fiddle - in JS part I am defining very simple, global sendAjax() function that suppose to call server using $.ajax():
window.sendAjax = function() {
var jqxhr = $.ajax({
url: "/ServerResource.txt"
});
jqxhr.done(function (data, textStatus, jqXHR) {
//this is never called
alert("done !")
});
jqxhr.fail(function (jqXHR, textStatus, errorThrown) {
//this is never called
alert("fail " + errorThrown);
});
}
also I try to substitute JQuery ajax xhr object using my own XHR where I replaced 'send()' method with my own implementation that suppose to return some data instead of XHTTPrequest - for the now in JSfiddle I am going to return imediately 'sucess' response. The problem is that the done or fail functions do not react on my response at all :(
Here is my redefinition of XHR
//reload jquery ajax
var originalXhr = jQuery.ajaxSettings.xhr;
$.ajaxSetup({
xhr: function () {
var req = originalXhr();
var deferred = $.Deferred();
var promise = deferred.promise(req);
if (req) {
// Add your progress handler
var _send = req.send;
req.send = function (headers, complete) {
//the one below does not work
setTimeout(function () {
deferred.resolve("Resolve promise", "OK", req);
}, 200);
}
var _open = req.open;
req.open = function () {
console.log('OPEN AJAX called');
}
}
return promise;
}
});
I probably do something and $.Deferred does not work in the way I wont it, but I cannot figure what is wrong so far.
Here is JS fiddle http://jsfiddle.net/ZwPXs/ - might be you have some ideas?
Best regards, Artem