Ajax and codeigniter framework issues - php

I have a problem with AJAX and CodeIgniter, I want to get total count of users in database but there is no data found.
my controller:
public function TotalUsers()
{
if($this->input->post("action")=='GetTotalUsers')
{
$this->load->model("usersmodel");
$totalcount=$this->usermodel->GetTotalUserCount();
echo $totalcount;
}
}
my model:
public function GetTotalUserCount()
{
$query = $this->db->get("users");
return $query->num_rows();
}
My html and jquery:
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-yellow">
<div class="inner">
<h3 id="totaluser"></h3>
<p>Total Users</p>
</div>
<div class="icon">
<i class="ion ion-person-add"></i>
</div>
More info <i class="fa fa-arrow-circle-right"></i>
</div>
</div>
<script>
$(document).ready(function () {
GetTotalUsersCount();
function GetTotalUsersCount() {
var action='GetTotalUsers';
$.ajax({
url:"<?php echo base_url()?>Users/TotalUsers",
method:"post",
data:{action:action},
success:function (data) {
$("#totaluser").html(data)
}
})
}
})
</script>

I think you might be sending it encoded in JSON while the controller is expecting it serialized, although I'm not sure.
Run var_dump() on $this->input->post("action").
If that doesn't give GetTotalUsers, then that's you're problem. You'll need to either set the controller to accept raw post data and decode as json, serialize the data instead of using a javascript object (JSON), or if possible, just remove the action conditional because currently it doesn't look useful as shown.

I suspect that url: is not evaluating to the correct value. There are a couple syntax errors (missing semi-colons) too. Try this JavaScript. Use your browser's "Developer Tools" to examine the headers to see where the post "goes" and that "action" is being posted.
$(document).ready(function () {
GetTotalUsersCount();
function GetTotalUsersCount() {
$.ajax({
url: '<?php echo base_url("Users/TotalUsers"); ?>',
method: "post",
data: {action: 'GetTotalUsers'},
success: function (data) {
$("#totaluser").text(data);
}
});
}
});
I'm curious why you use ajax and don't simply determine and pass the total count to the initial loading of the view?

1.Use Ctrl+Shift+I (or navigate to Current Page Control > Developer >
Developer Tools )or( use right click on your page and then select inspect
element)
2.Go to "Network" tab
3.Find your ajax request in "Name Path" column
4.Click on the specific ajax link

Related

How to pass a variable in JavaScript if in view it's empty?

So, I created a report system, but in the last step, I have a little problem...In JavaScript I'm using a variable from database for Ajax, but when a post has no comments, I'm getting Undefined variable: key.
Here is my script
if (isset($key)){
$('#yourFormIdComment{{$key+1}}').submit(function(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
method:'POST',
url:'/career_report_comment',
data:data,
success: function (result) {
// do something with result
}
});
});
}
Here is my view with variable
#foreach($opinionComment as $key => $comments)
<div class="news-v3 bg-color-white">
<h4 style="font-size: 13px">
{{ $comments->user->username }}</h4>
<p>{{ $comments->comments }}</p>
<ul class="post-shares post-shares-lg">
<li #if ($key === 0) class="active" #endif style="float: right;left: 20px;bottom: 30px"><a data-toggle="modal" data-target="#exampleModalComment{{$key+1}}" href="javascript:void(0)" ><i class="rounded-x icon-flag"></i></a></li>
</ul>
</div>
#endforeach
My question is...how can I pass the variable {{$key+1}}from script even if a post has no reviews/comments?Because this is happening only when I have comments on a post.
Andrew i after talking in the comments and checking your code i might have found a solution to your problem.
You get a error:
Undefined variable: key
You get that error because the key isnt defined.
if (isset($key)){
$('#yourFormIdComment{{$key+1}}').submit(function(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
method:'POST',
url:'/career_report_comment',
data:data,
success: function (result) {
// do something with result
}
});
});
}
In the first part of your code you use the variable $key, but the key is defined within the foreach in the second part of your code. That's why you get the error.

How to pass the button value in ajax url and display the json response in bootstrap panel body?

