AjaxCallBack was not called, windows phone phonegap - angularjs

I am trying to connect WCF RESTful C# API to phonegap application using angularjs. My html working perfect in Web but no in my windows phone.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="myApp">
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Profile</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
</head>
<body>
<div>
<div data-ng-controller="ProfileCtrl">
First Name: {{FirstName}}
Last Name: {{LastName}}
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<!--<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>-->
<script type="text/javascript" src="js/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
window.jsoncallback = function (json) {
debugger;
if (!json.Error) {
alert("run callback");
//alert("success");
}
else {
alert(json.Message);
}
}
myApp.controller('ProfileCtrl', ["$scope", "$http", function ($scope, $http) {
function LoadProfile() {
debugger;
var call_url = 'http://localhost:53834/LoginService.svc/UserProfile/1';
//For jsonp calling
//alert("Running Jsonp");
//$http.jsonp(call_url).success(function (data) {
// debugger;
//});
alert("Running Ajax");
$.ajax({
url: call_url,
type: "POST",
dataType: "jsonp", // from the server
crossDomain: true,
contentType: "application/json; charset=utf-8", // to the server
jsonpCallback: 'jsoncallback',
success: function (data) {
alert("success");
$scope.FirstName = data.FirstName;
$scope.LastName = data.LastName;
$scope.$apply();
},
}).done(function (data) {
debugger;
console.log(data);
}).fail(function (xhr, status, error) {
debugger;
alert(xhr.status + " " + status + " " + error);
});
};
LoadProfile();
}]);
</script>
</body>
</html>
Here is my html code,
Service code is
public Stream UserProfile(string profileID)
{
TestDBEntities db = new TestDBEntities();
int _ProfileID = Convert.ToInt32(profileID);
tblProfile objtblProfile = db.tblProfiles.Find(_ProfileID);
string jsCode;
JavaScriptSerializer returnList = new JavaScriptSerializer();
string output = returnList.Serialize(objtblProfile);
if (objtblProfile != null)
jsCode = "jsoncallback" + "(" + output + ");";
else
jsCode = null;
WebOperationContext.Current.OutgoingResponse.ContentType = "application/javascript";
return new MemoryStream(Encoding.UTF8.GetBytes(jsCode));
}
I have done all things but not working in my windows phone it is giving an error
200 parserror: jsoncallback was not called
but it is working perfect in Web normally.

The way I made an AJAX request in my application is as below. Take a look and see if this works out for you:
app.ajaxCall = function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', <URL>, false);
//Content-Type can be based on the content you are sending
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var params = <define param string here>;
xhr.send(params);
var isError = false;
try {
if (xhr.status === 200) {
var jsonResponse = JSON.parse(xhr.responseText);
<logic>
}
};
Hope this helps.

Related

elasticsearch and angular js Interworking error

Hi i wondering that ploblem so i want ask somebody
so please give me solution?
I make html file like that photo
but when i open this html file this file not working…
any data not diplay
what is the ploblem in this html file?enter image description here
<!doctype html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div ng-controller="QueryController">
</div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/elasticsearch-browser/elasticsearch.angular.js"></script>
<script>
var myApp = angular.module('myApp', ['elasticsearch']);
// Create the es service from the esFactory
myApp.service('es', function (esFactory) {
return esFactory({ host: 'localhost:9200'});
});
myApp.controller('ServerHealthController', function($scope, es, esFactory) {
es.cluster.health(function (err, resp) {
if (err) {
$scope.data = err.message;
} else {
$scope.data = resp;
}
});
});
// We define an Angular controller that returns query results,
// Inputs: $scope and the 'es' service
myApp.controller('QueryController', function($scope, es, esFactory) {
// search for documents
es.search({
index: 'epowersyst',
type: 'logs',
body: {
query:
{
match_all : {} }
}
}).then(function (response) {
$scope.hits = response;
console.log($scope.hits)
alert("hits값 : " + response);
});
});
</script>
</body>
</html>

Angular Storing array into Cookie

