How to get the requested data using Angular.js $http service - javascript

I need one help.I need to retrieve the data present in body part of a URL using Angular.js.I am explaining my code below.
var app=angular.module('hello',[]);
app.controller('Hello',function($scope, $http){
$http.get('http://oditek.in/medilink_global_new/#/product/Api/apiCatagory').
success(function(data) {
console.log('data',data);
$scope.greeting = data;
});
});
In console message i need the required json data.
The controller function of http://oditek.in/medilink_global_new/#/product/Api/apiCatagory is given below.
var cat=angular.module('medilink');
cat.controller('apiCatagoryController',function($state,$http,$scope){
$http({
method:'GET',
url:"php/category.php?op=disp",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
//console.log('catagory',response.data);
$scope.catadata=response.data;
},function errorCallback(response) {
});
})
catagory.html:
<div>
{{catadata}}
</div>
route.js:
.state('api',{
url:'/Api',
templateUrl:'Apiview/api.html',
controller:'apiController'
})
.state('api.catagory',{
url:'/apiCatagory',
templateUrl:'Apiview/catagory.html',
controller:'apiCatagoryController'
})
index.html:
<div ui-view>
</div>
Here inside body part i am displaying the ($scope.catadata) DB values.I need when any user will call this URL to get the data the data will deliver to the user.Please help me.

Related

HTTP JSONP request issue with $http in AngularJS

I get the bellow error when I try to use the JSONP method in angularJS.
Uncaught SyntaxError: Unexpected token : http://example.com/getSomeJson?format=jsonp&json_callback=angular.callbacks._0
What am I doing wrong here, this is my AngularJs controller with the http request:
UPDATED QUESTION DETAILS
See below with code snipit which reproduces my problem, I've commented some of the .js to illustrate what I've tried so far.
var app = angular.module('app', []);
app.controller('mainController', ['$http', 'mainService', function($http, mainService){
mainCtrl = this;
mainCtrl.test = "If you can see this the mainController works"
var promise = mainService.getJson();
promise.then(function (data)
{
mainCtrl.json = data;
});
}]);
app.service("mainService", function ($http, $q)
{
var deferred = $q.defer();
/*
// Method to Grab JSON that has CORs enabled:
// JSON resource with CORs enabled
var url = 'https://jsonplaceholder.typicode.com/posts/1';
$http({
method: 'GET',
cache: true,
url: url,
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
}).
success(function(response) {
//your code when success
deferred.resolve(response);
console.log('HTTP CORS SUCCESS!');
}).
error(function(response) {
//your code when fails
console.log('HTTP CORS ERROR!');
});
*/
/* */
// Method to Grab JSON that has CORs enabled:
// JSON resources without CORs enabled
var url = 'http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json' // does not work?
// var url = 'http://samcroft.co.uk/json-data/sample' // this one works
$http({
method: 'jsonp',
url: url + '?callback=JSON_CALLBACK',
}).
success(function(response) {
//your code when success
deferred.resolve(response);
console.log('JSONP SUCCESS!');
}).
error(function(response) {
//your code when fails
console.log('JSONP ERROR!');
});
this.getJson = function ()
{
return deferred.promise;
};
});
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular-route.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="mainController as mainCtrl">
<p>{{mainCtrl.test}}</p>
<hr />
<p>You should also see the JSON obeject below:</p>
{{mainCtrl.json}}
</body>
</html>
ORIGIONAL QUESTION DETAILS
app.controller('testController', ['$scope', '$http', function($scope, $http){
var url = 'http://example.com/getSomeJson';
$http({
method: 'JSONP',
url: url,
params: {
format: 'jsonp',
json_callback: 'JSON_CALLBACK'
}
}).
success(function(data) {
//your code when success
$scope.data = data;
console.log('SUCCESS!');
}).
error(function(status) {
//your code when fails
console.log('ERROR!');
});
}]);
When I look at the json in the chromes sources panel I see where the error is highlighted.
Any idea what I'm doing wrong? Or could it be an issue with how the API service is configured?
Here you go :-)
The code you tried with the jsonp request looks good but the url you used is not supporting the jsonp request, that's why you got an error.
If you try the same url with $http.get, it will work fine.
To support the jsonp call, the response should be wrapped with the JSON_CALLBACK () as below
JSON_CALLBACK ({ /* JSON */ })
Hence, I changed this to valid jsonp url and it worked!
https://angularjs.org/greet.php?callback=JSON_CALLBACK
You can try this url in the browser and see the response, how it is wrapped with JSON_CALLBACK ().
But if you try the below url, you can just see the json without any wrapping.
http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json?callback=JSON_CALLBACK
That's the difference to find whether the api supports jsonp.
Also, I have changed the service below with the same syntax as in another SO question answer,
https://stackoverflow.com/a/41030976/7055233
Working snippet:
var app = angular.module('app', []);
app.controller('mainController', ['$http', 'mainService', function($http, mainService){
mainCtrl = this;
mainCtrl.test = "If you can see this the mainController works"
var promise = mainService.getJson();
promise.then(function (data)
{
mainCtrl.json = data;
});
}]);
app.service("mainService", function ($http, $q)
{
var deferred = $q.defer();
var url = 'https://angularjs.org/greet.php';
//var url = 'http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json';
/*
// Method to Grab JSON that has CORs enabled:
// JSON resource with CORs enabled
var url = 'https://jsonplaceholder.typicode.com/posts/1';
$http({
method: 'GET',
cache: true,
url: url,
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
}).
success(function(response) {
//your code when success
deferred.resolve(response);
console.log('HTTP CORS SUCCESS!');
}).
error(function(response) {
//your code when fails
console.log('HTTP CORS ERROR!');
});
*/
/* */
// Method to Grab JSON that has CORs enabled:
// JSON resource without CORs enabled
function getJson() {
// $http.jsonp(url + "?callback=JSON_CALLBACK"). // this does not work either
$http.jsonp(url + '?callback=JSON_CALLBACK').
then(function(response) {
//your code when success
deferred.resolve(response);
console.log('JSONP SUCCESS!');
}, function(response) {
//your code when fails
console.log('JSONP ERROR!');
deferred.reject(response);
});
return deferred.promise;
}
this.getJson = getJson;
});
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular-route.js"></script>
<!--<script src="app.js"></script>-->
</head>
<body ng-controller="mainController as mainCtrl">
<p>{{mainCtrl.test}}</p>
<hr />
<p>You should also see the JSON obeject below:</p>
{{mainCtrl.json}}
</body>
</html>
JSONP callback must be specified by jsonpCallbackParam
BREAKING CHANGE
You can no longer use the JSON_CALLBACK placeholder in your JSONP requests.
Instead you must provide the name of the query parameter that will pass the callback via the jsonpCallbackParam property of the config object, or app-wide via the $http.defaults.jsonpCallbackParam property, which is "callback" by default.
-- Added to AngularJS v1.6.0-rc.2
UPDATE
The OPs example code does not work because the http://run.plnkr.co API does not support JSONP.
JSONP is available only on some sites with an API that pre-date ACCESS-CONTROL headers.
For more information, see JSONP Demystified

