Load Data into Dynamically created Tabs using jQuery AJAX and PHP - php

My situation is as follows:
PHP script retrieves data from a database. This information is shown in the first tab. This tab will always stand and can not be closed. This is fine, see me code.
try {
print '
<div class="clientTabs">
<ul class="nav nav-tabs" id="navTabs">
<li class="active" id="li0">Alle clienten</li>
</ul>
</div>';
$selectTabbladen = $gebruiker_data->runQuery("SELECT * FROM clients ORDER BY clients_id");
if (!$selectTabbladen->execute()) return false;
if ($selectTabbladen->rowCount() > 0) {
print '
<div class="tab-content" id="tabContent">
<div id="client0" class="tab-pane active">
<div class="bootstrap-table">
<div class="fixed-table-toolbar">
<div class="bars pull-left">
<button id="btnTabdel" class="btn btn-danger btn-labeled" disabled="disabled">Vervijderen</button>
</div>
</div>
</div>
<table class="table table-bordered" id="table"
data-toolbar="#toolbar"
data-search="true"
data-show-refresh="true"
data-show-toggle="false"
data-show-columns="true"
data-show-export="true"
data-detail-view="true"
data-detail-formatter="detailFormatter"
data-pagination="true"
data-id-field="id"
data-minimum-count-columns="2"
data-page-list="[10, 25, 50, 100, ALL]"
data-show-footer="false">
<thead>
<tr>
<th class="text-center" width="1">#</th>
<th>Name</th>
<th>Address</th>
<th>Zip</th>
<th>City</th>
<th>Tel.</th>
</tr>
</thead>
<tbody>';
while($aRow = $selectTabbladen->fetch(PDO::FETCH_ASSOC)) {
$id = $aRow['clients_id'];
$name= $aRow['name'];
$adress= $aRow['address'];
$zip= $aRow['zip'];
$city= $aRow['city'];
$tel= $aRow['tel'];
print '<tr class="tabData" id="'.$id.'">
<td>
<label class="cr-styled">
<input type="checkbox" ng-model="todo" class="tabID" value="'.$id.'"/>
<i class="fa"></i>
</label>
</td>
<td>'.$name.'</td>
<td>'.$address.'</td>
<td>'.$zip.'</td>
<td>'.$city.'</td>
<td>'.$tel.'</td>
</tr>';
}
Double-click creates a dynamic tab that retrieve other data from the database associated with this ID. This is also good, a new TAB is created and the data retrieved.
//Tabs
$('body').on('dblclick', '.tabData', function () {
var tab_id = $(this).attr("id");
addTab(tab_id);
});
function addTab(tab_id) {
// If tab already exist in the list, return
if ($("#li"+tab_id).length != 0) {
$("#navTabs li").removeClass("active");
$("#client0").removeClass("active");
$("#li"+tab_id).addClass("active");
$("#client"+tab_id).addClass('active').show();
//return;
} else {
$("#navTabs li").removeClass("active");
$("#client0").removeClass("active");
// add new tab and related content
$('ul#navTabs li:last-child').after('<li class="active" id="li' + (tab_id) + '">Client ' + (tab_id) + ' <button type="button" class="btn btn-warning btn-xs" onclick="removeTab(' + (tab_id) + ');"><i class="fa fa-remove"></i></button>');
loadClientData(tab_id);
//$('div#tabContent div:last-child').after('<div class="tab-pane" id="client' + (tab_id) + '"><p>Content tab ' + (tab_id) + '</p></div>');
// set the newly added tab as current
$("#client"+tab_id).addClass('active').show();
}
}
function loadClientData(tab_id) {
$("#tabContent").empty();
$.ajax({
type: "GET",
url: "clienten_data_load.php?id='+tab_id",
success: function(data) {
//empty(data);
$("#tabContent").text(data);
}
});
}
});
From here it goes wrong and I do not know how to solve this.
If I go back to the first TAB after first created dynamic tab, then this contains same data as the dynamically created tab.
What am I trying to do:
First tab: Provides an overview of all clients with a number of client data.
Dynamic tabs: There will be a maximum of 10 tabs. Each double click creates a dynamic tab to maximum of 10. The contents of the tab have to be all other client data associated with the corresponding ID.
How can I make sure that an additional tab is created with each double click without replacing the contents of other tabs?
Hope I explained it clearly.