I have a function below that works fine and passes info into and retrieves from a cookieStore without issue
$scope.num = 0
$scope.nums = []
$scope.increment = function () {
$scope.num++
}
$scope.$watch('num', function () {
$scope.nums.push($scope.num)
})
$scope.storeProductsInCookie=function(){
$cookieStore.put("invoices",$scope.nums)
};
$scope.getProductsInCookie=function(){
console.log( $cookieStore.get("invoices",$scope.nums));
}
However when I try with the below verufyGuess function that is injecting the Index and no as parameters into the function it fails to place into the cookieStore
$scope.verifyGuess = function (Index , no) {
$scope.votes = {};
$scope.newVotes = []
$scope.votes[Index] = $scope.votes[Index] || 0;
$scope.votes[Index]+= no;
$scope.$watch('votes', function () {
$scope.newVotes.push($scope.votes)
})
$scope.storeProductsInCookie=function(){
$cookieStore.put("invoices",$scope.newVotes)
};
$scope.getProductsInCookie=function(){
console.log( $cookieStore.get("invoices",$scope.newVotes));
}
$cookieStore is Deprecated: (since v1.4.0)
Please use the $cookies service instead.
$scope.nums is an array of strings.So $cookieStore is storing them as string(cookies only support strings to store).
In second case $scope.newVotes is an array of objects. cookies wont store objects.
you must use $cookieStore.put("invoices", JSON.stringify($scope.newVotes))
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.12/angular-cookies.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<script>
var app = angular.module('plunker', ['ngCookies']);
app.controller('MainCtrl', function($scope, $cookies) {
$scope.votes = {};
$scope.newVotes = []
var Index = 0;
$scope.votes[Index] = $scope.votes[Index] || 0;
$scope.votes[Index] += 10;
$scope.newVotes.push($scope.votes)
$scope.storeProductsInCookie = function() {
$cookies.put("invoices", JSON.stringify($scope.newVotes))
};
$scope.getProductsInCookie = function() {
console.log($cookies.get("invoices"));
}
$scope.storeProductsInCookie();
$scope.getProductsInCookie();
});
</script>
</body>
</html>

AngularJs dependency injection related to $http

While writing the above code in AngularJs, I am getting an error :
Error: $injector:unpr
Unknown Provider
Unknown provider: $http
I believe the reason might be while injecting $http through the serviceProvider which in my case is httpServiceProviderFunction.$inject = ["$http"];. I would appreciate if anyone could help me understand these two questions:
1) Although I have injected the $http in the httpServiceProviderFunction. Why am I getting the above error?
2)Is there any way I can inject $http in the service directly without injecting in serviceProvider? In my example, it corresponds to this line:
function httpService(url, $http) {.....}
The code snippet can be found below:
(function() {
angular.module("httpServiceApp", []).controller("httpServiceController", httpServiceControllerFunction).provider("httpService", httpServiceProviderFunction).config(configObj);
configObj.$inject = ["httpServiceProvider"]
function configObj(httpServiceProvider) {
httpServiceProvider.configuration.baseUrl = "http://davids-restaurant.herokuapp.com/categories.json";
}
httpServiceProviderFunction.$inject = ["$http"];
function httpServiceProviderFunction($http) {
var provider = this;
provider.configuration = {
baseUrl: "http://davids-restaurant.herokuapp.com/categories.json"
}
provider.$get = function() {
var service = new httpService(provider.configuration.baseUrl, $http);
return service;
}
}
function httpService(url, $http) {
var service = this;
service.menuCategories = function() {
var response = $http({
method: "GET",
url: url
});
return response;
}
}
httpServiceControllerFunction.$inject = ["httpService"]
function httpServiceControllerFunction(httpService) {
var service = httpService;
var controller = this;
var promise = service.menuCategories();
promise.then(function(response) {
controller.categories = response.data;
}).catch(function(error) {
console.log("Error occured", error);
})
}
})();
<!DOCTYPE html>
<html ng-app="httpServiceApp">
<head>
<meta charset="utf-8">
<meta name="description" content="First Angular App">
<meta name="keywords" content="HTML, Javascript, AngularJs">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
<script src="app1.js"></script>
<title>HTTP service in AngularJs</title>
</head>
<body>
<div ng-controller="httpServiceController as controller">
<div>
<ul>
<li ng-repeat="items in controller.categories">({{items.short_name}}){{items.name}}</li>
</ul>
</div>
</div>
</body>
</html>
Thank you for your time. I appreciate your help.

Angular login auth what about using web worker?

