Display AJAX success response in Table - php

How to display the value in table..I am not able to display the value.In ajax i've sent all the value and after retrieving the records from database. I've to display the result in table
Output is
[{"ID":"15","patient_name":"Sangeeta","patient_email":"sangeetha#gmail.com","gender":"Female","age":"26","address":"Jayanagar","city":"Bangalore","laboratory_name":"Anand","laboratory_address":"bsk","laboratory_place":"bengaluru","referral_pat_id":"18","active":"1","created_on":"2017-06-13"}]
How to retrieve each value
AJAX Script
$(document).ready(function(){
$('#myModal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
alert(rowid);
console.log(rowid);
$.ajax({
type : 'post',
url : 'url', //Here you will fetch records
data : 'id='+ rowid, //Pass $id
success : function(resp){
alert(resp);
var trHTML = '';
$.each(resp, function (i, userData) {
for (i = 0; i < resp.UserData.length; i++) {
alert(trHTML);
trHTML +=
'<tr><td>'
+ resp.userData[i].ID
+ '</td><td>'
+ resp.userData[i].patient_name
+ '</td><td>'
+ resp.userData[i].patient_email
+ '</td></tr>';
}
});
$('#tBody').append(trHTML);
}
});
});
});
Controller
public function fetch_records()
{
print_r($_POST);
$this->load->model('Physician_confirm_m');
$id = $_POST['id']; //escape string
print_r($id);
$result=$this->Physician_confirm_m->fetch_history_records($id);
echo json_encode($result);
}
Model
public function fetch_history_records($id)
{
$this->db->where('referral_pat_id',$id);
$this->db->from('referral_confirmation_details');
$q = $this->db->get();
return $q->result();
}
HTML
<button type="button" class="btn btn-info disablebtn" style="text-align: center;" data-toggle="modal" data-target="#myModal" data-id="<?php echo $post->referral_patient_id;?>"><i class="fa fa-history" aria-hidden="true"></i><strong> HISTORY</strong></button>
<div class="modal-body">
<table>
<tbody id="tBody"></tbody>
</table>
</div>
</div>

You can do in another way to achieve this.
$(document).ready(function(){
$('#myModal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
console.log(rowid);
$.ajax({
type : 'post',
url : 'url', //Here you will fetch records
data : 'id='+ rowid, //Pass $id
success : function(resp){
var obj = jQuery.parseJSON(resp);
$('#tBody').append(obj.ajaxPage);
}
});
});
});
In Your Controller should be like
public function fetch_records()
{
$this->load->model('Physician_confirm_m');
$id = $_POST['id']; //escape string
$data['result']=$this->Physician_confirm_m->fetch_history_records($id);
$result['ajaxPage'] = $this->load->view('pages/result_table', $data, true);
echo json_encode($result);
}
result_table view page should be
<?php if($result){ foreach($result as $row){ ?>
<tr>
<td><?=$row['ID']?></td>
<td><?=$row['patient_name'];?></td>
<td><?=$row['patient_email'];?></td>;
</tr>
<?php
}
}?>

Related

Update and Display value without refreshing the page

