Angular does not pick $scope.variable_name - javascript

Below is my HTML code.
<div class="container" ng-app="mintcart">
<div class="panel panel-default" ng-controller="categoriesctrl">
<input type="hidden" ng-model="session.sid" value="<?php echo session_id();?>"/>
<div class="panel-body">
<div class="row">
<ul class="nav nav-pills">
<?php
$i = 0;
while($i < count($list)){
$name = $list[$i]['categoryName'];
$id = $list[$i]['id'];
$normalUrl = $list[$i]['normalImageUrl'];
$hoverUrl = $list[$i]['hoverImageUrl'];
if($i == 0){
echo "<li role='presentation' class='active' ng-click='loadproducts($id)'><a href='#' >$name</a></li>";
} else {
echo "<li role='presentation' ng-click='loadproducts($id)'><a href='#''>$name</a></li>";
}
$i++;
}
?>
</ul>
</div>
</div>
</div>
</div>
ANd below is my JS code.
var app = angular.module('mintcart',[]);
app.controller('categoriesctrl', function($scope, $http){
var auth = {};
$http({
method: 'GET',
url: baseurl + 'api/get_product_categories'
}).then(function successCallback(response) {
$scope.categories = response.data.categories;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
$scope.loadproducts = function(item_id) {
alert($scope.session.sid);
$http({
method: 'GET',
url: baseurl + 'api/get_items_in_category_cart/' + item_id
}).then(function successCallback(response) {
$scope.items = response.data.products;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
//$scope.Language = lang;
};
});
When the loadproducts function is called the alert($scope.session.sid); gives me "undefined". I can't understand why my element is not being picked up.
Any help is greatly appreciated.

php works on the server side, you need to set the variable using a javascript not on the view.
Create a variable in JavaScript which gets the returned content of PHP.
var sessionid = <?php echo session_id();?>
then , you can access the variable in controller,
var app = angular.module("MyApp", []);
app.controller("categoriesctrl", function($scope) {
$scope.session.sid = sessionid ;
console.log($scope.session.sid);
});

Related

jQuery ajax keeps adding more and more elements

When a user searches for a username he gets results. When he backspaces or modifies the query, the results just keep getting added on top of the previous results instead of the results being modified and a fresh, updated result returned. I have modified the script here and there with no success yet.
My view:
<div class='container'>
<div class='row'>
<div class='col-sm-6 col-xs-12 col-centered'>
<div class='panel panel-default'>
<div class='panel-heading sticky'>
<div class='back pull-left'><a href='<?php echo site_url('chats') ?>'><span class='glyphicon glyphicon-chevron-left'></span></a></div>
<h1 class='panel-title text-center'>New Chat</h1>
<input class='form-control' id='search-field' type='text' placeholder='Username'>
</div>
<div class='panel-body'>
<ul class='users collapse'>
</ul>
</div>
</div>
</div><!--end column-->
</div><!--end row 1-->
</div><!--end container-->
My JS:
$(function() {
var $search_field = $('#search-field');
$search_field.on('keyup', searchByUsername);
$search_field.focus();
});
function searchByUsername(e) {
var username = this.value.trim();
var keyCode = e.keyCode;
var data = {username : username};
var $usersElement = $('.users');
var users = [];
// Use this condition to prevent searching when whitespace is entered
if (username) {
var request = $.ajax({
url : site_url + 'search/searchByUsername/',
method : 'GET',
data : data,
dataType : 'json'
});
request.done(function(jsonRepsonse) {
if (jsonRepsonse) {
var status = jsonRepsonse.status;
var usernames = jsonRepsonse.usernames;
if (status === 'success') {
$.each(usernames, function(index, value) {
// must be one line or will throw syntax error
users.push("<li class='user text-center'><a href='#'><span class='glyphicon glyphicon-user'></span><strong class='username'>" + value + "</strong></a></li>");
});console.log(users);
$usersElement
.append(users)
.show();
}
}
});
request.fail(function(xhr, status, error) {
console.log(error);
});
}
users.length = 0
$usersElement.hide();
}
My Codeigniter controller function:
public function searchByUsername()
{
$username = $this->input->get('username', true);
$usernames = [];
if (!empty($username)) {
$usernames = $this->find_users_model
->searchByUsername($username);
}
if (!empty($usernames)) {
$this->jsonResponse(
['status' => 'success',
'usernames' => $usernames]);
return;
}
$this->jsonResponse(
['status' => 'success',
'usernames' => ['User not found']]);
}
private function jsonResponse($response)
{
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response));
}
Result:
This is your users container:
var $usersElement = $('.users');
On ajax response, you do:
$usersElement.append(users).show();
But you're always appending, never removing. Try emptying the element before populating it with users again:
$usersElement.empty().append(users).show();

TypeError: myObservableArray is undefined

I have an observable array that I want to be able to delete entries from via a button in the HTML using the knockout.js framework. However, when I try to use the observable array this.comments in the deleteComment function, I get a TypeError: this.comments is undefined, even though it is clearly defined and has entries. this.comments is even used in the entryComments function which works perfectly fine. Am I missing something?
HTML/PHP:
<div class="textblock">
<h1>User Comments</h1>
<ul id="usercomment" data-bind="foreach: comments">
<li><p><strong data-bind="text: comment"></strong> - <strong data-bind="text: user"></strong></p>
<button data-bind="visible: display(), click: $parent.deleteComment.bind($data, $index)" >Delete Comment</button>
</li>
</ul>
</div>
<br />
<?php if (isset($_SESSION['logged_in'])): ?>
<?php if ($_SESSION['logged_in'] == true): ?>
<div class="textblock">
<ul>
<li>
<form name="commentform" data-bind="submit: enterComment.bind($data,$data.comment )">
<input type="text" data-bind="value: $data.comment"/>
<button type="submit">Submit Comment</button>
</form>
</li>
</ul>
</div>
<?php endif; ?>
<?php endif; ?>
Javascript:
var AppViewModel = function (commentList, userList) {
//Initializing data
this.displayButton = ko.observable(false);
this.comments = ko.observableArray();
this.username;
$.ajax({
url: "http://localhost/sem4/recept/UserInfo.php",
async: false,
dataType: 'json',
success: function(data) {
username = data.username;
}
});
//Giving the array values
for(var i = 0;i<=commentList.length -1;i++ ){
if(username === userList[i]){
this.comments.push(new Comment(commentList[i],userList[i],true ));
}
else{
this.comments.push(new Comment(commentList[i],userList[i], false));
}
};
//Function is called but it cannot define this.comments
this.deleteComment = function(index){
this.comments.splice(index,1);
}
//This function works without any problems
this.enterComment = function (comment) {
$.ajax({
url: "http://localhost/sem4/recept/UserInfo.php",
async: false,
dataType: 'json',
success: function(data) {
username = data.username;
}
});
this.comments.push(new Comment(comment, username,true));
$.post("http://localhost/sem4/recept/AddComment.php", {
comment: comment,
username: username
});
};
//OBJECTS
function Comment(comment, user,bool) {
var self = this;
self.comment = ko.observable(comment);
self.user = ko.observable(user);
self.display = ko.observable(bool);
};
};
this scope changes when you use a function. a regular workaround is defining a self variable at the top and using it when you need to access the whole function scope.
var AppViewModel = function (commentList, userList) {
//Initializing data
var self = this;
....
self.deleteComment = function(index){
self.comments.splice(index,1);
}
...
}
The easiest fix is to use an arrow function, as they inherit this from their context.
...
this.deleteComment = (index)=>{ // was function(index){
this.comments.splice(index,1);
}
...

CodeIgniter - getting data from database automatically using setInterval

In codeigniter, I want to display the change in the database automatically without reloading the page so i use ajax to run a controller function in my view. I'm using setInterval to run the function over and over again until the controller function listen_auth returns 1 and the view displays 1.
VIEW:
<h4 class="qr-title" id="status"></h4>
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
console.log(data);
}
});
document.getElementById("status").innerHTML = isAuth;
}
</script>
here's the listen_auth() function in my CONTROLLER:
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
return 1;
} else{
return 0;
}
}
The problem is that isAuth variable will only change once the page has been reloaded... Am I doing something wrong? Or is there any better way to do this?
The function from server 'listen_auth()' should print text not return.
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
echo 1;
} else{
echo 0;
}
}
And then get the answer from server in AJAX request:
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
document.getElementById("status").innerHTML = data;
}
});
}
</script>
You need to declare $isAuth and assign its value in ajax request, because php variable will not change its value without server request.

