I am not able to get response from web service using Angular javascript - angularjs

var msg = document.getElementById('inputXML').innerHTML;How to pass input xml as a parameter to web service and displaying response from web service using angular javascript in html.
Here is my code, please help, i m not able to get reponse from web service.
<div ng-app="customerApp" ng-controller="customersController">
<ul>
HI<br><br><li ng-repeat="x in names">{{x}}</li>
</ul>
</div>
<script>
var app = angular.module('customerApp');
app.factory(
"setAsXMLPost",
function() {
//prepare the request data for the form post.
function transformRequest(data, getHeaders) {
var headers = getHeaders();
headers[ "Content-type" ] = "text/xml; charset=utf-8";
// using parsexml for xml
return(jQuery.parseXML(data));
}
return(transformRequest);
}
);
function customersController($scope, $http, setAsXMLPost) {
var msg = document.getElementById('inputXML').innerHTML;
$http.post("url.asmx", msg, {transformRequest: setAsXMLPost}).success(function(response) {
$scope.names = response;
});
}
</script>
<div id="inputXML">
<ACORD> <SignonRq> <UserId>CUser</UserId> <Password>XuViDgegi/KtGyJuXfuMrw==</Password>
<SignonPswd> <CustId> < </ACORD>
</div>

Because you are not retriving the content of the div. You are simply extracting #inputXML node from the DOM tree. You can try is
var msg = document.getElementById('inputXML').innerHTML;

I am not sure about xml but you are not posting it, use innerHTML to get actual xml from <div id="inputXML">.
inputXML : msg.innerHTML // use innerHTML to get the actual xml

Have you checked if your controller is executing correctly, I think the standard controller declaration would be something like this:
.controller('customersController', ['$scope', '$http', 'setAsXMLPost',function($scope, $http, setAsXMLPost){
var msg = document.getElementById('inputXML').innerHTML;
$http.post("http://nordevd208wa1x.csc-fsg.com/TPOServiceEnh7/TPOService/TPOService.asmx", msg, {transformRequest: setAsXMLPost}).success(function(response) {
$scope.names = response;
});
}]);

in var msg you are getting a javascript object though you need complete html to process so it should be
var = document.getElementById('inputXML').innerHTML;
Also default tranformRequest of $http in angular js is json you will have to change it to text/xml i wrote an article on how you could change it tranformRequest example angularjs
complete example, filename is test.php placed at root
<?php
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
$xmlData = file_get_contents('php://input');
header("Content-type: text/xml; charset=utf-8");
echo '<?xml version="1.0" encoding="utf-8"?>' . $xmlData;
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<body >
<title>Simple xml post in angularjs Web Application</title>
<meta name="Description" content="Simple xml post in angularjs Web Application">
<div ng-app="customerApp" ng-controller="customersController">
<ul>
<li ng-repeat="x in users">{{x}}</li>
</ul>
</div>
<div id="inputXML">
<ACORD>
<SignonRq><UserId>CUser1</UserId><Password>XuViDgegi/KtGyJuXfuMrw==</Password></SignonRq>
<SignonRq><UserId>CUser2</UserId><Password>XuViDgegi/KtGyJuXfuMrw==1</Password></SignonRq>
</ACORD>
</div> <!-- Libraries -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var app = angular.module('customerApp', []);
app.factory(
"setAsXMLPost",
function() {
//prepare the request data for the form post.
function transformRequest(data, getHeaders) {
var headers = getHeaders();
headers[ "Content-type" ] = "text/xml; charset=utf-8";
// using parsexml for xml
return(jQuery.parseXML(data));
}
return(transformRequest);
}
);
app.factory(
"getAsXML",
function() {
//prepare the request data for the form post.
function transformResponse(data, getHeaders) {
var headers = getHeaders();
headers[ "Content-type" ] = "text/xml; charset=utf-8";
// using parsexml for xml
return(jQuery.parseXML(data));
}
return(transformResponse);
}
);
function customersController($scope, $http, setAsXMLPost, getAsXML) {
var msg = document.getElementById('inputXML').innerHTML;
$scope.users = [];
$http.post("test.php", msg, {transformRequest: setAsXMLPost, transformResponse: getAsXML}).success(function(returnedXMLResponse) {
//here you will get xml object in reponse in returnedXMLResponse
});
}
</script>
</body>
</html>