Your PHP should be returning an array (JSON) of rows with sub-arrays as the row content, NOT HTML. So build your return as an array then return using json_encode. Next you'd need to run through the array in your AJAX success method and simply fill in the content. I am on my phone, so I cannot provide an example as of right now, I will update this later if it is still needed. For now, concept should work.

Related

Getting data of a row to a modal with two parameters with codeigniter 3

My team and I are making a project wherein we need to pass on variables to a modal. How do I pass the data to the modal using loan id as parameter from the table row that I selected?
example:
loan id
name
view
0964
charles
button
0562
ultor
button
when you press the button of that particular row, a modal will show up wherein the details of that row will be loaded.
In addition, the modal will also have information that would be needed, but is from a different database table, but the parameter is name instead of loan id
Is there a way to do that? I don't have a lot of experience in jquery and ajax, but i read that it might be a solution to my problem.
here is my table view that shows the button and the row information.
<?php foreach($open_applications as $row): ?>
<tr>
<td><?php echo $row->col_full_name; ?></strong><td>
<td><?php echo $row->col_loan_assignid; ?></td>
<td>
<button class="btn btn-secondary btn-xs" data-bs-toggle="modal" data-bs-target="#loanDecision">Pending</button>
<a href="<?php echo site_url('Users/borrowerdetails')?>" role="button" class="btn btn-link btn-xs">View</button>
</td>
</tr>
Here is my modal where it would need to show information that are in the row and information from a different table
<div class="modal fade" id="loanDecision" tabindex="-1" aria-labelledby="loanDecisionLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content">
<div class="modal-header border-0">
<h5 class="modal-title" id="loanDecisionLabel">This would be where the name is from the row</h5><br>
</div>
<div class="modal-header">
<h5 class="modal-title" id="loanDecisionSubtitle">this would be where the person's job is from the row</h5>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-hover table-bordered">
<thead class="thead">
<tr>
<th scope="col">title of the column from a different table</th>
<th scope="col">title of the column from a different table</th>
<th scope="col">title of the column from a different table</th>
</tr>
</thead>
<tbody>
<tr>
<td>data from the column from the different table</td>
<td>data from the column from the different table</td>
<td>data from the column from the different table</td>
<td>data from the column from the different table</td>
<td>data from the column from the different table</td>
<td>data from the column from the different table</td>
<td>data from the column from the different table</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
I have created a controller and a model, but I don't know how to connect them to the modal, but here is my controller and model:
public function fetchDetails($col_loan_assignid, $col_borrower_id)
{
$data['getloandetails'] = $this->Users_model->getingloandetails($col_loan_assignid);
$data['getactiondetails'] = $this->Users_model->getingactiondetails($col_borrower_id);
}
public function getingloandetails($col_loan_assignid){
$sql = "select * from $this->tbl_loan_application where col_loan_assignid like '%$col_loan_assignid%'";
$query = $this->db->query($sql);
return $query->result();
}
public function getactiondetails($col_borrower_id){
$sql = "select * from $this->tbl_action where col_loan_assignid like '%$col_borrower_id%'";
$query = $this->db->query($sql);
return $query->result();
}
Step 1 : set unique id to data attributes in view button.
Example data-loanid='".$row->loanid."'
Step 2 : add a common class to view button and add event-listner to it.
Example view-btn
Step 3 : after adding event listener get data attributes from its. So you can able to access unique.
$(".view-btn").click(function(){
let loan_id=$(this).data('loanid');
console.log(loan_id);
});
Step 4 : after getting unique id so can able send a request via ajax or fetch api.
Step 5: on ci3 create a route and validate data in controller and pass data to model and fetch data from database and return response.
Fetch api Example
let ApiRequest = async function(Url,param) {
try {
const url = Url;
const options = {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: param,
//body:field1=Value1&field2=value2
}
const response = await fetch(url, options);
// response as json
return await response.json();
} catch (error) {
console.error('Error:', error);
return false;
}
}
let url="http://www.example.com/api/getdata";
let parameter=field1=Value1&field2=value2;
let Result=ApiRequest(url,parameter);
console.log(Result);