I want to change the status (Active/Deactive) of records in database without actually submitting(refreshing page) data, using jquery.
In my script Status is getting changed in database but as it is not refreshing, display status is not updating. is there a way to display the changed status without refreshing? i mean as soon as it updates in database, it should reflect in the status.
Here is my script
<table class="table table-bordered table-condensed table-striped mb-6">
<thead>
<tr>
<th>Firstname</th>
<th>Mobile</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
//$CQuery = ""; my query
while($ConRow = DB_fetch_array($CQuery ))
{
?>
<tr>
<td><?php echo $ConRow['fname']; ?></td>
<td><?php echo $ConRow['mobile']; ?></td>
<?php if($ConRow['status']=='A') { ?>
<td><button id="<?php echo $ConRow['con_id']; ?>" class="delbutton btn btn-danger btn-sm">De-Activate</button> </td>
<?php } else if($ConRow['status']=='D') { ?>
<td><button id="<?php echo $ConRow['con_id']; ?>" class="delbutton btn btn-success btn-sm">Activate</button> </td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
Script
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var data1 = 'id=' + del_id;
if (confirm("Sure you want to De-Activate this?.")) {
$.ajax({
type : "POST",
url : "DisableContact.php",
data : data1,
success : function() {
}
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
</script>
PHP
$id = $_POST['id'];
$sel1 = "SELECT status FROM contacts WHERE con_id=".$id."";
$Sel = DB_query($sel1);
$srow = DB_fetch_array($Sel);
if($srow['status']=='A')
{
$sql = "UPDATE contacts SET status='D' WHERE con_id=".$id;
}
else
if($srow['status']=='D')
{
$sql = "UPDATE contacts SET status='A' WHERE con_id=".$id;
}
$result = DB_query($sql);
In database , Status is getting changed, but in table it is not showing up.
//Updated
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to De-Activate this?.")) {
$.ajax({
type : "POST",
url : "DisableContact.php", //URL to the delete php script
data : info,
success: function(data) {
var d = $.trim(data); //triming value if there is any whitespaces
if (d == "A") {
//means data is activate so show that button
$("#"+del_id+ ".btn-success").show();
//hiding other
$("#"+del_id +".btn-danger").hide();
} else {
//show deactivate buttton
$("#"+del_id +".btn-danger").show();
//hide other button
$("#"+del_id +".btn-success").hide();
}
}
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
</script>
PHP
if($srow['status']=='A')
{
$sql = "UPDATE cust_contacts SET status='D' WHERE con_id=".$id;
echo 'A';
}
else
if($srow['status']=='D')
{
$sql = "UPDATE cust_contacts SET status='A' WHERE con_id=".$id;
echo 'D';
}
$result = DB_query($sql);
You can pass some value from php to ajax call and depending on that the required button will get displayed .So your php code will look like below :
..
if($srow['status']=='A')
{
$sql = "UPDATE contacts SET status='D' WHERE con_id=".$id;
echo "D";//will get passed as response to ajax
}
else
if($srow['status']=='D')
{
$sql = "UPDATE contacts SET status='A' WHERE con_id=".$id;
echo "A";//will get passed to ajax as response
}
Your ajax success function will look like below :
..
success: function(data) {
var d = $.trim(data); //triming value if there is any whitespaces
if (d == "A") {
//means data is activate so show that button
$("#"+del_id+ ".btn-success").show();
//hiding other
$("#"+del_id +".btn-danger").hide();
} else {
//show deactivate buttton
$("#"+del_id +".btn-danger").show();
//hide other button
$("#"+del_id +".btn-success").hide();
}
}
Update 1:
As you have use if-else to show button so i forgot here that other button will not exist in this case thats the reason jquery is not able to find other button and display blank.Now, to solve this you need to make some changes in your php code where you are displaying your table.Changes you need to make are as follows :
Change this :
<?php if($ConRow['status']=='A') { ?>
<td><button id="<?php echo $ConRow['con_id']; ?>" class="delbutton btn btn-danger btn-sm">De-Activate</button> </td>
<?php } else if($ConRow['status']=='D') { ?>
<td><button id="<?php echo $ConRow['con_id']; ?>" class="delbutton btn btn-success btn-sm">Activate</button> </td>
<?php } ?>
to below :
<td> <div class="<?php echo $ConRow['con_id']; ?>"> <?php if($ConRow['status']=='A') { ?>
<button id="<?php echo $ConRow['con_id']; ?>" class="delbutton btn btn-danger btn-sm">De-Activate</button>
<?php } else if($ConRow['status']=='D') { ?>
<button id="<?php echo $ConRow['con_id']; ?>" class="delbutton btn btn-success btn-sm">Activate</button>
<?php } ?> </div> </td>
Now ,in ajax success function we will use .html to add button inside <div></div> .So ajax will look like below :
if (d == "A") {
$("." + del_id).html('<button id="' + del_id + '" class="delbutton btn btn-danger btn-sm">De-Activate</button>');
} else {
$("." + del_id).html(' <button id="' + del_id + '" class="delbutton btn btn-success btn-sm">Activate</button> ');
}

Ajax not loading posts on live server but working on localhost

I'm trying to load posts of users from my database to the website but the ajax part isn't loading for some reason. It was working on localhost but not working on the live server. Is there some problem in the ajax code or the code written in the index page?
Here in the index page the posts_area div part isn't loading
index.php
<?php
include("includes/header.php");
if(isset($_POST['post'])){
$post = new Post($con, $userLoggedIn);
$post->submitPost($_POST['post_text'], 'none');
}
?>
<div class="main_column column">
<form class="post_form" action="index.php" method="POST">
<textarea name="post_text" id="post_text" placeholder="Got something to say?"></textarea>
<input type="submit" name="post" id="post_button" value="Post">
<hr>
</form>
<div class="posts_area"></div>
<img id="loading" src="assets/images/icons/loading.gif">
</div>
<div class="user_details column">
<h4>Popular</h4>
<div class="trends">
<?php
$query = mysqli_query($con, "SELECT * FROM trends ORDER BY hits DESC LIMIT 9");
foreach ($query as $row) {
$word = $row['title'];
$word_dot = strlen($word) >= 14 ? "..." : "";
$trimmed_word = str_split($word, 14);
$trimmed_word = $trimmed_word[0];
echo "<div style'padding: 1px'>";
echo $trimmed_word . $word_dot;
echo "<br></div><br>";
}
?>
</div>
</div>
<script>
var userLoggedIn = '<?php echo $userLoggedIn; ?>';
$(document).ready(function() {
$('#loading').show();
//Original ajax request for loading first posts
$.ajax({
url: "https://bestconnect.000webhostapp.com/includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(data) {
$('#loading').hide();
$('.posts_area').html(data);
}
});
$(window).scroll(function() {
var height = $('.posts_area').height(); //Div containing posts
var scroll_top = $(this).scrollTop();
var page = $('.posts_area').find('.nextPage').val();
var noMorePosts = $('.posts_area').find('.noMorePosts').val();
if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') {
$('#loading').show();
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=" + page + "&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(response) {
$('.posts_area').find('.nextPage').remove(); //Removes current .nextpage
$('.posts_area').find('.noMorePosts').remove(); //Removes current .nextpage
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //End if
return false;
}); //End (window).scroll(function())
});
</script>
</div>
ajax_load_posts.php
<?php
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit = 10; //Number of posts to be loaded per call
if (isset($_GET['posts'])) {
$posts = new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST, $limit);
}
?>
<?php
header("Access-Control-Allow-Origin: *");
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit = 10; //Number of posts to be loaded per call
if (isset($_GET['userLoggedIn']))
{
$posts = new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST, $limit);
}
?>

Ajax Search Table Not Working / Cannot Fetch Data - Codeigniter

I cannot simply fetch any data on my table, I tried to clean my code but still not working here is my code
Controller - I am not sure if this is correct or am i still missing something
function fetch()
{
$data = $this->level_model->fetch_data();
echo $this->load->view('levels', ['data' => $data], TRUE );
}
View
<select class='form-input input-lg col-md-6' name="search_text" id="search_text">
<?php
foreach ($courses as $row) {
echo '<option value="'.$row->course.'">'.$row->course.'</option>';
}
?>
</select>
Table
<table class="table table-striped table-bordered" style="width:100%;">
<thead>
<tr>
<th scope="col">Course</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody id="showdata">
</tbody>
</table>
Model - so here where I query so i can match the data and fetch it.
function fetch_data($query)
{
$this->db->select("*");
$this->db->from("levels");
if($query != '')
{
$this->db->like('course_year', $query);
}
$this->db->order_by('id', 'ASC');
return $this->db->get();
}
AJAX / JAVASCRIPT I am not quite sure if my ajax is right please kindy check
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"<?php echo base_url(); ?>levels/fetch",
method:"POST",
data:{query:query},
success:function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+data[i].course_year+'</td>'+
'<td>'+
'<a class="btn btn-primary item-edit" data="'+data[i].id+'"" href="javascript:;"><i class="fa fa-edit"></i> Edit </a> | '+
'<a class="btn btn-danger item-delete" data="'+data[i].id+'"" href="javascript:;"><i class="fa fa-remove"></i> Delete</a></td>'+
'</tr>';
}
$('#showdata').html(html);
}
})
}
$('#search_text').change(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
Try changing your controller fetch method as below:
function fetch()
{
$data = $this->level_model->fetch_data(
$this->input->post('query');
);
echo $this->load->view('levels', ['data' => $data], TRUE );
}
When the document is loading you are calling the load_data function without passing value to the query parameter here.
<script>
$(document).ready(function(){
load_data();
You should give it a default value here like this
<script>
$(document).ready(function(){
load_data();
function load_data(query='')
{
$.ajax({
url:"<?php echo base_url(); ?>levels/fetch",
method:"POST",
data:{query:query},
success:function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+data[i].course_year+'</td>'+
'<td>'+
'<a class="btn btn-primary item-edit" data="'+data[i].id+'"" href="javascript:;"><i class="fa fa-edit"></i> Edit </a> | '+
'<a class="btn btn-danger item-delete" data="'+data[i].id+'"" href="javascript:;"><i class="fa fa-remove"></i> Delete</a></td>'+
'</tr>';
}
$('#showdata').html(html);
}
})
}
$('#search_text').change(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
Also you are not passing any data to your model .
function fetch()
{
$data = $this->level_model->fetch_data(
$_POST['query'];
);
echo $this->load->view('levels', ['data' => $data], TRUE );
}

Pass user_id from mysql to bootstrap modal via ajax

I want to pass user id from my table to modal via ajax but only think i get is "undefined".
When i replace var dataString = 'id=' + recipient;
with var dataString = 'id=' + 1; it working fine so for some reason i cant get value on click to variable. What i'm missing??
PHP:
<?php
$query = mysql_query("select * from users");
$i=0;
while($fetch = mysql_fetch_array($query)):
echo '<tr>';
echo'<td> '.$fetch['user_id'].'</td>';
echo'<td> '.$fetch['user_name'].'</td>';
echo'<td> '.$fetch['user_email'].'</td>';
echo'<td> '.$fetch['user_imie'].'</td>';
echo'<td> '.$fetch['user_nazwisko'].'</td>';
echo'<td> '.$fetch['user_telefon'].'</td>';
echo'<td> '.$fetch['user_konto_akty'].'</td>';
echo'<td> '.$fetch['user_uprawnienia'].'</td>';
echo'<td>' .date("d.m.Y, H:i", $fetch['user_regdate']). '</td>';
echo'<td> <a class="btn btn-primary btn-sm" href="Kasuj_tab.php?user_id='.$fetch['user_id'].'">UsuĊ„</a></td>';
?>
<td>
<a class="btn btn-small btn-primary" data-toggle="modal" data-target="#exampleModal_user" data-whatever1="<?php echo $fetch['user_id']; ?>">Edit</a></td>
<?php
echo '</tr>';
endwhile;
?>
Ajax:
$('#exampleModal_user').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever1') // Extract info from data-* attributes
var modal = $(this);
var dataString = 'id=' + recipient;
$.ajax({
type: "GET",
url: "Modal_user.php",
data: dataString,
cache: false,
success: function (data) {
console.log(data);
modal.find('.ct').html(data);
},
error: function(err) {
console.log(err);
}
});
})
PHP:
<?php
include 'Panel_Logowanie/config.php';
db_connect();
$id = $_GET['id'];
echo"$id";
?>

Loop through multiple textboxes Code igniter php

I have a form in my view page where there have two select boxes and three input boxes in a row .I put them in a for loop and make five rows in which every row there is two select box and 3 simple text boxes .I write a function in jquery where if i select value from one select box it will appear in 2nd select box .But after making five rows in a loop ,this function is working only in the first row not other four rows . I don't know how to do that .If any one can code it for me,then thanks to him ...
This is my view page
<tr>
<th>Category:</th>
<th>Items:</th>
<th>Selling Price:</th>
<th>quantity:</th>
<th> total:</th>
</tr>
<?php for ($i = 0; $i < 5; $i++) {
?>
<tr>
<td>
<?php echo form_dropdown('cat_id', $records2, '#', 'id="category"');?>
</td>
<td>
<?php echo form_dropdown('item_id', $records3, '#', 'id="items"'); ?>
</td>
<td><?php echo form_input($price); ?> </td>
<td><?php echo form_input($quantity); ?></td>
<td> <?php echo form_input($total); ?>
</td></tr>
<?php }?></table>
My JavaScript for two select boxes.
$(document).ready(function(){
$('#check').click(function(){
alert("hello");
return false;
});
$('#category').change(function(){
$("#items > option").remove();
var category_id = $('#category').val();
$.ajax({
type: "POST",
url: "stockInController/get_Items/"+category_id,
success: function(items) //we're calling the response json array 'cities'
{
$.each(items,function(item_id,item_name)
{
var opt = $('<option />');
opt.val(item_id);
opt.text(item_name);
$('#items').append(opt);
});
}
});
});
});
JavaScript for sending values to the controller
<script type="text/javascript">
$('#btn').click(function() { // $("#form").serialize()
var cust_id = $('#cust_id').val();
var item_id = $('#items').val();
var sales_date = $('#sales_date').val();
var sales_bill_no = $('#sales_bill_no').val();
var price = $('#price').val();
var quantity = $('#quantity').val();
var form_data = {
cust_id: $('#cust_id').val(),
sales_date: $('#sales_date').val(),
sales_bill_no: $('#sales_bill_no').val(),
price: $('#price').val(),
quantity: $('#quantity').val(),
item_id: $('#items').val(),
};
$.ajax({
url: "<?php echo site_url('salesController/addSales'); ?>",
type: 'POST',
data: form_data,
dataType: 'json',
success: function(msg) {
if(msg.res == 1)
{
$(".success").fadeIn(500).delay(2000).fadeOut(500);
alert("true");
}
else{
alert("false");
}
}
});
return false;
});
</script>
i have done this but this not working
<?php echo form_dropdown('cat_id', $records2, '#', "id='category_".$i."'");?>
<?php echo form_dropdown('item_id', $records3, '#', "id='items_".$i."'"); ?>
<script type="text/javascript">// <![CDATA[
$(document).ready(function()
{
for (var i= 0; i<5; i++)
{
$('#category_'+ i).change(function(){
$('#items_'+ i > option").remove();
var category_id = $('#category_'+ i).val();
$.ajax({
type: "POST",
url: "stockInController/get_Items/"+category_id,
success: function(items)
{
$.each(items,function(item_id,item_name)
{
var opt = $('<option />');
opt.val(item_id);
opt.text(item_name);
$('#items_'+ i).append(opt);
});
}
});
});
}
});
I think the problem here is that in each row you have to inputs that have ID's "category" and "items". Each element on the page should have a unique ID. Maybe for row 1 they are "cat_1" and "item_1" or something similar.
Right now it is kind of like you have a room with 10 people, 5 named Johnny and 5 named Sarah. If you walk in and ask for Johnny, you will have a problem.
<?php for ($i = 0; $i < 5; $i++) {
?>
<tr>
<td>
<?php echo form_dropdown('cat_id', $records2, '#', "id='category".$i."'");?>
</td>
<?php echo form_dropdown('item_id', $records3, '#', "id='items".$i."'"); ?>
</td>
Similarly,run a loop in your javascript and get the values of categories and items
EDIT:
for(i=0;i < 5; i++){
$("#category"+i).change(function(){
$("#items"+i+" > option").remove();
var category_id = $("#category"+i).val();
$.ajax({
type: "POST",
url: "stockInController/get_Items/"+category_id,
success: function(items) //we're calling the response json array 'cities'
{
$.each(items,function(item_id,item_name)
{
var opt = $('<option />');
opt.val(item_id);
opt.text(item_name);
$("#items"+i).append(opt);
});
}
});
}

Categories