Related

How to bind remote JSON data to a Polymer vaadin-grid?

First time using this web component... I'm able to bind JSON data in a var to a vaadin-grid (w/ polymer 1.0), but am missing something basic about getting the JSON data from a url into the grid.
Here's the most simple example I could create, that worked with hard-coded JSON and now have used some of the examples from the Vaadin website to attempt to pull the data from a URL.
<head>
// import statements same as in my example that works with hard coded JSON
<script>
function getJSON(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
}
};
xhr.open('GET', url, true);
xhr.send();
}
</script>
</head>
<body>
<h2>Vaadin Grid - example </h2><br>
<vaadin-grid selection-mode="multi">
<table>
<col name="name">
<col name="city">
</table>
</vaadin-grid>
<script>
var grid = grid || document.querySelector('vaadin-grid');
HTMLImports.whenReady(function() {
grid.items = function(params, callback) {
var url = 'https://.../simple-data.json';
getJSON(url, function(data) {
callback(data[0]);
});
};
});
</script>
And simple-data.json URL returns this:
[ { "name": "Jose Romero", "city": "Monteray" }, { "name": "Chuy Diez", "city": "Los Angeles" }, { "name": "Inez Vega", "city": "San Diego" } ]
Where am I going wrong? Thanks in advance.
Binding is easily done using the Polymer 1.0 iron-ajax component. Here's the working code:
<head>
// import statements same as in my example that works with hard coded JSON
<link rel="import" href="iron-ajax/iron-ajax.html">
<link rel="import" href="vaadin-grid/vaadin-grid.html">
</head>
<body>
<h2>Vaadin Grid - working example </h2><br>
<template is="dom-bind">
<iron-ajax
auto
url = "http://hostname/.../simple-data.json"
handle-as="json"
last-response="{{gridData}}" ></iron-ajax>
<vaadin-grid selection-mode="multi" items="{{gridData}}">
<table>
<col name="name">
<col name="city">
</table>
</vaadin-grid>
</template>
<script>
</script>
</body>
I still would like to learn how it's done using the JavaScript code in the Vaadin documentation Remote Data Any tips?
Answering my own question again: to bind JSON to a vaadin-grid using JavaScript instead of using the Polymer iron-ajax component simply add this script section to the bottom of the body. It adds an event listener for WebComponentsReady.
<script type="text/javascript">
window.addEventListener('WebComponentsReady', function() {
var grid = document.querySelector('vaadin-grid');
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
grid.items = json;
}
}
};
xhr.open('GET', 'http://<your_url>', true);
xhr.send();
});
</script>
For others getting started with vaadin Polymer components they have a series of very short, but excellent tutorials - search YouTube for "vaadin elementary school" to find them.

multi data from different schema, angular display