Can't show the user's detail data in html (but can show the array with print_r()) "codeigniter"

I want to show the user detail modal when I click the detail button next to every that users name, but the problem is I can't display the "user_detail" data that I got from controller, it make me so confusing because when I display from controller using print_r() it show perfectly the data array that I want. Now I just want to display it as html like I display all user in the first place.
Here is my full code, I think we should just focus on the get_detail() method in the controller.
model/test_model.php:
function get_user()
{
$query = $this->db->query("SELECT * FROM tb_users ");
$result = $query->result_array();
return $result;
}
function get_detail($user_id)
{
$query = $this->db->query("SELECT * FROM tb_users where user_id = '".$user_id."'");
$result = $query->result_array();
return $result;
}
Controller/Welcome.php:
public function index()
{
$data["datakcp"] = $this->test_model->get_user();
$this->load->view('welcome_message',$data); // do this by loading a "view" that formats the data we gather here
}
public function get_user($user_id = null)
{
// get the user_id from the ajax request
// this means if $user_id is set (not null) then make $user_id = $user_id. Otherwise, make $user_id = posted input
$user_id = ($user_id) ? $retailer_id : $this->input->post('user_id');
$datadetail= $this->test_model->get_detail($user_id);
echo json_encode($datadetail);
}
Views/my_view.php:
<div class="container" style="width:700px;">
<h3 align="center"> </h3>
<br>
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="70%">Employee Name</th>
<th width="30%">View</th>
</tr>
<?php foreach($datakcp as $user){ ?>
<tr>
<td><?php echo $user["user_name"] ?></td>
<td><input type="button" name="detail" value="detail" id="<?php echo $user["user_id"] ?>" class="btn btn-info btn-xs view_dawta"></td>
</tr>
<?php } ?>
</table>
</div>
</div>
<div id="dataModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" id="employee_detail">
<table>
<thead>
<th>Username<th>
<th>Campaign</th>
</thead>
<tbody id="userDetail">
</tbody>
</table>
</div>
</div>
</div>
My jQuery ajax script:
<script>
$(document).ready(function(){
$('.view_dawta').click(function(){
var user_id= $(this).attr("id");
$.ajax({
url:"index.php/Welcome/get_user",
method:"post",
data:{user_id:user_id},
success:function(data){
console.log(data)
$.each((JSON.parse(data)), function(key, value){
$('#userDetail').append(
'<tr>'+
'<td>'+value.user_name+'</td>'+
'<td>'+value.campaign_name+'</td>'+
'</tr>'
);
});
$('#dataModal').modal("show");
}
});
});
});
</script>
get_user function is not returning anything. (Note: when you try your print_r or var_dump statement, the output of print_r or var_dump statement is returned, and otherwise nothing is being returned).
Put echo json_encode($datadetail); at the end in get_user function and receive json data in response. You will then have to use and format that json data in your ajax success function.
Alternatively, you can return formatted html from get_user function, in which case your $('#employee_detail').html(data); should work as it is.
EDIT:
1- Here is a basic ajax call you should use to receive json data:
$.ajax({
url:"index.php/Welcome/get_user",
method:"post",
contentType: "application/json;",
dataType: "json",
data:{user_id:user_id},
success:function(data){
$('#employee_detail').html(data);
$('#dataModal').modal("show");
}
});
2- And in your get_user function, put echo json_encode($datadetail); at the end. At this point, you should be able to see json data in your modal.
3- In get_user function, replace $datadetail["userdetail"] with $datadetail. And at the end of the function, echo json_encode($datadetail);.
4- In my_view.php, construct a table inside <div class="modal-body" id="employee_detail"> like below (this is just one way, you can decide a different approach if you wish):
<table>
<thead>
<th>Username</th>
<th>Campaign</th>
<!-- include more <th> tags for other user data -->
</thead>
<tbody id="userDetail">
</tbody>
</table>
5- In ajax call, your success function can be:
success:function(data){
$.each(data, function(key, value){
$('#userDetail').append(
'<tr>'+
'<td>'+value.user_name+'</td>'+
'<td>'+value.campaign_name+'</td>'+
/* include more <td> tags for other user data */
'</tr>'
);
});
$('#dataModal').modal("show");
}
6- This should be enough to give you a complete idea of how to receive and handle json data and also format it into html. This should be able to get you started. You can work on other formatting details etc. now.
On a related note, you have duplicate user_id in your returned data. Do check that.
Hope this helps.