AngularJS insert data twice to database

I am trying to insert data to database through angularJS but the data inserted twice.. I have tried to use ngRoute but still I face the same problem.
app.js
var app = angular.module("addDepApp", []);
app.controller('insertDepCtl', function($scope, $http) {
var isSend = false;
$scope.$on('newuser', function(event, data){
load(true);
});
var load = function(isEvent){
if($scope.$parent.newuser != null){
isSend = true;
}
};
load();
$scope.insertDepartment = function () {
console.log("called insertDepartment");
if (isSend == true){
$scope.newuserSend = {'org_id': $scope.$parent.newuser.org_id, 'dep_name': $scope.department};
$http.post("http://192.168.1.12:8888/XXXX/XXX/insertDep.php/",$scope.newuserSend)
}
}
});
add.html
<body ng-app="addDepApp">
<div class="12u$" ng-controller="insertDepCtl">
<input type="button" value="تسجيل" class="special" id="signup" ng-click="insertDepartment()"/>
</div>
</body>
Remove ng-controller="insertDepCtl" from your html code, your router injects this for you. Right now, you're calling everything twice
I have changed the code to this and now it works fine!!
$scope.insertDepartment = function () {
if (isSend == true) {
var request = $http({
method: "post",
url: "http://192.168.1.106:8888/XXXX/XXX/insertDep.php/",
data: {'org_id': $scope.$parent.newuser.org_id, 'dep_name': $scope.department},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
}

Successful ajax script doesn't give me response

The general problem is that I cannot get back echo or return through ajax from another file.The alert(msg) is empty. Does that prevent.default stop sending the GET? I am not very fluent in programming, could you please help me in this?
I have my simple form:
<form class='findAndBlock1' method="GET" action="">
<input type='text' name="nameToBlock1" placeholder=" who do you want to block?" class='nameInput'>
<input type='submit' value="Search" class='submitInput1'>
</form>
After clicking it, the ajax script starts:
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg);
},
error : function(error) {
alert('error');
}
});
});
</script>
It is directed to the script that is routed like this:
Route::any('/searchFriendsToBlock', 'SettingsController#searchFriendsToBlock');
Here is the script that is run through ajax:
public function searchFriendsToBlock() {
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
echo "hello";
return Response::json($newArr);
}
Use dataType parameter in ajax request as you are sending response in json format the default dataType is set to html in jQuery.ajax()
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg.type);
},
error : function(error) {
alert('error');
}
});
});
</script>
And Your script should be like this
public function searchFriendsToBlock()
{
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
$response = array();
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
$response['type'] = 'sussess';
$response['data'] = $newArr;
return Response::json($response);
}

Categories

Resources