What do you think about this approach
using web worker for angular login/auth
it looks good at me and in this way you can get rid of
$rootScope event as well :)
This is just an example in a more prodution way
you should use like https://stackoverflow.com/a/16730809
Html & js
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>Form</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body ng-controller="LoginController as vm">
<p ng-if="vm.isLogged">Logged as {{vm.username}}</p>
<a href ng-click="vm.doFakeLogin()">Login</a>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.2/angular.min.js">
</script>
<script>
function LoginController($scope){
var vm = this;
vm.isLogged = false;
var workerCheckLogin = new Worker('worker-check-login.js');
var workerDoLogin = new Worker('worker-do-login.js');
var jwt = 'auth-token';
workerCheckLogin.postMessage(jwt);
workerCheckLogin.addEventListener('message', function(e) {
if(e.data > 0){
$scope.$evalAsync(function() {
vm.isLogged = true;
vm.username = 'Whisher';
});
}
}, false);
vm.doFakeLogin = function doFakeLogin(){
workerDoLogin.postMessage({username:'whisher','password':'12345'});
}
workerDoLogin.addEventListener('message', function(e) {
if(e.data > 0){
$scope.$evalAsync(function() {
vm.isLogged = true;
vm.username = 'Whisher';
});
}
}, false);
}
angular
.module('app', [])
.controller('LoginController',LoginController);
</script>
</body>
</html>
worker-check-login.js
self.addEventListener('message', function(e) {
console.log('Worker check login said: ', e.data);
/*
do xhr to the server
e.data = jwt
return
1 succees
0 fail
*/
self.postMessage(0); //
}, false);
worker-do-login.js
self.addEventListener('message', function(e) {
console.log('Worker do login said: ', e.data);
/*
do xhr to the server
e.data = credentials
return
1 succees
0 fail
*/
self.postMessage(1); //
}, false);

access POST data from httpBackend in e2e test

In this example, I have an e2e test doing a button click, which executes a function that does a POST
I would like to be able to have access to the "data" object from testDev httpBackend callback, in my e2e scenerios code, for verification.
Is this possible in an e2e test? If so, could you point me in the right direction?
thanks
scenerio code
describe('test2 app', function() {
beforeEach(function() {
browser().navigateTo('/testbed/e2e/app/index2.html');
});
it('should run a POST',function() {
element('#myButton2').click();
});
});
test module
var test2Dev = angular.module('test2Dev', ['test2App', 'ngMockE2E'])
.run(function($httpBackend) {
$httpBackend.whenPOST(/testpost/)
.respond(function(method, url, data, headers){
console.log(data);
return [200, data, {}];
});
});
markup
<html lang="en" ng-app="test2Dev" ng-controller="test2Ctrl">
<head>
<meta charset="utf-8">
<title>Test click </title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-mocks.js"></script>
<script src="/testbed/e2e/test/e2e/test2Dev.js"></script>
<script src="js/controllers2.js"></script>
</head>
<body>
<button id="myButton2" ng-click="runPost()">run post</button>
</body>
</html>
controller
var test2App = angular.module('test2App', []);
test2App.controller('test2Ctrl', function($scope,$http) {
$scope.runPost = function() {
$http.post('/testpost',{
data1 : 'chevy',
data2 : 'ford'
});
}
});
runner
<!doctype html>
<html lang="en">
<head>
<title>End2end Test Runner</title>
<meta charset="utf-8">
<base href="../..">
<script src="app/lib/angular/angular-scenario.js" ng-autotest></script>
<script src="app/lib/angular/angular-mocks.js" ng-autotest></script>
<script src="/testbed/e2e/test/e2e/test2Dev.js"></script>
<script src="/testbed/e2e/test/e2e/scenarios2.js"></script>
</head>
<body>
</body>
</html>
Not very pretty but I removed my test module, and used a changed version of "mockApi" here->
https://github.com/blabno/ngMockE2E-sample (thank you Bernard Labno)
changed e2e.mocks.js to add the data object to it's config obj->
function setup(method, url, config)
{
$httpBackend.when(method, url).respond(function (requestMethod, requestUrl, data, headers) {
config.triggered = true;
config.data = data;
var response = config.response || {};
if (config.serverLogic) {
response = config.serverLogic(requestMethod, requestUrl, data, headers);
}
return [response.code || 200, response.data];
});
}
setup(POST, /testpost/, mocks.api.post_test);
.... and added this method to access it....
chain.getData = function() {
return this.addFuture("get data object for " + itemName, function(done) {
done(null,JSON.parse(api[itemName].data));
});
};
... here is my scenerio now...
it('should run a POST',function() {
element('#myButton2').click();
expect(mockApi("post_test").getData()).toEqual({
data1 : 'chevy',
data2 : 'ford'
});
});
Is there a better way to do this?

Resources