I have a really long json that each comes from different schema.
I did push in order to get them all in one json - that works.
know I want to use a controller for all of them and display it to the screen.
my index
<!DOCTYPE html>
<html ng-app="showFrozen">
<head>
<title>frozen</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
</head>
<body ng-controller="showFrozenCtrl">
<tbody>
<div ng-repeat="themes in showFrozenController.themes" ng-show="$first">
<h2>{{themes.theme}}</h2>
<span>for age: </span>
<p>{{themes.age}}</p>
<span>description: </span>
<p>{{themes.description}}</p>
<p>{{themes.description_more}}</p>
<img ng-src="{{themes.image}}" width="170" height="170">
</div>
</table>
<script src="js/lib/angular/angular.min.js"></script>
<script src="js/showFrozenController.js"></script>
</body>
</html>
my controller
var showFrozen = angular.module('showFrozen',[]);
showFrozen.filter("allItems", function() {
return function(frozen) {
var resultArr = [];
angular.forEach(frozen,function(item) {
resultArr.push(item);
});
return resultArr;
};
});
var model = {};
showFrozen.run(function($http) {
$http.get("http://localhost:3000/frozen").success(function(data){
console.log(data);
model.frozen = data;
});
});
showFrozen.controller('showFrozenCtrl',function($scope) {
$scope.showFrozenController = model;
});
so I don't get any output - but I see the json in the console, I'm attaching an image.
In your controller model is undefined.
Move the HTTP call to your controller and in the success assign the scope.showFrozenController to data
You need to make your $http request inside of your controller.
showFrozen.controller('showFrozenCtrl',function($scope, $http) {
$http.get("http://localhost:3000/frozen").success(function(data){
console.log(data);
$scope.model = data;
});
});
This is because when you try and print items out in your template (html) what is actually being accessed inside of any {{ }} blocks is your $scope object. So to make data available to your template you must store it on your $scope.
Have a read of this blog post
showFrozen.factory('frozenDataSrv',function($http) {
return {
getFrozenData: getFrozenData
};
function getFrozenData() {
return $http.get("http://localhost:3000/frozen")
.then(getFrozenDataComplete)
.catch(getFrozenDataFailed);
function getFrozenDataComplete(response) {
return response.data.results;
}
function getFrozenDataFailed(error) {
logger.error('XHR Failed for getFrozenData.' + error.data);
}
}
});
showFrozen.controller('showFrozenCtrl',function($scope, frozenDataSrv) {
frozenDataSrv.getFrozenData()
.then(function(response){
console.log(response)
})
});

ng-repeat does not work when I use it

my code as follows:
<ons-template id="stockSearch.html">
<ons-page ng-controller="stockSymbolController">
<ons-toolbar class="DCF">
<div class="left">
<ons-back-button style="color:white;"></ons-back-button>
</div>
<div class="center" style="font-size:22px;" >Stock Search : {{myDCFNavigator.getCurrentPage().options.symbol}}</div>
</ons-toolbar>
<div class="stockSearchList">
<div ng-repeat="stockSearch in stocksSearchList">
<div class="stockSearchOne">
<div class="stockSearchOneComp">{{stockSearch.company}}</div>
<div class="stockSearchOneInfo">Symbol: {{stockSearch.symbol}}| Exchange:{{stockSearch.exchange}} </div>
</div>
</div>
</div>
</ons-page>
and script.js as follows:
module.controller('stockSymbolController', function($scope, $http){
$scope.stocksSearchList = new Object();
var url = "https://www.xxxxx.com/api/public/search_company/"+myDCFNavigator.getCurrentPage().options.symbol;
$.ajax({
type: 'get',
url: url,
success: function(data) {
$scope.stocksSearchList = data;
console.log($scope.stocksSearchList);
},
});
});
but the ng-repeat does not work.when I add the <div ng-repeat="stockSearch in stocksSearchList"> Even in the middle just display "123" , it would not show.
Anybody knows the reason?
Firstly you should use angular's $http service not jQuery's $.ajax method. From the docs:
The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.
So your code should look more like this:
module.controller('stockSymbolController', function($scope, $http){
var url = "https://www.xxxxx.com/api/public/search_company/"+myDCFNavigator.getCurrentPage().options.symbol;
$http.get(url)
.then(function(response) { // success is being deprecated in favour of .then
$scope.stocksSearchList = response.stocksSearchList; // this should be an array that has nested objects that include properties and values for company, symbol and exchange (see note below)
console.log($scope.stocksSearchList);
}, function(error) {
// do something with the error
});
});
I'm assuming response looks like the below with two items in the array:
{
stocksSearchList: [
{
company: 'some company',
symbol: 'some symbol',
exchange: 'some exchange'
},
{
company: 'some other company',
symbol: 'some other symbol',
exchange: 'some other exchange'
}
]
}
Instead of:
$scope.stocksSearchList = new Object();
Try
$scope.stocksSearchList = [];
And make sure this returns a list;