Is there any code in angular for tabs which doesn't load data in browse initially but loads it only when we click it

this is what it shows on clicking tab one time 2nd time I click it loads last two file .15 and .17 again alltogetherthis is shown in console when I inspect even if I have not clicked on tab.And displays this data in browser when I click tab. This should not be shown whn console is clicked while inspectin page. Data only to be loaded only when I click tab.
Object {type: "FeatureCollection", metadata: Object, features:Array[11], bbox: Array[6]}bbox: Array[6]features: Array[11]metadata: Objecttype: "FeatureCollection"proto: Object
here is my code..
<body ng-controller="CountryCtrl">
<div ng-app ng-init="tab=1">
<div class="cb" ng-click="tab = 1">tab 1</div>
<div class="cb" ng-click="tab = 2">tab 2</div>
<div ng-show="tab == 1">
<p>hellloollllllllllllo</p>
</div>
<div ng-show="tab == 2">
<h2>Angular.js JSON Fetching Example</h2>
<table border=1>
<tr>
<th>type</th>
<th>properties_mag</th>
<th>properties_place</th>
<th>properties_time</th>
<th>properties_upated</th>
<th>properties_tz</th>
</tr>
<tr ng-repeat="type in country ">
<td>{{type.type}}</td>
<td>{{type.properties.mag}} </td>
<td> {{type.properties.place}} </td>
<td> {{type.properties.time}} </td>
<td> {{type.properties.updated}} </td>
<td> {{type.properties.tz}} </td>
<tr ng-repeat="cor in features.geometry.coordinates ">
<td> {{cor}} </td>
</tr>
</table>
</div>
this is controller function.....
var countryApp = angular.module('countryApp',[]);
countryApp.controller('CountryCtrl', function ($scope, $http){
$http.get('http:/4.5_day.geojson').success(function(data) {
console.log(data);
$scope.country = data.features;
$scope.coor=data.features.geometry.coordinates;
console.log($scope.country);
});
});
I would suggest that you simply call the function that loads the JSON data when clicking the second tab using ng-click. This way you will not get it loaded unless the tab is clicked.
You could change:
<div class="cb" ng-click="tab = 2">tab 2</div>
To:
<div class="cb" ng-click="switchTabAndLoadData()">tab 2</div>
And defined the function in your controller to update the tab variable and load the JSON.
You are calling the $http service directly in your controller that's why the data is loaded up front. Try this:
var countryApp = angular.module('countryApp',[]);
countryApp.controller('CountryCtrl', function ($scope, $http){
var loadData = function(){
$http.get('http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson').success(function(data) {
console.log(data);
$scope.country = data.features;
$scope.coor=data.features.geometry.coordinates;
console.log($scope.country);
});
}
$scope.switchTabAndLoadData = function(){
$scope.tab=2;
if(angular.isUndefined($scope.country) || angular.isUndefined($scope.coor)){
loadData();
}
}
});
Make sure to also apply the HTML change I previously suggested and it should be fine.
You problem lies elsewhere, had you checked the console you would have seen that angular gives an error on your assignment of variables for $scope.coor since you are trying to assign properies of an object in an array of object.
Check this pen for a solution: http://codepen.io/anon/pen/BjXGGJ
You can then adjust the HTML do your needs.

Angularjs:Need help on two way binding(bipolar binding)

