How to replace ajax call with $http, AngularJs - javascript

I am trying to implement angular.js in my php file, Because it's only one file project, So I am thinking where I use AngularJS. So i decided to replace AJAX call with $http.
For this i imported google angular js file
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
And replace my this ajax call
$.ajax({
url: url,
type: "GET",
data: data,
async: false,
success: function(res) {
resData = res;
}
});
With
$http({
url: url,
method: "GET",
data: data
}).success(function(data, status, headers, config) {
resData = data;
}).error(function(data, status, headers, config) {
resData = data;
});
beside these nothing changed, but when i am trying to execute my code, I am getting this error
$http is not defined

In order to use $http you first need to inject it into your controller
var module = angular.module('putNameHere', [])
module.controller('myCtrl', ['$http', function($http){ //injection here
$http({
url: url,
method: "GET",
data: data
}).success(function(data, status, headers, config) {
resData = data;
}).error(function(data, status, headers, config) {
resData = data;
});
}])

You are going to have to actually load an angular module and controller, then inject $http into the controller:
<script>
var app = angular.module('app', []);
app.controller('HttpCtrl', function($http) { //this is the $http injection here
//insert your $http code here
})
</script>
Plunker Demo (change google.com to whatever url you need to use)
You will also need to add the ng-app='app' attribute to your <html> tag, and the ng-controller='HttpCtrl' attribute to your <body> tag.

The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise with two $http specific methods: success and error.
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
source https://docs.angularjs.org/api/ng/service/$http

Related

Success Callback not called when $http post is in method scope

