angular with mysql to fetch database - php

I have this working example where i have use $scope and $http in controller to fetch an col from database using get method in variable as given below
<script>
var fetch = angular.module('myapp', []);
fetch.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
$http({
method: 'get',
url: 'quizdb.php'
}).then(function successCallback(response) {
// Store response data
$scope.users = response.data;
});
}]);
</script>
now i want this same thing in my factory service i have where i am using hardcoded array. i want to replace the hardcoded array with dynamic array.
with php i am getting an array of but the problem is that i dont know how to implement this thing in factory in angular
my factory is as follows
(function(){
angular
.module("htcssquiz")
.factory("DataService",DataService);
function DataService(){
var dataObj = {
turtleData: turtleData,
quizQuestions: quizQuestions,
correctAnswer : correctAnswer
};
return dataObj;
}
var correctAnswer = [1,2,3,0,2,0,3,2,0,3];
var quizQuestions = [
{
type: "text",
text: "How much can a loggerhead weigh?",
possibilities: [
{
answer: "Up to 20kg"
},
{
answer: "Up to 115kg"
},
{
answer: "Up to 220kg"
},
{
answer: "Up to 500kg"
}
],
selected: null,
correct: null
}
so i want to replace this correctAnswer array with dynamic one.
please help me i am new to angular . thank you in advance.
I am using this factory DataService in The List controller using $inject as follows
(function(){
angular
.module("htcssquiz")
.controller("listctrl", ListController);
ListController.$inject = ['quizMetric','DataService'];
function ListController(quizMetric,DataService){
var vm = this;
vm.quizMetric =quizMetric;
vm.data = DataService.turtleData;
vm.activeTurtle = {};
vm.changeActiveTurtle = changeActiveTurtle;
vm.activateQuiz =activateQuiz;
vm.search = "";
function changeActiveTurtle(index){
vm.activeTurtle = index;
}
function activateQuiz(){
quizMetric.changeState("quiz", true);
}
}
}) ();

This will require a change to both your controller AND your service. The controller will now use the service as if it were the $http call:
fetch.controller('userCtrl', ['$scope', 'DataService', function ($scope, DataService) {
DataService.getCorrectAnswer().then(function (response) {
// Store response data
$scope.correctAnswer = response.data;
});
}]);
Your service will now take responsibility for making the $http call:
DataService.$inject = ['$http'];
function DataService($http){
var dataObj = {
...
getCorrectAnswer : function() {
return $http({
method: 'get',
url: 'quizdb.php'
});
}
};
return dataObj;
}

Related

store php response in angularjs service, then get them in controller

So, I am new to angularjs. I want to use MVC structure. So, I was thinking that storing the response from php in my service, then use them in my controller.
Service:
(function () {
angular.module('dataService').service("incidentService", function ($http) {
var Data = [];
return ({
getData: __getData
});
function __getData() {
return Data;
}
function __setData($http, $q) {
var defer = $q.defer();
$http.get('PHP/NAME.php',{cache : 'true'}).
success(function(data){
Data = data;
console.log(Data);
defer.resolve(data);
defer.promise.then(function(data){
Data = data;
console.log(Data);
});
});
}
})})();
Controller:
(function () {
angular.module('app')
.controller('Ctrl', Ctrl);
/** #ngInject */
function Ctrl($scope, $http, $q,baConfig, incidentService) {
incidentService.setData($http,$q)
var DataSet = incidentService.getData();
console.log(DataSet);
}
})();
By doing this way, the problem is my dataSet does not get updated when the data array in my service is updated. I know that we can return a defer promise to controller to get the data, but can we set the data first in service, then use get method to use them?
OK, I think the biggest issue with why this doesn't work is because you're assigned the data returned by the $http call to nData rather than just Data.
The next issue is that there's not a getMonthlyData method defined on the service.
That being said, this looks overly complicated.
Your service should look more like this:
(function () {
angular.module('dataService').service("incidentService", function ($http,$q) {
var service
service.getData = __getData()
return service
function __getData() {
if (!service.Data) {
return $http.get('PHP/NAME.php',{cache : 'true'}).then( function(data) {
service.Data = data
return $q.when(service.Data)
})}
else {
return $q.when(service.Data)
}
}
})})();
Then in your controller you just get the data via incidentService.getData()

Angular ui-router resolve, http success, stateParams

My goal to achieve is:
first to insert new database record with http post, resolve with stateProvider and grab the new id and change view and stateParams.
i have this code for my http post service
myApp.service('postService', ['$http', function($http) {
this.insertNew = function() {
$http.post('create_new.php')
.success(function(data) {
return data;
});
};
create_new.php returns the ID like this (it works, proved with console)
return json_encode($data);
and the stateProvider looks like this (section)
$stateProvider
.state('newRecord', {
resolve: {
newArtID: ['postService',
function(postService) {
return postService.insertNew();
}]
},
params: {
artID: <-- new ID from DB
},
i did tests with stateParams in serval variations (in resolve and by params). how can i bring the new ID to stateParams, so i can access from the views?
Thanks for any help!
I'm not so sure your oder of operations is correct. params is for when you already have that data. You should return the data from your resolve, then you can access it in your scope, for ex:
Service:
.service('postService', function ($http) {
this.insertNew = function () {
return $http.post('create_new.php').then(function (data) {
return data;
});
}
})
Route:
$stateProvider
.state('newRecord', {
views: {
"main": {
controller: 'SomeCtrl',
templateUrl: '...'
}
},
resolvedId: {
newArtID: function (postService) {
return postService.insertNew().then(function (response) {
return response;
});
}
}
})
Controller:
.controller('SomeCtrl', function (resolvedId) {
var newID = resolvedId.id; //depending on what is returned
});

Search all entities Symfony2

I'm working on a webapplication in Symfony2. At the moment I have several pages that include a search form where you can search for specific entities that belong to that page.
For example; I have a client page with an overview of client information. Here you can search for clients with a name like your search value. Thats no rocket science I guess.
At the front page I want to somehow search all my entities at once. I was thinking about combining the searches I already have, or maybe there is a function in Symfony that allows this?
Here's some of my code for the search(es) I have so far:
Live search action for clients:
public function liveSearchAction(Request $request)
{
$string = $this->getRequest()->request->get('sQuery');
$clients = $this->getDoctrine()
->getRepository('clientsBundle:client')
->findByLetters($string);
$response = new JsonResponse(array('clients' => $clients));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
The repository function findByLetters:
public function findByLetters($string){
$query = $this->getEntityManager()
->createQuery(
'SELECT c FROM clientsBundle:client c
WHERE c.name LIKE :string'
)->setParameter('string', '%'.$string.'%');
$result = $query->getArrayResult();
return $result;
}
The AJAX call for returning searchresults
(function($, Handlebars, window, document, undefined) {
var that = this;
var oXHR;
var source = $("#searchResult").html();
var template = Handlebars.compile(source);
var action = $('#quickSearch').data('action');
var route = $('#quickSearch').data('route');
Handlebars.registerHelper('url', function(options) {
console.log(this, options);
return new Handlebars.SafeString(
Routing.generate(route, {'id': this.id})
);
});
$('#quickSearch').on('input',function() {
var $this = $(this);
var searchText = $this.val();
console.log('searching for: ' + searchText);
if (typeof oXHR !== 'undefined') {
oXHR.abort();
}
oXHR = $.ajax({
type: "POST",
url: action,
dataType: "json",
data: {
sQuery : searchText
},
success: function(response)
{
var html = template(response);
// console.log(html);
$('#list .list-group').html(html);
},
error: function(failresponse)
{
console.log( failresponse );
}
});
});
}).call(window.Test = window.Test || {}, jQuery, Handlebars, window, document);
As you might have noticed, the return of the AJAX call gets handled by handlebars.

Angularjs How to get Parsed Data of Json Format return by the $http response in Service

First of all i want to clear, That am not accessing the data using web service.
My database(php) and angularjs UI are on the same server it self.
In Service of AngularJs, am sending http Get Request to interface.php(Database) it return json format. I dont how to actually parse the data and send it to Controller ?
Here Clear Cut Code :)
var app=angular.module("app.chart.ctrls",['ngSanitize']);
Controller
app.controller("registrationCtrl",["$scope","$location","logger","registerService",function($scope,$location,logger,registerService){
$scope.data= registerService.getYears();
**how to parse the data is it correct format or not ? in Controller**
}
**Service**
app.factory('registerService', function ($http,$q,$log) {
return {
getYears:function () {
var deferred = $q.defer();
$http({
method : "GET",
url : "interface.php",
}).success(function(data){
**** How to Return the data from here to Controller ***
})
},
}
});
interface.php
1 - First define a object in your controller that later you can use as a storage for your http response like this :
app.controller("registrationCtrl",["$scope","$location","logger","registerService",function($scope,$location,logger,registerService){
$scope.data = {};
// fire your servise function like this :
registerService.getYears($scope);
}
2- In your Servise :
app.factory('registerService', function ($http) {
return {
getYears:function (scope) {// scopes comes from your controller
$http({method : "GET",url : "interface.php"})
.success(function(data){
scope.data = data;!!!!!!
})
}
}
});
It's done so far and it'll work ;
BUT if your want to use some kind of promise , you can do like this :
in your controller :
.
.
.
$scope.data = {};
// fire your servise function like this :
var promise = registerService.getYears();
promise.then(function(msg){
$scope.data = msg.data[0];
});
.
.
.
in your Service :
app.factory('registerService', function ($http) {
return {
getYears:function () {
var promise = $http({method : "GET",url : "interface.php"});
}
return promise ;
});
from https://docs.angularjs.org/tutorial/step_11
the source:
[
{
"age": 13,
"id": "motorola-defy-with-motoblur",
"name": "Motorola DEFY\u2122 with MOTOBLUR\u2122",
"snippet": "Are you ready for everything life throws your way?"
...
},
...
]
your service looks like:
phonecatServices.factory('Phone', ['$resource',
function($resource){
return $resource('phones/:phoneId.json', {}, {
query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
});
}]);
and your controller:
phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone', function($scope, Phone) {
$scope.phones = Phone.query();
$scope.orderProp = 'age';
}]);
so, you call the service from within the controller and get the results back.

AngularJS service for php files

i am trying to create a service for angular which should get the data from a php that generates a json. Right now my service looks like this
fixEvents.service('contactService', function($http, $q) {
this.getallContact = function() {
var json = $q.defer();
$http.get('models/contact.getall.json')
.success(function(data) {
json.resolve(data);
})
.error(function() {
json.reject();
});
return json.promise;
};
});
and my controller looks like this
fixEvents.controller('contactCtrl', function($scope, contactService) {
$scope.title = "CONTACT";
$scope.jsonContact = contactService.getallContact();
$scope.showMessage = function() {
alert($scope.jsonContact.length);
}
});
the problem is my jsonContact does not get any result. It seems to be undefined. Is there something i did wrong? And by the way is there a better way to do this ? Thank you, Daniel!
You have to use .then back in the controller to work with the data:
var jsonContactPromise = contactService.getallContact();
jsonContactPromise.then(function(data) {
$scope.jsonContact = data
}, function(error) {
console.log("ERROR: " + error);
});

Categories