failed bind angularJS variable to nodejs

i have a problem sending my angularJS POST parameters to my nodejs server... i've seen many topics related to this, tried everything here and nothing works (there were more):
How to pass parameter in Angularjs $http.post
Angular: how to pass $scope variables into the Node.js server.
How to pass client-side parameters to the server-side in Angular/Node.js/Express
How to pass data from AngularJS frontend to Nodejs backend?
my relevant code that is envolved in this problem,
handlebars-template:
<div ng-controller='questions'>
<form method="POST" class="form-inline" class="my-search-menu">
<button ng-click="search()" class="btn btn-default glyphicon glyphicon-search" type="submit" style="background-color: #85C1E9;"></button>
<input style="direction: rtl" type="text" name="search_text" ng-model="search_text" class="form-control" placeholder="Search" aria-describedby="sizing-addon3">
</form>
</div>
AngularJS:
var myapp= angular.module('myapp', []);
myapp.controller("questions", function($scope,$http) {
$scope.search = function () {
var formdata = {search_text : $scope.search_text};
$http.post('/search', {params: formdata})
.success(function (data, status, headers, config) {
$scope.questions = data;
})
.error(function(data, status, header, config){
$scope.onerror = "Data: " + status;
});
console.log(formdata);
};
});
NodeJS:
app.post('/search', function (req,res,next){
var search_text = req.query.params.formdata.search_text;
console.log(req);
Question.find({$text: {$search: search_text}}).exec(function (err, questions){
res.json(questions);
});
});
There are few points you are missing. First in the anguar controller
$http.post('/search', {params: formdata})
will send {params:formdata} as request body in the node server.. So in the server end you will receive the data as request.body. correct way to receive the body in this case will be ..
app.post('/search', function (req,res,next){
var search_text = req.body.params.search_text;
//TODO
});
If you want to send the data as parameter then in controller write the function like this...
$http({
method: 'POST',
url: '/search/'+paramData,
}).then(function successCallback(response) {
//TODO
}, function errorCallback(error) {
//TODO
});
And in the server side...
app.post('/search/:searchText', function (req,res,next){
var paramData = req.params.searchText;
//TODO
});

