Angular Js beginner Ajax Call - javascript

I'm new to angular js, Inside my controller.js are controllers for my app, which is 100% working. What I'm having problem is how to make an ajax call using angular js. I'm trying to fetch data from my service and pass it to my index.html using this ajax. When I try to debug the code, it only hits on $http but doesn't go through the code inside it. What am I doing wrong here?
$http({
method: 'POST',
url: 'http://someService.site.net/site.aspx',
data:{action:'someAction', position:'founders'},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response){
var json =jQuery.parseJSON(response);
var htmldata="";
for(i=0; i<json.length; i++)
{
var htmlInfo = '<li><div class=\'col\'><img width=\'100%\' height=\'auto\' src="'+json[i].Image + '" class=\'profile-img\' /><h3>' +json[i].Name+'</h3><p>'+json[i].Title+'</p></div></li>';
htmldata+= htmlInfo;
}
jQuery("#vflist").html(htmldata);
}, function errorCallback(response){
});

Mark your breakpoints on success and error callbacks.
$http is a service. You passed the required data in it's parameter.
$http({})
^options
After calling this $http will do it's work and send a request to the provided url asynchronously. But You don't need to debug that part.
$http({options})
.then(function(data){
// mark 1 breakpoint here
}, function(data){
// mark another breakpoint here
})

Since you are already using jQuery along with Angularjs I would recommend you to use the $.params() function to encode the parameter data.
Your $http would be like
$http({
method: 'POST',
url: 'http://someService.site.net/site.aspx',
data:$.params({action:'someAction', position:'founders'}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
Also I suggest you to use the Angular way of doing things rather than using jQuery. You might even like it ;)

First thing is: you can simply use your $http function like this:
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}};
$http.post('http://someService.site.net/site.aspx',
{action:'someAction', position:'founders'},
config)
.success(function(response) {
var json =jQuery.parseJSON(response);
var htmldata="";
for(i=0; i<json.length; i++) {
var htmlInfo = '<li><div class=\'col\'><img width=\'100%\' height=\'auto\' src="'+json[i].Image + '" class=\'profile-img\' /><h3>' +json[i].Name+'</h3><p>'+json[i].Title+'</p></div></li>';
htmldata+= htmlInfo;
}
jQuery("#vflist").html($sce.trustAsHtml(htmldata));
})
.error(function(data, status, headers, config) {
console.log(status);
});
Secondly, as you can see in the above code I have used $sce.trustAsHtml() -- this is required when you are pushing some html to DOM via $http - or it will just show the codes with tags. You have to inject $sce in the controller definition.

put this line before calling ajax this works for me hope for you to
$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
// YmVlcDpib29w you can put any string
This is also given in- https://docs.angularjs.org/api/ng/service/$http

Related

AngularJS $location.search() doesn't return anything