Laravel View code:
<div class="container" style="display:none;" id="panel1">
<div class="panel panel-default">
<div class="panel-heading" style="color:#0000FF" data-toggle="tooltip" title="Gateways!">
<input type="button" value="Haghway Lite" style="background-color:transparent;border:none;width:100%;height:100%;" name="button1" id="button1"><font size="5"></font>
</div>
<div class="panel-body" align="center">
<img src="haghwaylitecontroller.jpg" width="100" height="100">
</div>
</div>
</div>
This my view code.
Script(ajax):
<script type="text/javascript">
$(document).ready(function() {
$("#button1").click(function(){
var button1 = $(this).val();
if(button1) {
$.ajax({
url: "{{url('panelview').'/'}}"+button1,
type: "GET",
dataType: "json",
success:function(data) {
$.each(data, function(key,value) {
$("#panel1").append('<div "'+ value.panel1 +'"></div>');
});
//alert("success");
}
});
}else{
alert("failed");
}
});
});
In this script code, I calling the ajax function with the button id and trying to pass the value of button to be redirected to the mentioned url and the returned json response to be displayed on the panel body. Here if I am trying to print the button value it alerts NaN
Route:
Route::get('panelview/{button1}','viewController#newProduct');
Controller:
public function newProduct($button1)
{
$users=addModel::select('Desc')->where('Pname',$button1 )->first();;
return json_encode($users);
}
The controller code should fetches the correspoding record based on the value of button and return the response.

Delete row with ajax and delete the record on page too