How to acces XML data in response

I have this method
angular.module('RDash')
.controller("SipsCtrl", ['$scope','$http', function($scope, $http){
'use strict';
$http({
method: 'GET',
url: 'http://192.168.2.35/SIPSWS/SIPSWS.asmx/HelloWorld'
}).then(
//OK
function (response) {
$scope.btnCUPS = "Exito",
},
//KO
function (response) {
$scope.btnCUPS = "Error",
});
}]);
I have a server status 200 ok, but y donĀ“t see the response.
I should receive XML data response with the next structure
<string xmlns="http://tempuri.org/">Hola a todos</string>
How can I put de response in my view?
See if you are really getting the data by: console.log(response);
If you are, the generaly comes a data inside response, in the controller:
$scope.data = response.data;
In the view:
<div>{{data}}</div>

Error -1 send parameters using $http.post angular

I have a problem when you submit parameters using $ http.post in angular.
I assume it's some sort of error itself have little knowledge of angular , because in jquery work fine.
Request jquery'javascript
var user = $('#usuariotxt').val();
var pass = $('#passwordtxt').val();
var login= {
Usuario : user,
Password : pass
};
$.ajax({
type: 'POST',
url: 'http://190.109.185.138/Apipedro/api/login',
data: login,
datatype: 'json'
}).done(function(data) {
console.log(data);
});
Request Angular-Javascript
var app;
app = angular.module('AppUPC',[]);
app.controller('Formulario',['$scope', '$http', function ($scope, $http){
$scope.login = function(){
var login = {
Usuario: $scope.usuariotxt,
Password: $scope.passwordtxt
};
console.log(login);
var url, method;
url = 'http://190.109.185.138/Apipedro/api/login';
method = 'POST';
$http.post("http://190.109.185.138/Apipedro/api/login", {},
{params: {Usuario:$scope.usuariotxt, Password:$scope.passwordtxt}
}).success(function (data, status, headers, config) {
$scope.persons = data;
console.log($scope.persons);
}).error(function (data, status, headers, config) {
$scope.status = status;
console.log($scope.status);
});
};
}]);
I have also used many other forms , including the most common
$http({
url: url,
method: method,
data: login,
headers :{'Content-Type':'application/json'}
})
Errors that occur to me are the following
Short answer: If you want to send the same data as the jQuery example, use this
app.controller('Formulario', ['$scope', '$http', '$httpParamSerializer', function ($scope, $http, $httpParamSerializer) {
// snip
$http.post(url, $httpParamSerializer(login), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function success(response) {
$scope.persons = response.data;
}, function error(response) {
$scope.status = response.status;
});
}]);
This is because jQuery by default sends POST data as an x-www-form-urlencoded string, ie
Usuario=dfvides&Password=dfvids
Using the code above, Angular will send an identical request to jQuery.
Angular by default sends POST data as JSON with the Content-Type header set to application/json, ie
{"Usuario":"dfvides","Password":"dfvids"}
Is your API even set up to handle a JSON payload?
The reason your Angular version was triggering a pre-flight OPTIONS request (which it appears that your API is not equipped to handle) was because the header Content-Type: application/json makes the request non-simple...
A simple cross-site request is one that:
Only uses GET, HEAD or POST. If POST is used to send data to the server, the Content-Type of the data sent to the server with the HTTP POST request is one of application/x-www-form-urlencoded, multipart/form-data, or text/plain.
Does not set custom headers with the HTTP Request (such as X-Modified, etc.)

POST form data using AngularJS

I'm trying to use AngularJS to POST a form to an API I'm developing.
The form has novalidate, name="addMatchForm", and ng-submit="submit(addMatchForm)". The addMatchForm is as followed:
app.controller('addMatchController', ['$scope', 'players', 'matches', function($scope, players, matches) {
...
$scope.submit = function(form) {
form.submitted = true;
// Make sure we don't submit the form if it's invalid
if ( form.$invalid ) return;
matches.add(form).success(function(data) {
console.log('post result:', data);
})
}
}]);
app.factory('matches', function($http) {
return {
add: function(data) {
return $http.post('/matches', data);
}
}
});
But the weird thing is that each and every input's value becomes an empty object at that point. This is the Form Data from Chrome Developer Tools:
{"a_score":{},"b_score":{},"day":{},"month":{},"year":{},"a_player1":{},"a_player2":{},"b_player1":{},"b_player2":{},"submitted":true}:
I did add the content-type part already.
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
Any ideas?
Try to use $http like this:
return $http({
method: 'POST',
url: '/matches',
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

Categories

Resources