I got this sports website project written in Codeigniter/AngularJs and I'm stucked at the communication between view/controller/model.
There is this function that updates user points in view, then I should use this dataSavingHttp service to update the database also, but I'm really confused about its functionality
The View Angularjs controller
$scope.buy_salary_cap = function() {
$scope.remainSalary = parseInt($scope.contestDetails.salary_cap/10) + parseInt($scope.remainSalary);
$rootScope.profile_data.points_balance = parseInt($rootScope.profile_data.points_balance) + parseInt(1);
dataSavingHttp({
url: site_url+"lineup/update_user_points_balance",
data: {},
}).success(function (response) {
$scope.content = response.data.points_balance;
}).error(function (error) {
$scope.content = "Erro!";
});
$scope.isDisabled = true;
}
The Codeigniter controller
private function update_user_points_balance()
{
return $this->Lineup_model->update_user_points_balance();
}
The Model function
public function update_user_points_balance()
{
$condition = array('user_id' => $this->session->userdata('user_id'));
$config['points_balance'] = $this->remain_balance;
$this->table_name = USER;
return $this->update($condition , $config);
}
Here is the dataSavingHttp code
vfantasy.factory('dataSavingHttp', function($http, $location) {
var wrapper = function(requestConfig) {
var options = angular.extend({
url: "",
method: "POST",
data : '',
dataType: "json",
},requestConfig);
var httpPromise = $http(options);
httpPromise.success(function(result, status, headers, config){
var l = window.location;
wrapper.lastApiCallConfig = config;
wrapper.lastApiCallUri = l.protocol + '//' + l.host + '' + config.url + '?' +
(function(params){
var pairs = [];
angular.forEach(params, function(val, key){
pairs.push(encodeURIComponent(key)+'='+encodeURIComponent(val));
});
return pairs.join('&')
})(config.params);
wrapper.lastApiCallResult = result;
})
return httpPromise;
};
return wrapper;
});
Maybe there is a simpler solution, but I'm really new in these languages. Thanks in advance.
Related
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;
}
Is it possible to make ajax post request in ServiceWorkers execution?
I have a Service Worker registered that just "listen" for a push notification.
I need to call a PHP function (in order to read some data from my database) during the execution of the Service Worker (when receiving the push notification), but I'm not able to do it. When I call the ajax post it goes to "error" section and the error is "No Transport" (I tried to add the "jQuery.support.cors = true;" like suggested in other thread, but this not fixed the issue).
Here below the serviceworker code.
Is it impossible to do what I'm trying to do, or I'm doing something wrong?
var document = self.document = {parentNode: null, nodeType: 9, toString: function() {return "FakeDocument"}};
var window = self.window = self;
var fakeElement = Object.create(document);
fakeElement.nodeType = 1;
fakeElement.toString=function() {return "FakeElement"};
fakeElement.parentNode = fakeElement.firstChild = fakeElement.lastChild = fakeElement;
fakeElement.ownerDocument = document;
document.head = document.body = fakeElement;
document.ownerDocument = document.documentElement = document;
document.getElementById = document.createElement = function() {return fakeElement;};
document.createDocumentFragment = function() {return this;};
document.getElementsByTagName = document.getElementsByClassName = function() {return [fakeElement];};
document.getAttribute = document.setAttribute = document.removeChild =
document.addEventListener = document.removeEventListener =
function() {return null;};
document.cloneNode = document.appendChild = function() {return this;};
document.appendChild = function(child) {return child;};
importScripts('js/jquery.js');
self.addEventListener('push', function(event) {
jQuery.support.cors = true;
var endpoint = "";
if (event.data) {
endpoint = event.data.text();
}
var data = {
query: "SELECT * FROM [TABLE] WHERE ENDPOINT = '" + endpoint + "'"
};
$.ajax({
data: data,
method: "POST",
url: 'ExecuteQueryJquery.php',
dataType: 'json',
success: function (obj, textstatus) {
var o = obj;
},
error: function (obj, textstatus) {
var o = obj;
}
});
});
I created a controller and called the function for one time.But it call two times and inserted the value two times.I call the service upload_album in controller.Now value got inserted for two times.one with original value and another with dummy value
Controller
$scope.savealbum = function() {
$scope.album_pids = $routeParams.id;
$timeout(function () {
//console.log($scope.justapp);
for (tt in $scope.justapp) {
if ($scope.justapp[tt].id == $scope.album_pids) {
for (var i = 0; i < $rootScope.media_lib.length; i++) {
}
}
}
$scope.promise=AlbumServices.upload_album($scope.album_pids,$scope.images,$scope.videos);
$scope.promise.then(function(data) {
console.log(data);
alert('Photos Added to Album Successfully');
// $location.path('album_details/' + $routeParams.id);
}, function(reason) {
console.log(reason);
});
}, 1500, false);
};
Service
upload_album: function (alb,img,vid) {
var deferred = $q.defer();
var data = {};
data.pagename = "upload_album";
data.album = alb;
data.photo = img;
data.video = vid;
$http.post('js/data/album.php', data)
.success(function (data, status, headers, config)
{
console.log(status + ' - ' + data);
deferred.resolve(data);
})
.error(function (data, status, headers, config)
{
deferred.reject(data);
console.log('error');
});
return deferred.promise;
}
php
function upload_album ($prefix) {
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$sub_id=$request->album;
$val=$request->photo;
$photo = json_encode($val);
$video = json_encode($request->video);
$now = date('Y-m-d H:i:s');
$count_pho = sizeof($photo);
$count_vid = sizeof($video);
$test = '';
if($count_pho != '0' ) {
$test .= "('".$sub_id."','".$content_type."','".$photo."','".$website_id."','".$now."'),";
$demo = substr($test, 0, -1);
$sql="INSERT INTO `album_details` (SUB_ID,CONTENT_TYPE,CONTENT_VALUE,WEBSITE_ID,CreatedTime)VALUES".$demo;
$query = mysql_query($sql) or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $sql, __LINE__);
}
if ($query) {
echo $msg = true;
} else {
echo $msg = false;
}
}
Because we cannot se the whole code (including the HTML) my suggestions are these:
check your html and/or run method inside angular to be sure that your controller was not instanciated twice
create a unique key pair in your database (it could help not have double records)
create a debouncer when using timeout so that if the timeout is always launched once. something like this:
var t = null;
var mySaveFunction = function () {
if (t) {
clearTimeout(t);
}
t = setTimeout(function () {
/* do saving here */
}, 2000);
};
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.
I try to load database data in my Select2 input. (Im working on CI)
Here's my code from the controller : transforms array in echo json
class Ajax extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('client');
}
public function returnClientsAjax(){
echo json_encode($this->client->getClients());
}
}
Model : returning an array of results
function getClients(){
return $this->db->query("SELECT idclient AS id, CONCAT(societe,' [', nom,']') as text FROM du_client WHERE (societe != '' AND nom != '') AND evo2012 >=2 AND type_client != 'Particulier' AND statut_client = 'Demandeur' AND idclient = 6141;")->result_array();
}
My Select2 :
$("#sel_clients").select2({
placeholder: "Search for an Item",
ajax: {
dataType: "json",
url: "http://commexpert.dev.local/ajax/returnclientsajax",
results: function (data) {
return {results: data};
}
}
});
The input still empty so, don't know what to do.
Thnaks :D
I think something is missing on your data results method. Here is my code from working ajax select2 component:
results: function (data) {
var results = [];
var id1 = data.id;
var name = data.text;
$.each(data.data, function(index, item){
results.push({
id: item[id1],
text: item[name].trim()+' : '+ item[id1]
});
});
return {results: results};
}
also, I'm having somewhat diff data call also:
data: function (term) {
try {
mirko = $(this).closest('[rendered]').find( "input[fparamname$=" + $(this).attr('flookupfiltref') + "]" ).val();
if (mirko.indexOf(' : ') >=0 ) { // pocetna vrijednost
mirko = mirko.split(' : ')[1].trim();
}
} catch(e){
mirko = '';
}
return {
sp_name: $(this).attr('objectname'),
fl_name: $(this).attr('fparamname'),
node_id: $(this).attr('node_id'),
bound: mirko,
q: term,
};
},
I'm having somekind of manipulation before sending or returning q to server,, but I hope that can help you for your service :)
hth, k