isset and !empty for ajax posted variable retrieval php - php

I have a button group consisting of two buttons, each assigned an id and a value :
echo "<div style='margin-top:20px;' class='btn-group'>
<button type='button' class='btn btn-primary' id='btnconventional' value='conventional' style=' border-radius: 3px;'>Conventional Units</button>
<button type='button' class='btn btn-primary' id='btnsi' value='si' style=' border-radius: 3px;'>SI Units</button>
</div>";
And then i want to submit a query and table result depending on the value of the button that will be sent via this ajax script :
<script>
$("#btnconventional").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
Metric: $('#btnconventional').val(), // < note use of 'this' here
},
success: function(result) {
alert('Viewing conventional units');
},
error: function(result) {
alert('error');
}
});
});
</script>
Now when i try to get the variable and run my code, nothing appears but the else statement:
if(isset($_POST['Metric']) && !empty($_POST['Metric'])){
$sql2 = "Select DISTINCT Record_id,Test_Group,Test_Name,Result,subtests.Units from tests,medicalrecords,subtests WHERE medicalrecords.CommonID=".$comid." and medicalrecords.Subtest_id IS NOT NULL AND medicalrecords.Subtest_id=subtests.Subtest_id AND subtests.Test_id=tests.Test_id and tests.Test_Group='CBC'";
$result2 = $conn->query($sql2);
echo $_POST['Metric'];
echo "<table style='margin-top:10px;' class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th style='text-align:center;'>CBC</th>
<th style='text-align:center;'>Result</th>
</tr>
</thead>";
while ($row2 = mysqli_fetch_array($result2)) {
echo "<tr>
<td style='text-align:center;'>".$row2['Test_Name']."</td>
<td style='text-align:center;'>".$row2['Result']." ".$row2['Units']."</td>
</tr>";
}
echo "<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
echo "<button onclick='hideLabResult();'>Back</button>";
}
else echo "Nope";
The success alert is showing after clicking the button, yet "Nope" still shows after the click, it's not going into the if statement and I can't seem to find out way, I'm a starter in ajax and I'd appreciate any tip or help please.

So in success you are only registered to display information about a successful request, not its contents. To display its contents, use $('.btn-group').html(result); for jquery example.

well, when I run the code on my local , I found ajax was not sending the request to correct page. When I put url then success message was showing there with all html code(whole page I mean). Then I write isset condition on top of page and at ending of } i put exit().
Now its working.
<?php
if(isset($_POST['Metric']) && !empty($_POST['Metric']))
{
$sql2 = "Select DISTINCT Record_id,Test_Group,Test_Name,Result,subtests.Units from tests,medicalrecords,subtests WHERE medicalrecords.CommonID=".$comid." and medicalrecords.Subtest_id IS NOT NULL AND medicalrecords.Subtest_id=subtests.Subtest_id AND subtests.Test_id=tests.Test_id and tests.Test_Group='CBC' ";
$result2 = $conn->query($sql2);
$html = $_POST['Metric'];
$html.= "<table style='margin-top:10px;' class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th style='text-align:center;'>CBC</th>
<th style='text-align:center;'>Result</th>
</tr>
</thead>";
while ($row2 = mysqli_fetch_array($result2)) {
$html.= "<tr>
<td style='text-align:center;'>".$row2['Test_Name']."</td>
<td style='text-align:center;'>".$row2['Result']." ".$row2['Units']."</td>
</tr>";
}
$html .="<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
$html .= "<button onclick='hideLabResult();'>Back</button>";
echo $html;
} else echo "Nope"; ?>
<script>
$("#btnconventional").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
Metric: $('#btnconventional').val(), // < note use of 'this' here
},
url : '', // put your page url
success: function(result) {
alert('Viewing conventional units'+result);
},
error: function(result) {
alert('error');
}
});
});
</script>

Related

Ajax / Php sending id from while loop on click to view record details