I am using AngularJS 1.6.4
The url of my homepage is http://localhost:8080/AsumForum/
I am trying to display a success message if user has registered successfully to my web site. If the user is registered, I will redirect him to the home page, and my url looks like this: http://localhost:8080/AsumForum/?registered=true.
The thing is, $location.search() never finds registered=true. I have tried making $locationProvider compatible with HTML5, but that doesn't work either.
Here is my registration.js:
var app = angular.module('reg',[]);
app.controller('valid', ['$scope','$location','$http',
function($scope,$location,$http){
$scope.send = function(){
var date = new Date();
$scope.user.date=date.toString();
$http({
url: 'http://localhost:8080/AsumForum/webapi/users/register',
dataType: 'json',
method: 'POST',
data: $scope.user,
headers: {
"Content-Type": "application/json"
}
}).then(function success(response){
$scope.res = response.data;
$scope.satus = response.status;
console.log('RES: '+$scope.res+'\nSTATUS: '+$scope.status);
window.location="http://localhost:8080/AsumForum/?registered=true";
}, function error(response){
$scope.res = response.statusText;
console.log('Error: +'+$scope.res);
});
}
}]);
And here is my login.js
var app = angular.module('mainPage',[]);
app.controller('regsuc',['$scope','$location',function($scope,$location){
$scope.message = '';
var show = $location.search();
for(var i in show){
console.log(i);
}
if(show==true){
$scope.message="Successfull registered! You can now log in.";
}
}]);
Logs don't return anything. Using console.log(show) returns [object Object].
Do I really have to use routing to pass parameters, or can it be done like I tried?
Note 1: Redirecting with $location.url('http://localhost:8080/AsumForum/?registered=true); doesn't work for me.
Note 2: Using location.search instead of $location.search returns ?registered=true.
Just try the following
you have missed the parameter name in $location.search()
$location.search().registered

Not Able to receive data from api server( with public ip) using ngReouce

I know this question in naive, but i stuck and new to angular. I search enough but not able to comeup with solution.
var app=angular.module('myApp',['ngResource']);
app.controller('myCtrl',['$scope','$resource',function ($scope,$resource) {
// body...
var data= $resource('http://ip/category/something',{"p1":76,"p3":9}, { charge: { method: 'POST' } });
console.log(data);
}]);
I am not able to fetch the data from the server and it return a function.
I need explanation if it is possible.
the problem you have is that the $resource service isnt a function that returns data from a request, it returns a $resource object, that has predefined methods to make those requests.
heres how you should do it to get what your looking for
var app=angular.module('myApp',['ngResource']);
app.controller('myCtrl',['$scope','$resource','$q',function($scope,$resource,$q) {
// body...
var data,
dataResource = $resource('http://ip/category/something',{"p1":76,"p3":9}, { charge: { method: 'POST' } });
data = dataResource.get();
$q.when(data.$promise).then(function(){
console.log(data);
});
}])
```
or something like that.

Angularjs firing request without request data

First of all my apologies if the question is repeated.
I am making ajax requests using $q service.
UtilityService.requestCall('/test/encrypt-data', {'json_string' : data_to_encrypt, 'encryption_key' : window.localStorage.getItem("Mi_Encryption_Key")})
.then(function(encrypt_response) {
var requestConoce = parseInt(window.localStorage.getItem("Mi_Cnonce")) + 1;
window.localStorage.setItem("Mi_Cnonce", requestConoce);
requestData['cnonce'] = requestConoce;
requestData['encrypted_data'] = encrypt_response.data;
return UtilityService.requestCall($scope.apiDetails.url, requestData, 'GET');
})
.then(function(api_response) {
var requestConoce = parseInt(window.localStorage.getItem("Mi_Cnonce")) + 1;
window.localStorage.setItem("Mi_Cnonce", requestConoce);
return UtilityService.requestCall('/test/decrypt-data', {'encrypted_string' : api_response.encrypted_data, 'encryption_key' : window.localStorage.getItem('Mi_Encryption_Key') });
})
.then(function(decrypt_response) {
$scope.serverResponse = JSON.stringify(decrypt_response);
return;
})
.catch(function(error) {
alert("Some Error");
})
MyApp.factory('UtilityService', ['$http', '$q', function($http, $q) {
return {
requestCall: function(requestUrl, requestData, methodType) {
var deferred = $q.defer();
var serverUrl = window.localStorage.getItem("Mi_Server_Url");
$http({
method: (methodType) ? methodType : "POST",
url: serverUrl + requestUrl,
data: requestData
})
.then(function(result) {
deferred.resolve(result.data);
},
function(error) {
deferred.reject(error);
});
return deferred.promise;
}
};}]);
I am making requests using the above code. It is working fine for the request "/test/encrypt-data"
But then request for $scope.apiDetails.url is not working. Request is made without any parameters But, I am sending all required parameters in requestData.
This code working for other (even I am sending the data) but not working for this request.
It seems angularjs requests two time for the same request once without data and other with data.
Please help for this strange issue. Please take a look on these images these are showing two different requests once with data and other without data.
First of all you are getting two requests because one of them is the OPTIONS call and one is the actual POST call. This is the normal behaviour and nothing to worry about.
The second request you are making is a GET request which cannot contain any POST-Data. This is just not supported by HTTP.
So depending on what the backend is expecting you could either turn that request into a POST request or you could add the data as GET parameters which is described here: in the Angular docs

How do I set a variable within an Angular JS service to the response data from an $http call within an AngularJS service?

I have the following service which I eventually want to cache. However, I can't seem to figure out how set a variable within the service to the response data from the REST call using $http in Angular.
routerApp.service('activityService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.temp = null;
this.setTemp(x) {
this.temp = x;
}
this.getActivities = function(x) {
var promise = $http({
method: 'GET',
url: 'my url is here...'
}).then(function(response) {
//setTemp(response.data); //definitely wont work
return response.data;
});
//how to set temp to response.data???
setTemp(promise.data); //doesn't work -
};
});
I don't know JS (or angular for that matter) very well. What is the best way to do this?
There is no need to cache the angular service, it's guaranteed to be a singleton.
If you mean to cache the response data, you will create a cache object in your service.
Now about the main question. In this code there is misuse of promises not angular services. Promises are asynchronous, meaning that a callback provided to .then() will be executed some time later, when request is finished. Besides .then returns another promise, which you should return from activityService.getActivities method.
this.getActivities = function(x) {
var promise = $http({
method: 'GET',
url: 'my url is here...'
}).then(function(response) {
setTemp(response.data); //meaning that setTemp somehow modifies it's argument
return response.data;
});
return promise;
};
Then in one of your controllers you will use this service's method attaching .then to it's return value.
.controller('someController', function (activityService) {
activityService.getActivities()
.then(function (data) {
doSomethingWithResponse(data);
}
});

Getting Json data in the Angularjs Scope

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.

Categories

Resources