I am trying to achieve a login functionality using Angular JS on front-end and PHP + Zend on the back-end. Below is the code snippet of the angular js controller. This doesn't redirect the user to the appropriate page and while debugging, the control doesn't enter the success part but enters the error part with data being NULL. However if I put the $http part outside the function, atleast the control enters the success part with data being that of the next page to be redirected.
What could i be missing and what is the correct way to achieve the redirection?
In the below code the control doesn't enter the success section.
var myApp = angular.module('myApp',[]);
myApp.controller('loginCtrl', function ($scope, $http) {
$scope.authenticatelogin = function () {
$http({
url: "/admin/auth/authenticatelogin",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({login: $scope.login, password: $scope.password, rememberMe: $scope.remember})
}).success(function(data, status, headers, config) {
$window.location.href= "index/index";
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
};
});
In the below code the control enters the success section.
var myApp = angular.module('myApp',[]);
myApp.controller('loginCtrl', function ($scope, $http) {
$http({
url: "/admin/auth/authenticatelogin",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({login: 'abc#abc.com', password: 'xyzxyz', rememberMe: ''})
}).success(function(data, status, headers, config) {
$window.location.href= "index/index";
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
});
I would rather go for success/error callbacks to be part of the then method.
From angular documentation for version 1.4.5:
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
Try this one, although if you say that your code works outside the closure, it might not be the solution you are looking for:
$http({
url: "/admin/auth/authenticatelogin",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({login: $scope.login, password: $scope.password, rememberMe: $scope.remember})
}).then(function(data, status, headers, config) {
$window.location.href= "index/index";
$scope.data = data;
}, function(data, status, headers, config) {
$scope.status = status;
});

Angular $http.post not returning XML

I am trying to call a web service with angular, but not having much luck. The service takes a POST request with no POST body, and returns XML. I can confirm that the service works with a raw XMLHttpRequest call:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4)
console.log(xhr.responseText); // Returns data
}
xhr.open("POST", "https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML", true);
xhr.send(null);
And with jQuery:
$.ajax({
url: 'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML',
type: "POST",
success: function(data){
console.log(data); // Returns data
},
error: function (hxr, status, errorThrown){
console.log(status);
}
});
However, I'm not getting anything back when I try it with angular's $http service:
angular.module('TestApp',[])
.controller('TestController', function($scope, $http){
$http({
method: "POST",
url: 'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML'
}).success(function(data, status, headers, config){
console.log("data:");
console.log(data); // Returns null
}).error(function(data, status, headers, config){
console.log("error status:");
console.log(status); // No errors returned
})
})
EDIT: Using the $http.post shortcut method:
angular.module('TestApp',[])
.controller('TestController', function($scope, $http){
$http.post(
'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML'
).success(function(data, status, headers, config){
console.log("data:");
console.log(data);
}).error(function(data, status, headers, config){
console.log("error status:");
console.log(status);
})
})
Note that the $http.post shortcut method has a second data parameter, but I have no data to pass. If I include the parameter as null, Chrome says:
Request header field Content-Type is not allowed by Access-Control-Allow-Headers
Since the $http.post shortcut method does not complain about missing out the data parameter, I have deliberately missed it out.
I need to be able to make the POST call with no data, as is possible with a raw XMLHttpRequest call, or jQuery's ajax method. What might be going wrong? Thanks!
(NB, the API is public, so don't worry about the API key I've posted. It's a valid API key, which I'll keep active only while this question is open)
Angular by default expecting to get JSON from your server you can change that by adding
var app = angular.module('app', []);
app.controller('homeCtrl', function($scope, $http) {
$scope.xml = "";
$http({
method: "POST",
url: 'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML',
headers: {
"Accept": "application/xml"
}
}).success(function(data, status, headers, config) {
console.log("data:");
console.log(data); // Returns null
$scope.xml = data;
}).error(function(data, status, headers, config) {
console.log("error status:");
console.log(status); // No errors returned
})
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">
{{xml}}
</div>
</div>
to your request

variable is not shareable in http $scope

$http({
url: "php/InsertTab.php",
method: "POST",
data: {
'userId': userId,
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
myVar = data;
}).error(function(data, status, headers, config) {
});
console.log(myVar);
can variable myVar be share / be access outside the scope of $http? I wrote console.log(myVar) outside it returned blank?
u have to use angular $q service in order to use myVar outside of $http.
try reading in this page : https://docs.angularjs.org/api/ng/service/$q

$http scope issue with variable

$http({
url: "php/myuId.php",
method: "POST",
data: {
'userId': userId,
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
$scope.myId= data;
//return last inserted id
}).error(function(data, status, headers, config) {
});
//can't use it outside?
$scope.user.push({
"userId": $scope.myId,
});
strange, $scope.myId isn't change when I used it outside of scope $http, so I can't push my last inserted id to front end.
The problem is that it is asynchronous, so you don't have the data yet until the promise returns. You could either put the $scope.user.push inside the success callback, or use $scope.$watch("myId"... to register when the value is updated.
Try using .apply(); The change in JS won't be seen, or reflected in the UI if you don't.
}).success(function(data, status, headers, config) {
$scope.apply(function(){
$scope.myId = data;
});
})

Angularjs $http POST request empty array

The following $http request executes successfully, yet the PHP script on the other end receives an empty $_POST array when it should receive 'test' and 'testval.' Any ideas?
$http({
url: 'backend.php',
method: "POST",
data: {'test': 'testval'},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
console.log(data);
}).error(function (data, status, headers, config) {});
If you wan to send just that simple data, try this:
$http({
url: 'backend.php',
method: "POST",
data: 'test=' + testval,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
console.log(data);
}).error(function (data, status, headers, config) {});
And php part shoul be like this:
<?php
$data = $_POST['test'];
$echo $data;
?>
It is working for me.
This is a common issue with AngularJS.
The first step is to change the default content-type header for POST request:
$http.defaults.headers.post["Content-Type"] =
"application/x-www-form-urlencoded; charset=UTF-8;";
Then, using an XHR request interceptor, it is necessary to serialize properly the payload object:
$httpProvider.interceptors.push(['$q', function($q) {
return {
request: function(config) {
if (config.data && typeof config.data === 'object') {
// Check https://gist.github.com/brunoscopelliti/7492579
// for a possible way to implement the serialize function.
config.data = serialize(config.data);
}
return config || $q.when(config);
}
};
}]);
In this way, payload data will be again available in the $_POST array.
For more info about XHR interceptor.
Another possibility, it is to mantain the default content-type header, and then server side parse the payload:
if(stripos($_SERVER["CONTENT_TYPE"], "application/json") === 0) {
$_POST = json_decode(file_get_contents("php://input"), true);
}
More simplified way:
myApp.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(data) {
if (data === undefined) { return data; }
return $.param(data);
};
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});
Remove the following line, and the preceding comma:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
And then the data will appear in $_POST. You only need that line if you are uploading a file, in which case you'll have to decode the body to get the data vars.
I found my solution here http://www.peterbe.com/plog/what-stumped-me-about-angularjs. There is a piece of code in the "AJAX doesn't work like jQuery" section, which solved my problem.

Categories