When a value change in the back-end(in my case Mysql,Patient details) With any other user(other console) ,i want to update that values on another page at same time(Without refreshing the page) .how it is possible. my code is given below.
myscript.js
var ajaxApp=angular.module('ajaxApp',[]);
ajaxApp.controller('ajaxController',function ajaxController($scope,$http){
$http.get('core/getdata.php').success(function(data){
$scope.patient=data;
});
});
my php page
<tr ng-animate="'animate'" ng-repeat="p in patient|filter:pnametext|limitTo:10">
<td><div class="btn btn-info">{{p.opNo}}</div></td>
<td><b>{{p.pName | uppercase}}</b></td>
<td>
<div ng-switch on="p.pCatId">
<div ng-switch-when="1">
ONE
</div>
<div ng-switch-when="2">
TWO
</div>
<div ng-switch-when="3">
THREE
</div>
</div>
</td>
<td>{{p.pAge}}</td>
<td>{{p.pHusFather}}</td>
<td>{{p.phNumber}}</td>
<td><button class="btn btn-danger">Add to Queue</button></td>
</tr>
suggest use socket.io(web socket) group people editing the same content in same chanel, broadcast modification to others, and notify other people and apply change. ajax is not real time and costs more
http://socket.io/
socket.connect(xx);
socket.on('change', function(data) {
alert('change happen!');
$scope.data = data;
$scope.$apply();
})
$scope.$watch('data', function() {
if (change) {
socket.emit('change', $scope.data);
}
})

can not reload div tag using jquery ajax that contains some Php code

I have table in which data comes from the database.and I have the form on the same page which insert the data in the table.but when I insert data using $.ajax , it inserts record in database , but after reloading table in same function is not working, means it doesn't reload the table.
below is my code.
HTML
<div class="col-lg-8" id="value_table">
<div class="panel-body">
<div class="table-responsive">
<?php
$q=$db->query('select attr_val_id,attr_val,sortorder,status from db_attribute_value where attr_id="'.$attr_id.'"' );
?>
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Edit/Delete</th>
</tr>
</thead>
<tbody>
<?php $c=1; while($r=$q->fetch_assoc()){?>
<tr class=" gradeX">
<td><?php echo $c; ?></td>
<td><?php echo $r['attr_val']; ?></td>
<td><a href="add_attribute_val.php?id=<?php echo $r['attr_val_id']; ?>&attr_id=<?php echo #$r['attr_id']; ?>">
<button type="button" class="btn btn-default btn-circle"><i class="fa fa-pencil-square-o"></i></button>
</a>
<button type="button" class="btn btn-danger btn-default btn-circle" id="<?php echo $r['attr_val_id']; ?>" name="deleteRecord"><i class="fa fa-times"></i></button></td>
</tr>
<?php $c++;}?>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
</div>
JQuery
$('#attr_val_form').submit(function(event) {
//$('.form-group').removeClass('has-error'); // remove the error class
//$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'attr_val' : $('input[name=attr_val]').val(),
'attr_id' : $('input[name=attr_id]').val(),
'sortorder' : $('input[name=sortorder]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'admin_operation.php?mode=add_attr_value', // the url where we want to POST
data : formData, // our data object
cache: false,
success: function(data)
{
if($.trim(data)== 'yes')
{
$("#value_table").html($("#value_table").html());
$("#notice")
.show()
.html('<div class="alert alert-success"<strong>Successfully !</strong> record added.</div>')
.fadeOut(3000);
}
else
{
$("#notice")
.show()
.html('<div class="alert alert-danger"<strong>Error !</strong>Record already exist.</div>')
.fadeOut(10000);
}
}
})
// using the done promise callback
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
I guess what you think this line should do is get the data from the response and substitute the same tag in your DOM:
$("#value_table").html($("#value_table").html());
You should use something like that instead:
$("#value_table").html($.parseHTML(data).find("#value_table").html());
This code has not been tested, but the main idea is to parse the data parameter and the find the #value_table element.
More info here: http://api.jquery.com/jquery.parsehtml/
As you say it seems like 'admin_operation.php?mode=add_attr_value' not success, try to call to always function instead success (for debugging it).
if the always function called successfully you have to return true from admin_operation.php
if not you have a problem on admin_operation.php after the insertion.

Categories