I am trying to fetch data from the database using ajax call, but my function in jquery is not working for fetching the data and I am getting an error "data is not defined". I don't know what goes wrong. I am trying to fetch all data from the database table and display it on the screen Here is my controller
<?php
namespace App\Http\Controllers;
use Haruncpi\LaravelIdGenerator\IdGenerator;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use Illuminate\Support\Facades\DB;
use App\User;
use App\Models\patient;
use Illuminate\Support\Facades\Validator;
class SearchPatient extends Controller
{
function action(Request $request)
{
if ($request->ajax())
{
$query= $request->get('query');
if ($query != '')
{
$data = DB::table('patients')->first()
->where('patientid','like','%'.$query.'%' )
->orWhere('fname','like','%'.$query.'%')
->orWhere('lname','like','%'.$query.'%')
->orWhere('contactno','like','%'.$query.'%')
->orWhere('gender','like','%'.$query.'%')
->orWhere('cnic','like','%'.$query.'%')
->orWhere('city','like','%'.$query.'%')
->orWhere('address','like','%'.$query.'%')
->get();
}
else
{
$data = DB::table('patients')->first()
->orderBy('created_at', 'desc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>
'.$row->patientid.'
</td>
<td>
'.$row->fname.'
</td>
<td>
'.$row->lname.'
</td>
<td>
'.$row->cnic.'
</td>
<td>
'.$row->gender.'
</td>
<td>
'.$row->address.'
</td>
<td>
'.$row->contactno.'
</td>
<td>
'.$row->city.'
</td>
<td>
'.$row->created_at.'
</td>
</tr>
';
}
}
else
{
$output='
<tr>
<td align="center" colspan="5">
No Data Found
</td>
</tr>';
}
$data = array(
'table_data' => $output,
'table_data' => $table_data
);
echo json_encode($data);
}
}
}
Here is my ajax function
$(document).ready(function() {
fetch_patients('');
function fetch_patients(query = '')
{
$.ajax({
URL:"/action",
method: 'GET',
data: {query:query},
dataType: 'json',
success: function(data)
{
$('tbody').html(data.table_data);
$('total-patient-records').text(data.total_data);
}
})
}
$(document).on('keyup', '#searchpatient', function(){
var query = $(this).val();
fetch_patients(query);
})
});
Here is my route
Route::get('/action', [SearchPatient::class, 'action'])->name('action');
Route:: get ('/SearchPatient',function(){
return view ('SearchPatient');
});
Here is my blade file
<div class="container box">
<h3 align="center">Search Patient</h3><BR>
<div class="panel panel-default">
<div class="panel-heading">
Search Patient Data
</div>
<div class="panel-body">
<input type="text" name="searchpatient" id="searchpatient" class="form-control" placeholder="Search Patient">
</div>
<div class="table-responsive">
<h3 align="center">Total Data : <span id="total-patient-records"></span></h3>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Patient ID</th>
<th>Name</th>
<th>CNIC</th>
<th>Gender</th>
<th>Address</th>
<th>Contact No</th>
<th>City</th>
<th>Last Visit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
You have error in your code, double key 'table_data' and undefined variable $table_data
//Jquery
var data = {
"_token": $('input[name=_token]').val(),
query:query
};
$.ajax({
URL:"/action",
method: 'GET',
data: data,
dataType: 'json',
success: function(data)
{
$('tbody').html(data.table_data);
$('total-patient-records').text(data.total_data);
}
})
//controller
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
return response()->json(['data' => $data]);
var url = '{{ route('get_products') }}';
var data = {
"_token": $('input[name=_token]').val(),
};
$.ajax({
type: "get",
url: url,
data: data,
success: function(response) {
alert(response.data);
}
});
<------ controller ------>
public function get_products()
{
$data = DB::table('products)->get();
return response()->json(['data' => $products]);
}
here is the issue in the document-ready method the data variable is used but Never initialize before using it.
The solution in to pass fetch_patients('') an empty string in your method, instead of data (an undefined variable)
Related
I am beginner on JSON. In my web application I am trying convert the table values into JSON and pass to another page using ajax call.
Below is my ajax query which I tried to convert the table values and pass to prescription.php page to save the records. There are two different separate java script variables which need to sent to the above page.
<script>
$(document).ready(function () {
$(document).on('click', '#submit', function () {
var getapt = $('#getapt').val();
var getpid = $('#getpid').val();
var ids={
'getapt': getapt,
'getpid': getpid,
}
var modess = $('#rows tr').map(function() {
let $tr = $(this);
return [{
"medname": $(this).find('.med_name').val(),
"morning": $(this).find('.morning').val(),
"noon": $(this).find('.noon').val(),
"night": $(this).find('.night').val(),
}]
console.log(modess);
});
var ids = JSON.stringify(ids);
var medical = JSON.stringify(modess);
$.ajax({
url: "adminquery/prescription.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:{
index1: medical,
index2: ids
},
dataType:'json',
cache: false,
contentType: false,
processData: false,
async: false,
//contentType: "application/json; charset=utf-8",
})
});
});
</script>
Here is my prescription.php page
<?php
session_start();
require_once "../auth/dbconnection.php";
// if (isset(json_decode($_POST["data"])) {
$medical = json_decode($_POST["data"]);
if($stmt = mysqli_prepare($conn,"INSERT INTO prescription (apt_id,user_id,p_id, med_records,date) VALUES (?, ?, ?, ?, ?)")){
$user_id = $_SESSION['user_id'];
mysqli_stmt_bind_param($stmt, "sssss", $user_id);
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($conn);
}
// }else{
// echo "now records";
// }
mysqli_stmt_close($stmt);
?>
Here is my HTML codes.
<form method="post" id="prescriptionn" enctype="multipart/form-data">
<div class="table-responsive">
<table class="table table-bordered mb-0" id="medical">
<thead>
<tr>
<th>Medicine Name</th>
<th>Morning</th>
<th>Noon</th>
<th>Night</th>
<th> <button type="button" name="add" id="add" class="btn btn-success btn-xs">
+ </button> </th>
</tr>
</thead>
<tbody id="rows">
</tbody>
</table>
<br><br>
<div align="center">
<input type="hidden" value="<?php echo $row['apt_id'] ?>" id="getapt"
name="getapt" class="btn btn-primary">
<input type="hidden" value="<?php echo $row['p_id'] ?>" id="getpid" name="getpid" class="btn btn-primary">
<input type="button" name="submit" id="submit" class="btn btn-primary" value="Enter Prescription">
</div>
</div>
</form>
But nothing happen when I submit the button. Please give me some suggestions to improve my code may highly appreciated.
Following Method show how to send HTML table data using jQuery Ajax and save in Database. Hope this will help.
function storeTblValuesSpecial(x)
{
var TableData = new Array();
$('#'+x+''+' tr').each(function(row, tr){
TableData[row]={
"columOne" :$(tr).find('td:eq(1)').text()
, "columTwo" : $(tr).find('td:eq(2)').text()
, "columThree" : $(tr).find('td:eq(3)').text()
}
});
TableData.shift(); // first row will be empty - so remove
return TableData;
}
function storeTblValuesAjax(y) {
var TableData;
TableData = JSON.stringify(storeTblValuesSpecial(y));
$.ajax({
type: "POST",
url: '../yourFile.php',
data: {
"pTableData" : TableData
},
success: function(msg){
alert('Success');
}
});
}
<table id="table1" class="table table-dark" border="1">
<thead>
<tr>
<th scope="col">columOne</th>
<th scope="col">columTwo</th>
<th scope="col">columThree</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<button type="button" class="btn-danger" id = "delete" onclick="storeTblValuesAjax('table1')" >Save Table</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
From PHP File once the Post Request Sent through Ajax Call
<?php
session_start();
// Unescape the string values in the JSON array
$tableData = stripcslashes($_POST['pTableData']);
// Decode the JSON array
$records = json_decode($tableData,TRUE);
$sizeOfArray = sizeof($records);
for($test = 1; $test < $sizeOfArray; $test++)
{
$columOne= str_replace(",","",$records[$test]['columOne']);
$columTwo= str_replace(",","",$records[$test]['columTwo']);
$columThree= str_replace(",","",$records[$test]['columThree']);
/* From Here a general SQL Insert query , pass $columOne , $columTwo , $columThree as the insert values, the loop will continue until the entire table is saved */
}
I have a partial view named SIM Balance in mine dashboard. This view should show the number of sims issued to a user date wise.
I have set up the controller
public function actionSimbalance()
{
$sql = "SELECT user.`name` AS issued_to, COUNT(`sims`.`id`) AS sims_issued, sims.`operator_name` AS operator_name,
CASE
WHEN sims.`status` = 'Production Stored SIM' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
WHEN sims.`status` = 'Testing Stored SIM' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
WHEN sims.`operator_name` = 'Zong' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
WHEN sims.`operator_name` = 'Mobilink' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
ELSE CAST(`sims`.`created_at` AS DATE) END AS issued_date
FROM `sims`
INNER JOIN `sim_issueance_transaction` ON (`sims`.`id` =
`sim_issueance_transaction`.`sim_id`)
INNER JOIN `user` ON (`sims`.`issued_to` = `user`.`id`)
WHERE sims.`status` IN ('Testing Stored SIM','Production Stored SIM')
GROUP BY user.`name`, sims.`status`, issued_date, sims.`operator_name`";
$rows = Yii::$app->db->createCommand($sql)->queryAll();
$output = [];
$grandtotal = 0;
foreach ($rows as $row) {
$std = new \stdClass();
$std->count = $row['sims_issued'];
$std->issued_to = $row['issued_to'];
$std->operator = $row['operator_name'];
$std->issued_date = $row['issued_date'];
$grandtotal += $std->count;
$output[]= $std;
}
return $this->renderPartial('sim_progress', ['model' => $output, 'grandtotal' => $grandtotal]);
}
The partial view sim_progress is below
<?php foreach ($model as $row){?>
<tr>
<td><?=$row->issued_to?></td>
<td><?=$row->count?></td>
<td><?=$row->operator?></td>
<td><?= $row->issued_date ?></td>
</tr>
<?php } ?>
<tr>
<td><strong>Grand Total</strong></td>
<td>
<strong><?= $grandtotal ?></strong>
</td>
<td></td>
</tr>
Then there is an HTML sim-balance I have designed
<div class="box box-info">
<div id="af8a8d88334">
<div class="print-header print-only">
<center><img style="width: 100px" src="<?=
\yii\helpers\Url::to('#web/images/logo.png', true); ?>"/>
</center>
<br/>
<hr/>
</div>
<div class="box-header with-border">
<h3 class="box-title">SIM Balance</h3>
</div>
<div class="box-body">
<div class="table-responsive">
<table class="table no-margin">
<thead>
<tr>
<th>Issued To</th>
<th>Sims Issued</th>
<th>Operator Name</th>
<th>Issued At</th>
</tr>
</thead>
<tbody id="dashboard-sim-balance">
</tbody>
</table>
</div>
</div>
</div>
<div class="box-footer clearfix">
<a href="javascript:void(0)" onclick="$('#af8a8d88334').printThis();"
class="btn btn-sm btn-default btn-flat pull-right">Print</a>
</div>
Then in my main site index view, I am calling it like below
.
.
.
<?php if (!Yii::$app->user->isGuest && in_array(Yii::$app->user->identity->user_role,[1,6])) {
echo $this->render('dashboard/sim-balance');
} ?>
.
.
.
.
$url_sim_balance = Url::toRoute('/dashboard/simbalance');
.
.
.
.
In my JS I am creating an ajax function which should show the details.
$script = <<< JS
$(document).ready(function () {
.
.
.
.
loadSimBalance();
.
.
.
});
function loadSimBalance() {
$('#dashboard-sim-balance').html('');
$.ajax({
url: '$url_sim_balance',
data: data.val(), // also tried $('#dashboard-sim-balance').val()
success:function(data) {
$('#dashboard-sim-balance').html(data);
},
error: function() {
}
});
}
JS;
$this->registerJs($script);
But when I run my project I cannot see the details but an empty table like below
How can I set my ajax call to view the details.
Any help would be highly appreciated.
change
function loadSimBalance() {
$('#dashboard-sim-balance').html('');
$.ajax({
url: '$url_sim_balance',
data: data.val(), // also tried $('#dashboard-sim-balance').val()
success:function(data) {
$('#dashboard-sim-balance').html(data);
},
error: function() {
}
});
}
To
function loadSimBalance() {
$('#dashboard-sim-balance').html('');
$.ajax({
url: '$url_sim_balance',
success:function(data) {
$('#dashboard-sim-balance').html(data);
},
error: function() {
}
});
}
I'm trying to get all checked checkbox values and parse them to my php functin using AJAX.
I use foreach to try and get each id of the checked checkbox's.
My problem is that when I try and update the database, it doesn't return '1' which I echo upon success.
When I take my foreach code out, it works.
My delete button is :
<form class="form -dark" id="form-inline" method="POST">
<div class="btn-group">
<button type="button" onclick="deleteSelectedTokens()" class="btn -dark" style="margin-left: 5px;" title="Delete all selected tokens"><i class="fa fa-trash"> </i></a>
</div>
</form>
My checkbox html/php code is :
<table class="table -dark -striped">
<thead>
<tr>
<th style="text-align: center;"><input type="checkbox" id="selectall"/></th>
<th style="text-align: center;">Token</th>
<th style="text-align: center;">Date/Time Generated</th>
<th style="text-align: center;">Status</th>
<th style="text-align: center;">Durbaility</th>
</tr>
</thead>
<tbody>
<tr>
<?php
$username = $_SESSION['username'];
$token_result = mysqli_query($con, "SELECT id, token, used, time_generated, durability FROM tokens WHERE user_id = '$username' ORDER BY used");
if(mysqli_num_rows($token_result) > 0) {
while($token_row = mysqli_fetch_array($token_result)) {
$result = array($token_row['durability']); $sub_struct_month = ($result[0] / 30) ; $sub_struct_month = floor($sub_struct_month); $sub_struct_days = ($result[0] % 30); $sub_struct = "<i>".$sub_struct_month."</i> month(s) <i>".$sub_struct_days."</i> day(s)";
echo '
<tr style="text-align: center;">
<td>
<center><input type="checkbox" id="checkedTokens" class="checkbox" value='.($token_row['id']).'></center>
</td>
<td>
'.$token_row['token'].'
</td>
<td>
'.($token_row['time_generated']).'
</td>
<td>
'.($token_row['used'] == "0" ? "<span class='label label-primary'><i class='fa fa-check'></i> Valid </span>" : "<span class='label label-primary'><i class='fa fa-fa fa-times'></i> Used </span>").'
</td>
<td>
'.$sub_struct.'
</td>
';
} }else{ ?>
<tr>
<td colspan="12" style="padding: 30px;">
<div class="alert -dark">
<div class="alert-icon _text-danger">
<i class="fa fa-exclamation-circle"></i>
</div>
No tokens in your account
</div>
</td>
</tr>
<?php } ?>
</tr>
</tbody>
Notice I need to use foreach to get each check checkbox value so I can remove the selected ones when I press the delete button.
My AJAX send to PHP function is :
<script>
function deleteSelectedTokens() {
var selectedTokens = document.getElementById("checkedTokens").value;
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: {
deleteSelectedTkns: true,
checked_id: selectedTokens
},
success: function(msg){
if(msg == 1) {
update_myDays_success();
} else {
general_error_forms();
}
},
});
return false;
}
</script>
I think the problem is the Javascript... when I get the value of the checkboxes and post them, i think it's only getting 1 value inside the checkedTokens id.
My php receive code (this is not the problem) :
$username = $_SESSION['username'];
$selectedTokens = mysqli_real_escape_string($con, $_POST['checked_id']);
foreach($selectedTokens as $id) {
$doUpdateDelete = 'DELETE FROM tokens WHERE id = "'.$id.'" AND user_id = "'.$username.'"';
$result = $con->query($doUpdateDelete) or die("Error");
if($result)
{
echo '1';
}
else
{
echo 'Failed';
}
}
My console.log has not errors. Like I said, i think it's the javascript code for getting the value of my checkbox's not getting all the values.
You can send json of checked items:
<script>
var selectedTokens = [];
$('#checkedTokens:checked').each(function(key, value){
selectedTokens.push($(value).val());
});
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: {
deleteSelectedTkns: true,
checked_id: JSON.stringify(selectedTokens)
},
success: function(msg){
if(msg == 1) {
update_myDays_success();
} else {
general_error_forms();
}
},
});
</script>
And your php code mysqli_real_escape_string give only string we should convert json to get array:
$selectedTokens = json_decode($_POST['checked_id']);
foreach($selectedTokens as $id) {
$doUpdateDelete = 'DELETE FROM tokens WHERE id = "'.$id.'" AND user_id = "'.$username.'"';
$result = $con->query($doUpdateDelete) or die("Error");
if($result)
{
echo '1';
}
else
{
echo 'Failed';
}
}
In html it is not allowed to assign the same id to multiple tags. (As already mentioned in the comments.)
If you place your checkboxes on a <form id="some_id">, and give every checkbox a unique name and id, you can use the function $('#some_id').serialize() to get the data of the form and post it to the server.
display.html :
<div id="display_result" style="display: none"><table class="table">
<p style="float: right;" >Select All<input type="checkbox" class="allcb" data-child="chk" checked/> </p>
<thead>
<tr>
<th>Die No</th>
<th> Status </th>
<th> Location </th>
<th>Select</th>
</tr>
</thead>
<tbody>
</table>
<div id ="issue_button">
<input type="submit" id="submit" class="btn btn-success " value="Recieve" style="width: 150px;"></div>
</div>
Ajax:
var data = JSON.stringify($("#form").serializeArray());
// alert(data);
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type: 'POST',
data: {
list: data
},
url: 'die_recieving_process.php',
success: function(data) ){
$('#display_result').html(data);
}
});
die_recieving_process.php
while($fetch = mysql_fetch_array($query))
{
if($fetch[1] == "Table Rack" )
{
echo '<tr class="success"><td>'.$fetch[0].'</td><td>'.$fetch[1].'</td><td>'.$fetch[3] . '</td> <td><input type=checkbox class="chk" id=check_box value= '.$fetch[2].' name= check_list[] </td> </tr>';
}
else
{
echo '<tr class="warning"><td>'.$fetch[0].'</td><td>'.$fetch[1].'</td><td>'.$fetch[3] . '</td> <td><input type=checkbox class="chk" id=check_box value= '.$fetch[2].' name= check_list[] checked </td> </tr>';
}
}
Hi friends in display.html I have to display the result processed in die_recieving_process.php . In ajax i've sent all the value to die_recieving_process.php and after fetching the result i've to display the result in display.html
First in you Javascript, you have 2 errors:
Your code overrides existing contents of div, which is the whole table...
And you have one unnecessary bracket in success function declaration
So change this:
success: function(data) ){
$('#display_result').html(data);
}
To this:
success: function(data) {//remove unnecessary bracket
$('#display_result tbody').html(data);//add data - to tbody, and not to the div
}
By the way, using $.post() you can write your javascript code shorter, like this:
var data = JSON.stringify($("#form").serializeArray());
$.post('die_recieving_process.php',{list:data},function(responseData){
$('#display_result tbody').html(responseData); //added to tbody which is inside #display_result
$('#display_result').show();
});
Second you need to close your tbody tag inside the table
Create html table with empty body tags and body id = tBody for example:
<table>
<caption>Smaple Data Table</caption>
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
</tr>
</thead>
<tbody id="tBody"></tbody>
</table>
Use the jquery ajax to load json data in the created table after load button is clicked assuming that my json file is storing userData like userName, age, city:
$('#btnLoadAll').click(function () {
$.ajax({
url: "url/data.json",
dataType: 'json',
success: function (resp) {
var trHTML = '';
$.each(resp, function (i, userData) {
trHTML +=
'<tr><td>'
+ userData.userName
+ '</td><td>'
+ userData.age
+ '</td><td>'
+ userData.city
+ '</td></tr>';
});
$('#tBody').append(trHTML);
},
error: function (err) {
let error = `Ajax error: ${err.status} - ${err.statusText}`;
console.log(error);
}
})
});
If you do not see result, try to remove style="display: none" in display.html
I am having a table with data from database called through codeigniter controller.What I want to do is read the selected value from within the table send it back to the controller and use those values to retrieve new records from DB and then load them on again into the page.
My Controller:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Dashboard1 extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->model('dash_match_model');
$this->session->keep_flashdata('supplier_id');
$this->load->helper('url');
$this->load->database();
}
public function index() {
$arr['page']='dash1';
$arr['present_all_suppliers'] = $this->dash_match_model->dash_present_all_suppliers();
$arr['supplierCompany'] = "";
$this->load->view('clients/clDashboard',$arr);
}
public function select_supplier() {
$supplierCompany = $this->input ->post('supplierCompany');
$arr['present_all_suppliers'] = $this->dash_match_model->dash_present_all_suppliers();
$arr['supplierCompany'] = $supplierCompany;
$supplier_selected = $this->user_model->return_selected_supplier($supplierCompany);
foreach($supplier_selected->result() as $row)
{
$this->session->set_flashdata('supplier_id', $row->supplier_id);
}
$this->load->view('unspscSegment',$arr);
}
}
Specific lines of table of my view file:
<table id="suppliertable" class="table table-striped table-bordered bootstrap-datatable datatable">
<thead>
<tr>
<th>Supplier</th>
<th>Open Range</th>
<th>Fill Content</th>
<th>Total Match</th>
</tr>
</thead>
<tbody>
<?php foreach ($present_all_suppliers as $v): ?>
<tr>
<td onclick="window.location = 'http://example.com'" class="center" style="color:#0c595b;"> <?php echo $v->supplierCompany; ?> </td>
<td class="center"></td>
<td class="center"></td>
<td class="center"></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
How can I do that with javascript so when i select a supplier (value) to get the selected value and sent it to the controller? Then what should I modify to the controller in order to send the value to the model and collect it and reload them in the view?
You can use jQuery.ajax()
Implemented in your code:
Script:
<script>
$(".supplier_edit").click(function(){
var supplier_company = $(this).find('input').val()
$.ajax({
type: 'POST',
url: 'http://example.com/'+'Dashboard1/select_supplier',
data: {supplierCompany: supplier_company},
success: function(result) {
$("#content").html(result)
}
})
return false
})
</script>
HTML:
<tbody>
<?php foreach ($present_all_suppliers as $v): ?>
<tr>
<td class="supplier_edit" style="color:#0c595b;"><input type="hidden" value="<?php echo $v->supplierCompany; ?>" ></td>
<td class="center"></td>
<td class="center"></td>
<td class="center"></td>
</tr>
<?php endforeach; ?>
</tbody>
<div id="content">content from the controller</div>