ng-repeat not printing resp.items from cloudendpoint on webpage

I'm new to angularjs. I'm working on a web application using angularjs and cloud endpoints. I'm getting the response from endpoint and I can see that in Console.log also. but when I'm trying to print that response it's not working. I'm not getting what's going wrong. Can anyone fix this?
Here's my code.
HTML Page
<div ng-repeat="lister in lists">
</div><h2>{{lister.title}}</h2>
</div>
AngularJs Code
<script>
function init() {
window.init();
}
</script>
<script>
var app = angular.module('list',[]);
app.controller('listCtrl',function($scope,$window){
$window.init= function() {
$scope.loader();
};
$scope.loader= function(){
gapi.client.load('MyEndPoint', 'v1', function(){
gapi.client.MyEndPoint.MyMethod1({
'latitude':'24.5555','longitude':'45.55555'
}).execute(function(resp) {
$window.console.log(resp);
$scope.lists = resp.items;
});
}, 'https://MyEndpointURL.appspot.com/_ah/api');
};
</script>

Connecting AngularJS and CodeIgniter (GET calls working but POST not)

EDIT: It works on IE!!! So my Chrome and Mozilla must be blocking the POST call. FYR: I've got a Allow-Control-Allow-Origin installed on Chrome.
I would like to connect AngularJS (I'm running it in a JavaScript framework - npm, gulp and bower - on MyDocuments) and CodeIgniter (which is on XAMPP).
GET calls work fine (I get the user names and their cities on my screen via AngularJS).
But I have a problem to run this POST function (which adds a new user into the database):
$scope.addUser = function(name,city) {
$http.post("http://localhost/test/index.php/usercontroller/addUser",{'name':name,'city':city})
.success(function(response) {$scope.answer=response})
.error(function(response) {alert('error');$scope.answer = response});
};
When I call it it there is an error in the console:
OPTIONS http://localhost/test/usercontroller/add 500 (Internal
Server Error)(anonymous function) # angular.js:10413sendReq #
angular.js:10232$get.serverRequest # angular.js:9944processQueue #
angular.js:14454(anonymous function) #
angular.js:14470$get.Scope.$eval # angular.js:15719$get.Scope.$digest
# angular.js:15530$get.Scope.$apply # angular.js:15824(anonymous
function) # angular.js:23095eventHandler # angular.js:3247 (index):1
XMLHttpRequest cannot load
http://localhost/test/usercontroller/add. Invalid HTTP status code
500
The structure of my folders is as follows:
CODEIGNITER - CONTROLLER
xampp/htdocs/test/application/controllers/usercontroller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Usercontroller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('usermodel');
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Content-type: application/json');
header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
}
public function index()
{
$data['include'] = 'user/index';
$this->load->view('user/index', $data);
}
public function addUser()
{
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name = $request->name;
$city = $request->city;
$id = $this->usermodel->addUser($name,$city);
if($id)
{
echo '{"status" : "success"}';
}
else
{
echo '{"status" : "failure"}';
}
}
public function getCities()
{
$cities = $this->usermodel->getCities();
echo json_encode($cities);
}
public function getUsers()
{
$users = $this->usermodel->getUsers();
echo json_encode($users);
}
}
CODEIGNITER - MODEL
xampp/htdocs/test/application/models/usermodel.php
<?php if (!defined('BASEPATH')) exit('No direct script allowed');
class Usermodel extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function addUser($name,$city)
{
$data = array('name' =>$name,'city' => $city);
$this->db->insert('user',$data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
public function getCities()
{
$sql='SELECT city FROM user';
$query = $this->db->query($sql);
$city = array();
foreach($query->result() as $row)
{
$city[]=array("city" => $row->city);
}
return $city;
}
public function getUsers()
{
$sql='SELECT * FROM user';
$query = $this->db->query($sql);
$user = array();
foreach($query->result() as $row)
{
$user[]=array(
"name" => $row->name,
"city" => $row->city
);
}
return $user;
}
}
ANGULAR - APP
MyDocuments/test/src/app.js
angular.module('app', []);
ANGULAR - INDEX.HTML
MyDocuments/test/src/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test project</title>
<link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css">
<script src="../bower_components/angular/angular.js"></script>
<script src="js/all.js"></script>
</head>
<body ng-app="app">
<div ng-controller="MainController">
<form novalidate>
<label>Name:</label>
<input type="text" ng-model="name"/>
<div>{{name}}</div>
<label>City:</label>
<input type="text" ng-model="city"/>
<div>{{city}}</div>
<button ng-click="addUser(name,city)">Submit</button>
<div>Answer:{{answer}}</div>
</form>
<h3>Users</h3>
<ul>
<li ng-repeat="user in users track by $index">{{ user.name }}, {{user.city}}</li>
</ul>
</div>
</body>
</html>
ANGULAR - CONTROLLER
MyDocuments/test/src/components/MainController.js
angular.module('app').controller('MainController', function($scope, $http) {
$http.get("http://localhost/test/index.php/usercontroller/getUsers")
.success(function(response) {$scope.users = response});
$http.get("http://localhost/test/index.php/usercontroller/getCities")
.success(function(response) {$scope.cities = response});
$scope.addUser = function(name,city) {
$http.post("http://localhost/test/index.php/usercontroller/addUser",{'name':name,'city':city})
.success(function(response) {$scope.answer=response})
.error(function(response) {alert('error');$scope.answer = response});
};
});
Am I doing something wrong?
Is there a problem in the fact that I have a JavaScript framework on MyDocuments and CodeIgniter on XAMPP. I've also tried by putting the whole JavaScript folder (with npm, gulp and bower) on XAMPP (don't know if that is such a good idea but, I've tried it anyway) and I get the same 500 error when running that addUser() POST call.
Another thing that I've tried is that I've put a super simple angular.html (attached at the bottom of this post) directly on xampp/htdocs and in this case the POST call works perfectly.
So I guess there is a problem in the communication between JavaScript (angular, npm, gupl, bower) and CodeIgniter folders.
Any ides what could be done to connect them? The GET calls are working so I guess there should also be a solution for the POST calls. Thank you in advance for any hints.
SUPER SIMPLE ANGULAR.HTML DIRECTLY ON XAMPP/HTDOCS
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</head>
<body>
<div ng-app="app" ng-controller="MainController">
<form novalidate>
<label>Name:</label>
<input type="text" ng-model="name"/>
<div>{{name}}</div>
<label>City:</label>
<input type="text" ng-model="city"/>
<div>{{city}}</div>
<button ng-click="addUser(name,city)">Submit</button>
<div>Answer:{{answer}}</div>
</form>
<h3>Users</h3>
<ul>
<li ng-repeat="user in users track by $index">{{ user.name }}, {{user.city}}</li>
</ul>
</div>
<script>
var app = angular.module('app', []);
app.controller('MainController', function($scope, $http) {
console.log('delam');
$http.get("http://localhost/ekohrana/index.php/usercontroller/getUsers")
.success(function(response) {$scope.users = response});
$scope.addUser = function(name,city) {
$http.post("http://localhost/ekohrana/index.php/usercontroller/addUser",{name:name,city:city})
.success(function(response) {$scope.answer=response})
.error(function(response) {alert('error');$scope.answer = response});
};
});
</script>
</body>
</html>
Problem is that you are making CORS post request, therefore browser is trying to make first OPTIONS call to your backend on same url as POST and when you dont response correctly on OPTIONS request , your frontend will fail.
function __construct() {
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
die();
}
parent::__construct();

Resources