i have a table with differente IDs on each row (obtained from a while loop), and next to each ID i have element to view the details of this specific record. Now i understand if i want to retrieve the id, i have to send via post method in a form, but i don't want the page to refresh because i'm using bootstrap tabs, i don't want the page to go back to the first tab, therefore, i'm trying to use Ajax not to make the page refresh.
So first of all i have my first table :
I am in Medical Records Tab > Member Medical Records.
and my View item is :
<td style='text-align:center;'> <ul class='nav nav-tabs'><form><a data-toggle='tab' id='testz' value='".$rowmed[0]."' href='#viewMed' role='button'></form><i style='color: gray;' class='fa fa-eye'></i></a></td></ul>
Now i write an ajax script with the variable recdetailsid in DATA:
<script>
$("#testz").click(function(e) {
switchVisible();
e.preventDefault();
$(this).toggleClass( "selected" );
$.ajax({
type: "POST",
data: {
recdetailsid: $(this).val(), // < note use of 'this' here
},
success: function(result) {
alert('Viewing Details !');
},
error: function(result) {
alert('error');
}
});
});
`
and then to get this ajax element :
if ($_SERVER['REQUEST_METHOD'] == 'POST' ) {
if(isset($_POST['recdetailsid'])){
$recdetailsid=$_POST['recdetailsid'];
$sqlmedr = "Select Record_id,Medical_Condition,Date,Notes FROM medicalrecords,teachers WHERE Teacher_id=".$comid." and medicalrecords.CommonID=teachers.CommonID and Dependant_id IS NULL and Record_id=".$recdetailsid." ";
// Created 2 same queries with different names because can't fetch_array twice on the same query and need to pull data twice, 1 outside the while and 1 in a while for table results
$sqlmedrx = "Select Record_id,Medical_Condition,Date,Notes FROM medicalrecords,teachers WHERE Teacher_id=".$comid." and medicalrecords.CommonID=teachers.CommonID and Dependant_id IS NULL and Record_id=".$recdetailsid." ";
// Record_id need to be sent on view click !!!!!!!!!!!! now it is specified explicitely
$resultmedr = $conn->query($sqlmedr);
$resultmedrx = $conn->query($sqlmedrx);
?>
<div class="jumbotron" style="margin-top: 20px; padding-left:0px !important;">
<h3 style="color:black;">Member Record</h3></div>
<?php
$rowmedrx = mysqli_fetch_array($resultmedrx);
if ($type=='teachers') {
echo "Record Id: <td>".$rowmedrx['Record_id']."</td> ";
echo "<table class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th>Condition</th>
<th>Date Of Diagnosis</th>
</tr>
</thead>";
while ($rowmedr = mysqli_fetch_array($resultmedr)) {
echo "<tr>
<td>".$rowmedr['Medical_Condition']."</td>
<td>".$rowmedr['Date']."</td>
</tr>";
}
echo "<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
echo "Notes : <td>".$rowmedrx['Notes']."</td> ";
} else {
$sqlmedr = "Select DISTINCT Record_id,Medical_Condition,Date FROM medicalrecords,teachers,dependants WHERE medicalrecords.Dependant_id=".$comid." and medicalrecords.Dependant_id=dependants.Dependant_id ";
$resultmedr = $conn->query($sqlmedr);
echo "<table class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th>Condition</th>
<th>Date Of Diagnosis</th>
</tr>
</thead>";
while ($rowmedr = mysqli_fetch_array($resultmedr)) {
echo "<tr>
<td>".$rowmedr['Medical_Condition']."</td>
<td>".$rowmedr['Date']."</td>
</tr>";
}
echo "<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
}
} }
?>
<div class="jumbotron" style="margin-top: 20px; padding-left:0px !important; ">
<h3 style="color:black;">Documents</h3></div>
But everything in the server $_POST brackets and isset $_POST brackets does not show, only the alert shows with the Document jumbotron.
( you can see i'm using the variable inside the query, Record_id=".$recdetailsid." ) , this is my whole purpose !
Can anyone give me some tips or help please ? i'm new to ajax but trying my best to get through this, appreciated!

PHP - If database record is a specific value, only show these buttons

I have a multi-step form that allows the user to save for later or submit. If they save for later, i want them to have an option to edit or delete but if they submit, i dont want them to have any option to edit or delete. Although the following code makes sense, its not working; i'm not getting any buttons and it breaks the jquery table plugin and i dont have the search or pagination option:
<table id="myTable" class="table table-bordered table-hover table-striped tablesorter table-responsive">
<thead>
<tr>
<td>Id</td>
<td>Status</td>
<td>Date/Time</td>
<td>Tag</td>
<td>Serial Number</td>
<td>Equipment</td>
<td>Company</td>
<td>Grand Total</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['id']."</td>";
echo "<td><span class='label ".$res['labelwarning']."'>".$res['status']."</span></td>";
echo "<td>".$res['todaysdatetime']."</td>";
echo "<td>".$res['tag']."</td>";
echo "<td>".$res['serialnumber']."</td>";
echo "<td>".$res['currentequipment']."</td>";
echo "<td>".$res['company']."</td>";
echo "<td>".$res['total_grandtotal']."</td>";
$Submitted = "Submitted";
$Saved = "Saved";
if ($res['labelwarning'] == $Submitted) {
echo "<td></td>";
} elseif ($res['labelwarning'] == $Saved) {
echo "<td></td>";
}
echo "</tr>";
}
?>
<Script>
$(document).ready(function() {
$("#myTable").dataTable({
"aaSorting": [ [0,'desc'] ]
});
});
</Script>
Oke I will try to explain this process here:
1 - First you will create a php file where you will fetch the results you need.
when you are fetching the records you will put your results in a variable like so:
$result_html = '';
while($res = mysqli_fetch_array($result)) {
$result_html .= "<tr>";
$result_html .= "<td>".$res['id']."</td>";
...en so on
$result_html .= "</tr>";
}
To return the response to your ajax call you need to add also this:
echo json_encode($result_html);
2 - Before the end </body> tag
<script>
$(document).ready(function() {
$.ajax({
url: '/path/to/the_php_file',
type: 'POST',
dataType: 'json',
data : { //only needed if you have to pass parameters to your query },
})
.done(function(data) {
//data is your html response
// and #returnedResponse is the id given to your body tag
$('#returnedResponse').html(data);
$("#myTable").dataTable();
})
.fail(function() {
console.log("error");
});
});
</script>
3 - Your table
<table id="myTable" class="table table-bordered table-hover table-striped tablesorter table-responsive">
<thead>
<tr>
<td>Id</td>
<td>Status</td>
<td>Date/Time</td>
<td>Tag</td>
<td>Serial Number</td>
<td>Equipment</td>
<td>Company</td>
<td>Grand Total</td>
<td>Action</td>
</tr>
</thead>
<tbody id="returnedResponse">
</tbody>
</table>
NOTE:
You need to have the link to the jquery.js before your ajax call.
This is not a copy and paste solution. You asked for an example on how to do it and here you have a good start point to learn it.
Try to change your if/else part to this:
if ($res['labelwarning'] == $Submitted) {
echo "<td></td>";
} else{
echo "<td></td>";
}

How to get the value of the button in a table if it has multiple records

This is my following code in front End:
<div class="panel panel-primary">
<div class="panel-heading text-center text-uppercase">Birth Certificates For Overall (Pending, Completed)</div>
<div class="panel-body">
<div class="box-body">
<table id="viewer" class="table table-bordered">
<thead>
<tr>
<th>Sr No</th>
<th>Reg Number</th>
<th>From Hospital</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php $Viewer->showAllData(); ?>
</tbody>
<tfoot>
<tr>
<th>Sr No</th>
<th>Reg Number</th>
<th>From Hospital</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
</div><!-- /.box-body -->
</div><!-- /.box -->
</div>
This is my classes code in it of which i have called the object:
public function showAllData()
{
$query = "SELECT * FROM certificate_details ORDER BY created DESC";
$connection = $this->establish_connection();
$details = $connection->query($query);
$connection->close();
if($details->num_rows > 0)
{
$counter = 1;
while($detail = $details->fetch_assoc())
{
$status = $detail['status'];
if($status == 0)
{
$bg = "bg-danger";
$issuestatus = "btn btn-success";
$message = "Confirm Issue!";
}
elseif($status == 1)
{
$bg = "bg-success";
$issuestatus = "btn btn-success disabled";
$message = "Certificate Issued";
}
else
{
$bg = "bg-warning";
$issuestatus = "btn btn-warning";
}
echo "
<tr class='odd gradeX ".$bg."'>
<td>".$counter."</td>
<td>".$detail['registration_number']."</td>
<td>".$this->getHospitalInfo($detail['user_id'])."</td>
<td style='margin: 0;'><div class='btn btn-primary' href='#' value='".$detail['id']."' id='view-details'>View Details</div><div style='margin-left: 10px;' class='".$issuestatus."' href='#' value='".$detail['id']."' id='confirm-issue'>".$message."</div></td>
</tr>
";
$counter = $counter + 1;
}
}
}
I have give a specific id to the button i.e id="view-details" and in the value section it hold the unique value
This is the following JQuery Code which i am triggering whenever i am calling the ("#view-details").click(function(){})
$("#view-details").click(function()
{
var certificateId = $("#view-details").attr('value');
$.ajax({
url: 'get_data.php?id=getCertificateDetails',
type: 'POST',
dataType: 'html',
data: {certificate_id : certificateId},
})
.done(function(resp)
{
var data = $.parseJSON(resp);
if(data.status == 1)
{
var message = "Certificate is Already Issued";
var btn_status = "btn btn-success disabled";
}
else if(data.status == 0)
{
var message = "Click To Confirm Issue!";
var btn_status = "btn btn-danger";
}
else
{
var message = "Technical Issue";
var btn_status = "btn btn-danger disabled";
}
var data = "<div class='modal-dialog'>"+
"<div class='modal-content'>"+
"<div class='modal-header' align='center'>"+
"<h3 class='modal-title'>Certificate Details Are As Follows</h3>"+
"</div>"+
"<div class='modal-body'>"+
"<b>Registration Number</b> : "+data.reg_number+
"<br /><b>Baby's Birth Date</b> : "+data.birth_date+
"<br /><b>Baby's Birth Time</b> : "+data.birth_time+
"<br /><b>Baby's Gender</b> : "+data.gender+
"<br /><b>Baby's Full Name</b> : "+data.baby_name+
"<br /><b>Father's Full Name</b> : "+data.fathers_name+
"<br /><b>Mother's Full Name</b> : "+data.mothers_name+
"<br /><b>Parent's Address While Baby's Birth</b> : "+data.while_baby_birth_parents_address+
"<br /><b>Parent's Permanent Address</b> : "+data.parents_permanent_address+
"<hr /><h4 class='text-center'>Hospital Details</h4>"+
data.hospital_detail+
"<hr /><h4 class='text-center'>Home Details</h4>"+
data.home_detail+
"<hr /><h4 class='text-center'>Other Details</h4>"+
data.other_detail+
"</div>"+
"<div class='modal-footer'>"+
"<button type='button' class='btn btn-default' data-dismiss='modal'>Cancel</button>"+
"<a href='#' class='"+btn_status+"' id='confirm-issue'>"+message+"</a>"+
"</div>"+
"</div>"+
"</div>";
$('#viewDetails').html(data);
$('#viewDetails').modal('show');
})
.fail(function()
{
console.log("error");
});
});
The problem arises when lets take a scenario
have a look at this screenshot
when i click on view details of the very first record the modal is called, but when i click on the next view details the modal doesn't appear. it seems that the modal appears only for the very 1st record present in the table
please can anyone help me with this code
you are generating multiple elements with the same id ("view-details"). That's invalid HTML. Element IDs must be unique. Your click event handler will only work on the first one because it considers that all the later ones are not valid.
Use classes instead (e.g. $( "body" ).on( "click", ".view-details"... instead of $("#view-details").click(... and <div class='btn btn-primary view-details'... as the button (instead of id="view-details")
#view-details id always unique so your modal will only work with first where ever it comes.
For more details about Difference between id and class in CSS and when to use it
so you need to add a class to open model, and some change in your code
HTML :
id='view-details' to <div class='btn btn-primary view-details'>
JS:
$( "body" ).on( "click", ".view-details", function() {
var certificateId = $( this ).attr('value');
// .... Rest of your code here
});
Why Use jQuery .on() because it will bind click handler to every button holding view-details class.
var certificateId = $( this ).attr('value');
Will give you current clicked button's attribute value.

Permanently change order of records by draggable table

I have data table that populates data from the database, I'm using an Ajax Call to Populate the data on the table and I'm using jQuery RowSorter.js to make my table rows draggable. The my query in my data is sorted by sortorder column. Provided that it is draggable, how can I make the sort permanent in the table and be saved on the database. The sortorder should also be updated depending on what sort order the user choose in the draggable table rows. Here's my code:
Ajax:
$.ajax({
url: "api/question/all",
type: 'GET',
success: function(result){
var myObj = $.parseJSON(result);
$.each(myObj, function(key,value) {
var t = $('#QuestionList').DataTable();
t.row.add( [
value.id,
value.columnheader,
value.costperlead,
// value.isenabled,
"<label class='toggle'><input type='checkbox' checked='' id='"+value.columnheader+"'><span class='handle'></span></label>",
value.sortorder,
"<a class='btn btn-small btn-info' href='<?php echo URL::to('question').'/';?>"+value.id+"/edit'><span class='glyphicon glyphicon glyphicon-edit' aria-hidden='true'></span></a>",
"<form method='POST' action='<?php echo URL::to('question').'/';?>"+value.id+"' accept-charset='UTF-8' class='pull-left' >"+
"<input name='_method' type='hidden' value='DELETE'>"+
"<button type='submit' class='btn btn-warning'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span></button>"+"</form>",
] ).draw();
if(value.isenabled == "Yes")
{
$("#"+value.columnheader).prop('checked', true);
}
else if(value.isenabled == "No")
{
$("#"+value.columnheader).prop('checked', false);
}
});
}}).error(function(){
progress.progressTimer('error', {
errorText:'ERROR!',
onFinish:function(){
alert('There was an error processing your information!');
}
});
}).done(function(){
progress.progressTimer('complete');
$( "#progressbar" ).fadeOut( "slow" );
});
My Table HTML
<table id="QuestionList" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th colspan="5"> <center>Question Information<center></th>
<th colspan="2"> <center>Actions<center></th>
</tr>
<tr>
<th>ID</th>
<th>Column Header</th>
<th>Cost Per Lead</th>
<th>Is Enabled?</th>
<th>Sort Order</th>
<th>Edit/View</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7"> </td>
</tr>
</tfoot>
</table>
JS to Call rowsorter
$("#QuestionList").rowSorter({
onDrop: function(tbody, row, index, oldIndex) {
$(tbody).parent().find("tfoot > tr > td").html((oldIndex + 1) + ". row moved to " + (index + 1));
}
});
My Query
public function apiGetQuestions()
{
$questions = Question::orderBy('id', 'DESC')->get();
return json_encode($questions);
}
I'm using Laravel 5, any ideas or guides will be appreciated. Thanks!
Update:
Using Jquery's rowsorter function I can keep track of the positions of the rows and its new position:
$(tbody).parent().find("tfoot > tr > td").html((oldIndex + 1) + ". row moved to " + (index + 1));
You don't want to store the entire table, but you can store the sorting events. Everytime a user clicks on a column, you add that to a sort sequence array and save the array serialized.
var sortSequence = [];
$('th').click(function() {
// direction: 'asc' or 'desc'
sortSequence[$(this).text()] = get_direction_from_jquery_sort_plugin_somehow();
var data = {
'table': ...,
'sequence': sortSequence.serialize()
};
$.post('store-sequence', data);
});
I would then have some sanitization in place when storing the sorting to remove any duplication or ascending, descending, ascending sequences.
Then when retrieving the data, you add the sorting sequence as orderBy() calls.
$query = \DB::table("my_table")->where(...);
$sorts = $this->fetchSorting(\Auth::user(), "my_table");
foreach ($sorts as $column => $direction) {
$query->orderBy($column, $direction);
}
This is all a lot of work however and I wonder if it is really worth it.

Adding a loader to load a table with data jQuery or ajax

Here is the description of my issue:
I have a db connection here:
$host = 'some host credentials';
$dbh = 'My database';
Here is my statement:
$qry = "SELECT some_data FROM some_table LIMIT 1000";
$result = some code here;
Here is my while loop:
echo '<table class="table table-striped table-hover table-bordered" id="example">
<thead>
<tr class="test">
<th style="border: 1px solid #333;">PRODUCTPRICE</th>
<th>PRODUCTNAME</th>
<th>PRODUCTCODE</th>
<th>PRODUCTSALE</th>
<th>PRODUCTPRICE</th>
</tr>
</thead>
<tbody>';
while ($row = mysql_fetch_assoc($result)){
$PRODUCTID = intval($row["PRODUCTID"]);
$PRODUCTNAME = $row["PRODUCTNAME_1"];
$PRODUCTCODE = $row["PRODUCTCODE"];
$PRODUCTSALE = $row["PRODUCTSALE_"];
$PRODUCTPRICE = $row["PRODUCTPRICE"];
echo '<tr class="odd gradeX">
<td>'.$PRODUCTID.'</td>
<td>'.$PRODUCTNAME.'</td>
<td>'.$PRODUCTCODE.'</td>
<td class="center">'.$PRODUCTSALE.'</td>
<td class="center">'.$PRODUCTPRICE.'</td>
</tr>';
}
echo '</tbody>
</table></div>
</div>
</body>
</html>';
I want to make a loader before this content table display because there are more than 50,000 products. Something kind of processing or a circle showing that a content is loading, just a simple one, maybe jQuery or ajax. I have tried many tutorials till now but no success.
here is a scheme for that :
<div id="content"></div>
$.ajax({
url : 'the-above-script.php',
beforeSend : function() {
$("#content").html('<img src="ajax-icon-from-www.ajaxload.info">');
},
success : function(html) {
$("#content").html(html);
}
});

Categories