I'm trying to remove the record in database via ajax. In the same time I want to delete also the record from the page. So I have this in my HTML
<ul id="comments-list record-'.$row['id'].'" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">'.$row['author'].''</h6>
<a href="?delete='.$row['id'].'" class="del">
<i class="fa fa-trash "></i>
</a>
</div>
</div>
</div>
</li>
</ul>
This is inside the loop which display all records on page. This is the ajax function
$(document).ready(function() {
$('.del').click(function(e) {
e.preventDefault();
var parent = $(this).parent();
$.ajax({
type: 'get',
url: 'delete.php',
data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
});
And my delete.php is simple delete query
$stmt = $pdo->prepare("DELETE FROM comment where id = :id");
$stmt->bindParam(':id', (int)$id, PDO::PARAM_INT);
$stmt->execute();
Current error is from the ajax when I click on delete on this line index.php:183 Uncaught TypeError: Cannot read property 'replace' of undefined
Uncaught TypeError: Cannot read property 'replace' of undefined
The ajax part is from tutorial since I'm very unfamiliar with js/ajax.
What can be the problem here?
In your function $(this) = <a href="?delete='.$row['id'].'" class="del">.
var parent = $(this).parent(); = <div class="comment-head">
which has no ID. Thus attr('id') returns undefined.
You can select the ul element this way:
var parent = $(this).closest('ul.comments-list.record');
How about this code: (make full use of jquery)
<ul id="comments-list record-'.$row['id'].'" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">'.$row['author'].''</h6>
<i onclick="del(<?=$row['id']?>)" class="fa fa-trash "></i>
</div>
</div>
</div>
</li>
your jquery becomes:
function del(i)
{
$.ajax({
type: 'get',
url: 'delete.php',
data: {'ajax':1,'delete':i},
success: function() {
get_list();
}
});
}
function get_list()
{
//make ajax call to get data from php
}
You are getting undefined because the parent you are fetching is this one:
<div class="comment-head">
As you can see that does not have an id. That is why you are getting undefined.
For reference, I do not believe that there is a replace() method in jQuery. What you might be looking for is a replaceWith() method. Please refer to the documentation for more information.
I do not believe that you need to do a replace anywhere. From what I can understand, you want to pass the row[id] as a parameter on your AJAX call. Instead of trying to do a replace, use data as shown below:
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
crossorigin="anonymous"></script>
<style>
#comments-list {
border: 1px solid black;
}
</style>
<ul id="comments-list" data-id="1" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">Me</h6>
<a href="?delete=1" class="del">
click here
</a>
</div>
</div>
</div>
</li>
</ul>
<script>
$(document).ready(function() {
$('.del').click(function(e) {
e.preventDefault();
// Grab the id
var commentsBlock = $('#comments-list');
var id = commentsBlock.data('id');
console.log(id);
$.ajax({
type: 'get',
url: 'delete.php',
data: 'ajax=1&delete=' + id,
success: function() {
commentsBlock.slideUp(300,function() {
commentsBlock.remove();
});
}
});
});
});
</script>

$http.post not working inside ng-click function in Angular Js

I'm developing a project with Anjular js and Codeigniter 3. I have faced some issues with routing in angular js. I have a view page with a list of details of users and inside that list there is a tag with ng-click="myName()". I have declared this function inside my js file and this function works fine.
<div class="container" ng-controller="ListController">
<div class="row">
<div class="col-lg-12 text-center">
<h1>Starter Template</h1>
<p class="lead">Complete with pre-defined file paths that you won't have to change</p>
<div class="row">
<div class="col-sm-6 col-md-4 wow zoomIn" data-wow-delay="0.5s" ng-repeat="items in artists">
<div class="thumbnail">
<img ng-src="{{settings.base_url}}/application/assets/images/profile/{{items.shortname}}.jpg" alt="...">
<div class="caption">
<h3>{{items.name}}</h3>
<p>{{items.bio}}</p>
<p>Button Button</p>
</div>
</div>
</div>
</div>
</div>
</div>
Inside this function "myName()" I have written $http.post for getting a function inside the controller(Codeiginter controller). I'm using auth.php as controller and functionOne() is the function to retrive.
var base_url_abs = window.location.origin;
var base_url = base_url_abs+'/AngularExPack/Angular_Bootstrap_CI_1/';
var base_url_controller = base_url_abs+'/AngularExPack/Angular_Bootstrap_CI_1/index.php/';
myApp.controller('ListController', ['$scope', '$http', 'settings', function($scope, $http) {
$http.get('application/datas/data.json').success(function (data){
$scope.artists = data;
});
$scope.myName = function() {
alert("hai1");
/*
$http.post(base_url_controller+'auth/functionOne/').success(function (response){
$scope.data = response
console.log(response);
//alert($scope.data);
});*/
/**/ $http({
method : 'POST',
url : base_url_controller+'auth/functionOne/',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
$scope.data = response
console.log($scope.data);
alert($scope.data);
});
}
}]);
When i run this, an error is occured and showing like this inside the console
But i'm getting the correct result when i click on this link and also if i give base_url path inside the href inside a tag.
Button Button
But what i need is inside this myName function i have to access the controller function functionOne() using $http using angular js. Is that possible.?
If anyone knows please help me to find out the solution in ng-click. Correct me if i written wrong code.
Thank you.
you should use
$http({
method : 'GET',
url : base_url_controller+'auth/functionOne/',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
$scope.data = data
console.log($scope.data);
alert($scope.data);
});

use session made from ajax inside blade laravel 4.2

hi so im making a session via ajax when a certain button is clicked here is the code
function cModal(id)
{
alert(id);
$.ajax({
method: 'post',
url: 'http://localhost/dummy/app/putSession.php',
data: {
'dID': id
},
success: function()
{
alert(id);
}
});
}
it is successfull because it alerts the id inside the success:function()
in my putSession.php file here is how i did it
<?php
session_start();
$tId = $_POST['dID'];
$_SESSION["sID"] = $tId;
exit();
?>
but the thing is i can't access it inside my blade file im calling it like this
<div class="modal-content">
<div class="row rowMarg">
<?php session_start(); ?>
#if(Session::has('sID'))
{{ Session::forget('sID') }}
<h6>Information.</h6>
#else
<h6>File details not found.</h6>
#endif
</div>
</div>
it just goes to the file details not found
any idea what im doing wrong? thanks in advance!
use laravel session like
$request->session()->put('user', 'value');
$request->session()->get('user', 'value');
$request->session()->push('user.teams', 'developers');
for more https://laravel.com/docs/4.2/session

Categories