if condition php reports generation - php

I created a Reports module in a medication administration webapp.
A medication can be stopped, and when it happens, it's value in the database turns to 1 (1=stopped 0=active). I need the report to show "STOPED" in the "administered by" column instead of the administrator's name when a medication is stopped so here is my code, but it's not working :( It returns "STOPED" for everything. What am I doing wrong ?
Any help will be appreciated!
for (var i = 0; i < medi.length; i++) {
keys_str += "<tr>";
keys_str += "<td>" + medi[i].date + "</td>";
if (medi[i].isprn == 'y' || medi[i].isprn == "Y")
keys_str += "<td>PRN</td>";
else
keys_str += "<td>" + medi[i].time + "</td>";
keys_str += "<td>" + medi[i].medicationame + "</td>";
keys_str += "<td>" + medi[i].dosage + "</td>";
if (medi[i].is_stop !== '1' || medi[i].is_stop !== "1")
keys_str += "<td>STOPED</td>";
else
keys_str += "<td>" + medi[i].administeredby + "</td>";
keys_str += "<td>" + medi[i].witness + "</td>";
keys_str += "<td>" + medi[i].notes + "</td>";
keys_str += "<td > <img width='150px' src='" + medi[i].e_sign + "' /></td>";
keys_str += "</tr>";
}
$("#medication_hid_pdf").html();
$("#medication_hid_pdf").html(keys_str);
var date;
var time;
var medicationame;
var dosage;
var addministered;
var witness;
var str = "";
var count = 0;
for (property in medi) {
if (medi.hasOwnProperty(property)) {
str += "<tr class='gradeX'>";
date = medi[count].date;
time = medi[count].time;
medicationame = medi[count].medicationame;
dosage = medi[count].dosage;
addministered = medi[count].administeredby;
witness = medi[count].witness;
mid = medi[count].id;
str += "<td>" + date + "</td>";
if (medi[count].isprn == 'y' || medi[count].isprn == "Y")
str += "<td>PRN</td>";
else
str += "<td>" + time + "</td>";
str += "<td>" + medicationame + "</td>";
str += "<td>" + dosage + "</td>";
if (medi[count].is_stop !== '1' || medi[count].is_stop !== "1")
str += "<td>STOPED</td>";
str += "<td>" + addministered + "</td>";
str += "<td>" + witness + "</td>";
str += "<td>" + medi[count].notes + " </td>";
str += "<td ><img width='150px' src='" + medi[count].e_sign + "' /> </td>";
str += "</tr>";
count++;
}
}
$("#medicationreport_data").html(str);
}
});

I don't know exactly what your error is, but there is a lot of minor "issues" and messyness.
Now as this question is tagged PHP and you mention getting the data from the database I will assume that there is some PHP file giving this data to Javascript. How that is happening I cant tell by what is posted.
But my point is, that you should format as much of this data as you can on the PHP ( backend ) side of things. Most of this is stuff like:
....
if (medi[count].isprn == 'y' || medi[count].isprn == "Y")
str += "<td>PRN</td>";
else
str += "<td>" + time + "</td>";
....
if (medi[i].is_stop !== '1' || medi[i].is_stop !== "1")
keys_str += "<td>STOPED</td>";
else
keys_str += "<td>" + medi[i].administeredby + "</td>";
......
Basically we are just checking a value and changing it, so here PHP's loosly typed nature will help you more then JavaScripts weakly typed.
In PHP this would be something like this
$formatted = [];
foreach( $medi as $row ){
$data = []; //create a clean array if you have to
$data['isprn'] = strtolower($row['isprn']) == 'y' ? 'PRN' : $row['time'];
$data['is_stop'] = $row['is_stop'] != '1' ? 'STOPED' : '';
//include other stuff in $data you need
$formatted[] = $row;
}
Then if you get it clean enough, in Javascript you can do stuff like this
var str = '';
for (var i = 0; i < medi.length; i++) {
str += '<tr>';
str += '<td>' + medi[i].join('</td><td>') + '</td>';
str += '</tr>';
}
There are many many ways to do this, and there is a lot of "necessary" information missing for me to really be able to do much more. But I would "Strongly" suggest, normalizing all this data on the server side as best as can be done. Then on the client side you will really reduce the amount of work needed to display it to the end user.

Related

Dynamically form not submitting properly AJAX PHP

I am trying to generate dynamically form in table and submit but there is problem in my code which is difficult for me solve,
$(document).ready(function() {
$('#btnsummary').on('click', function() {
var date = $('#dddeliverydate').val();
var soid = $('#sssoid option:selected').val();
$.ajax({
url: "tblsum.php",
method: "POST",
dataType: 'JSON',
data:
"&date=" +
date +
"&soid=" +
soid,
success: function(response) {
if ( response.length == 0 ) {
alert("NO DATA FOUND!");
}
else{
$("#tblsum tbody").empty();
var len = response.length;
for(var i=0; i<len; i++){
var invoiceno = response[i].invoiceno;
var shopname = response[i].shopname;
var paymentmode = response[i].paymentmode;
var finalamount = response[i].finalamount;
if (finalamount==0){
return false
}
else if (paymentmode=="Credit"){
var tr_str = "<tr>" +
"<td align='center'>" + invoiceno + "<input type='hidden' name='invoiceno[]' value='"+invoiceno+"'></td>" +
"<td align='center'>" + shopname + "</td>" +
"<td align='center'>" + paymentmode + "</td>" +
"<td align='center'>" + finalamount + "</td>" +
"<td align='center'><input type='number' id='finalamount' name='finalamount[]' value='0'></td>" +
"</tr>";
$("#tblsum tbody").append(tr_str);
}
else{
var tr_str = "<tr>" +
"<td align='center'>" + invoiceno + "<input type='hidden' name='invoiceno[]' value='"+invoiceno+"'></td>" +
"<td align='center'>" + shopname + "</td>" +
"<td align='center'>" + paymentmode + "</td>" +
"<td align='center'>" + finalamount + "</td>" +
"<td align='center'><input type='number' id='finalamount' name='finalamount[]' value='" + finalamount + "'></td>" +
"</tr>";
$("#tblsum tbody").append(tr_str);
}
}
$("#tblsum tbody").append("<tr><td colspan='5'><button class='btn btn-success' type='button' id='btnsum'onclick='summary()'>Save</button></td></tr>");
}
}
})
});
})
There is two problem if final amount is 0 then save button did not appear, when I submit form first field which is invoiceno don't submit on next page,
below is submit function
function summary(){
$(document).ready(function(e) {
var date = $('#dddeliverydate').val();
var soid = $('#sssoid option:selected').val();
var form = $('#formsum').serialize();
$.ajax({
url: "test.php",
method: "POST",
data:
"&date=" +
date +
"&soid=" +
soid+
"&form=" +
form,
success: function(data) {
var w = window.open('about:blank', 'windowname');
w.document.write(data);
}
})
})
}
Below is my PHP code.
for($count = 0; $count<count($_POST['invoiceno']); $count++){
$data = array(
$invoiceno = $_POST['invoiceno'][$count],
$amount = $_POST['finalamount'][$count],
);
echo "Invoice NO ".$invoiceno." Amount ".$amount.'<br>';
}
sorry for bad english.
I told you before return STOPS executing a function, so all code after it is obsolete. In this case, when finalamount == 0 you stop executing the function and return to the place where it started. So the code to create the submit button never will be reached. With some proper indentation, you could see that:
$(document).ready(function() {
//<< ===== START START START of onclick function
$('#btnsummary').on('click', function() {
....
$.ajax({
url: "tblsum.php",
....
success: function(response) {
if ( response.length == 0 ) { .... }
else{
$("#tblsum tbody").empty();
....
for(var i=0; i<len; i++){
var invoiceno = response[i].invoiceno;
var finalamount = response[i].finalamount;
....
if (finalamount==0){
return false
// STOP EXECUTING THIS FUNCTION
// AND GO DIRECTLY TO END OF FUNCTION ================= >>
// code after this will NOT be executed
}
else if (paymentmode=="Credit"){....}
else{....}
}
// if finalamount == 0, this will never be executed
$("#tblsum tbody").append("<tr><td colspan='5'><button class='btn btn-success' type='button' id='btnsum'onclick='summary()'>Save</button></td></tr>");
}
}
})
});
// ===== END END END of onclick function << ===============
// continue executing script from here
})
So you could use continue instead of return to skip only one itteration in the for loop.

jQuery.Deferred exception: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefined

$.post("#", params).then(function (response) {
if (obj['error'] != 1) {
var html = '';
for (var i = 0; i < response['data'].length; i++) {
console.log('data' + i, response['data'][i]);
html += '<tr>';
html += '<td>' + response['data'][i]['wallet_type'] + '</td>';
html += '<td>' + response['data'][i]['balance'] + '</td>';
html += '<td>' + response['data'][i]['wallet_address'] + '</td>';
html += '</tr>';
}
}
});
I found
Uncaught TypeError: Cannot read property 'length' of undefined
in the console for that i cannot able to display my result.
First you need to check your response array in console something missing in your response.i think your response array does not set.
ex. console.log(response);
<script>
var response={"data":[{"id":556,"user_id":333,"email":"alokkr#dispostable.com","name":"alokkr#dispostable.com","wallet_id":"5ab7dfaa39062807cc3d0659a5ee9634","wallet_address":"QNqpGLNDhsCLWsqbz4joJHnh7QBQYhWQhz","wallet_type":"ltc","balance":0,"is_custom":false,"is_test":"0","created":"2018-03-25T17:44:50","updated":null},],"error":0,"msg":[]}
//console.log(response['data'].length);
var html='';
for (var i = 0; i < response['data'].length; i++) {
console.log('data' + i, response['data'][i]);
html += "<table border='1'>";
html += "<tr>";
html += '<td>' + response['data'][i]['wallet_type'] + '</td>';
html += '<td>' + response['data'][i]['balance'] + '</td>';
html += '<td>' + response['data'][i]['wallet_address'] + '</td>';
html += '</tr>';
html += '</table>';
}
document.write(html);
</script>

Change the way time is displayed in query

I fetch a series of times from the database which represent competitors lap times. I have got the database set as TIME which shows 00:00:00. It also adds up the total at the end.
I am wanting to change it so that it does not show all the 0's if for example a time of 53 seconds is entered (0:53) would be shown. I want to do this just to tidy the webpage up. Same for the total that shows 00:00:53 for the above example I would prefer it to be 0:53. If there is a minutes included to show 1:53, ten minutes 10:53, hour 1:10:53 etc.
<?php
//MySqli Select Query
$results = $mysqli->query("SELECT *, TIME(r1 + r2 + r3 + r4 + r5 + r6 + r7 + r8 + r9 + r10 + r11 + r12 + r13 + r14 + r15 + r16 + r17 + r18 + r19 + r20 + r21 + r22 + r23 + r24 + r25 + r26 + r27 + r28 + r29 + r30 + r31 + r32 + r33 + r34 + r35 + r36 + r37 + r38 + r39 + r40 + r41 + r42 + r43 + r44 + r45 + r46 + r47 + r48 + r49 + r50) AS total FROM test");
$title = $mysqli->query("SELECT * FROM test_info");
$all_cols=array("rt1" => "r1","rt2"=> "r2","rt3"=> "r3","rt4"=> "r4","rt5"=> "r5","rt6" => "r6","rt7"=> "r7","rt8"=> "r8","rt9"=> "r9","rt10"=> "r10","rt11" => "r11","rt12"=> "r12","rt13"=> "r13","rt14"=> "r14","rt15"=> "r15","rt16" => "r16","rt17"=> "r17","rt18"=> "r18","rt19"=> "r19","rt20"=> "r20","rt21" => "r21","rt22"=> "r22","rt23"=> "r23","rt24"=> "r24","rt25"=> "r25","rt26" => "r26","rt27"=> "r27","rt28"=> "r28","rt29"=> "r29","rt30"=> "r30","rt31" => "r31","rt32"=> "r32","rt33"=> "r33","rt34"=> "r34","rt35"=> "r35","rt36" => "r36","rt37"=> "r37","rt38"=> "r38","rt39"=> "r39","rt40"=> "r40","rt41" => "r41","rt42"=> "r42","rt43"=> "r43","rt44"=> "r44","rt45"=> "r45","rt46" => "r46","rt47"=> "r47","rt48"=> "r48","rt49"=> "r49","rt50"=> "r50",);
while ($t = $title->fetch_assoc()){
// remember empty cols
$empty_cols=array();
echo "<table width=\"100%\" cellpadding=\"5\" cellspacing=\2\" class=\"entrywriting\" align=\"center\">
<tr align=\"center\">
<td>Overall</td>
<td>Competitor</td>";
foreach ($all_cols as $col => $value) {
if (!empty($t[$col])) {
echo "<td>" . $t[$col] . "</td>";
} else {
// set this column as empty for later
$empty_cols[]=$col;
}
} unset($col); unset($value);
echo "
<td>Total</td>
</tr>";
}
//set counter
$counter = 1;
while($row = $results->fetch_assoc()) {
echo "<tr align=\"center\">";
echo "<td>" . $counter . "</td>";
echo '<td>'.$row["driver"].'</td>';
foreach ($all_cols as $col => $value) {
if (!in_array($col, $empty_cols)) {
// echo non-empty values
echo '<td>'.$row[$value].'</td>';
}
} unset($col); unset($value);
echo '<td>'.$row["total"].'</td>';
$counter++; //increment count by 1
}
echo "</table>";
?>
So I need r1 - r50 to only show times entered in brief rather than full 00:00:00 and total to do the same.
So I have added just under select * from test_info
function timeformat($time) {
// Convenience identifiers
$hh = 0; $mm = 0; $ss = 0;
// Explode the time
$timecomp = explode($time);
// Analyse and return
if ($timecomp[$hh] = "00" && $timecomp[$mm] = "00") {
return '0:'.$ss;
} else
// Continue remaining tests from hereon
if ($timecomp[$hh] = "00" && $timecomp[$mm] = "01") {
return ':'.$mm.$ss;
}
}
I have replace two lines in the code to
echo '<td>'.timeformat($row[$value]).'</td>';
echo '<td>'.timeformat($row["total"]).'</td>';
I am getting
explode() expects at least 2 parameters, 1 given in
You could write a function which takes the time in the hh:mm:ss format and returns a string in the format you want.
Code for the function:
function formattime($time) {
$timecomp = explode(':', $time);
$hh = (int) $timecomp[0]; // Cast as integer
$mm = (int) $timecomp[1]; // Cast as integer
$ss = $timecomp[2]; // Keep '00' format
if ($hh == 0) {
return $mm.':'.$ss;
} else {
return $hh.':'.$mm.':'.$ss;
}
}
Executing:
echo (formattime('00:00:53')); echo '<br>';
echo (formattime('02:00:53')); echo '<br>';
echo (formattime('00:07:53')); echo '<br>';
gives:
0:53
2:0:53
7:53

Data tabulation table

basically I need help to display data in a table using the "td" and "tr" tags.
html += '<table class="table table-striped">';
for(var i in value){
if(!number_regex.test(i)){
html += '<tr>';
html += '<td>' + i + '</td>';
if(i == 'image_link'){
html += '<td> : ' + '<img src=' + value.image_link + ' alt>' + '</td>';
}
else{
html += '<td> : ' + value[i] + '</td>';
}
html += '</tr>';
}
}
html += '</table><br/>';
This is my current code where the value is an object. This outputs one "td" in each "tr". I'm trying to align 2 "td"s in one "tr". However, this cannot be accomplished through next(i) or (i+1) as it isn't a number.
This is what I have tried so far to no avail:
html += '<td>' + next(i) + '</td>';
if(next(i) == 'image_link'){
html += '<td> : ' + '<img src=' + value.image_link + ' alt>' + '</td>';
}
else{
html += '<td> : ' + value[next(i)] + '</td>';
}
and:
html += '<table class="table table-striped">';
html += '<tr>';
for(var i in value){
if(!number_regex.test(i)){
html += '<td>' + i + '</td>';
if(i == 'image_link'){
html += '<td> : ' + '<img src=' + value.image_link + ' alt>' + '</td>';
}
else{
html += '<td> : ' + value[i] + '</td>';
console.log(data);
}
for(var counter = 0; counter <= 8; counter++){
//8 because there are 9 fields in the query I want to display
if(counter % 2 == '0'){
html += '</tr>';
html += '<tr>';
}
}
}
Any idea guys?
These are the additional information that some of you requested:
A picture of the table I have atm:
https://www.dropbox.com/s/kmhkwturtmcxovh/lala.png
and as for the html, this is a javascript syntax, which is why I'm using html in this manner.
Take a variable and place it in the loop, which does the job of ending the rows by adding </tr>...something like :
This is what you have right now :
html += '</tr>';
amend it to something like :
$var = 0; /* initiaize it somewhere outside for(var i in value) */
if(++$var < 2)
{
/* do not echo </tr> if 2 td's haven't been added */
}
else /* 2 td's have been added, end this row */
{
$var = 0; /* reset counter*/
html += '</tr>'; /* end rows */
}

Validating array of inputs using javascript

I hav a rather large form it has 8 fields for entering books .
Now for user to add more books there is a button add more books ,on click of which a javascript function is called and 7 out of 8 fields are duplicated.
User can add maximum 6 books , and all the input fields created dynamically have their names as arrays . I am able to post them and store in a table , Now i want to validate them using javascript.
I have been tryng to do this since a week and am a new to Javascript . Please help me.
MY JAVASCRIPT CODE
function addInput(divName){
var bname1 = new Array();
var abname1 = new Array();
var cost1 = new Array();
var num1 = new Array();
if (counter == limit)
{
alert("You have reached the limit of adding " + counter + " inputs");
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML ="<table>"+ "<tr align='right'>" + "<td>"+ " Name of book" + (counter + 1) + " " +" : <input type='text' name='bname1[]' > "+"</td>" + "</tr>"+"<tr align='right'>"+ "<td>"+" Name of Authour"+(counter + 1)+" "+": <input type='text' name='aname1[]'>"+"</td>"+"</tr>"+"<tr align='right'>"+"<td>"+"Publisher"+(counter+1)+" "+": <input tyme='text' name='pub1[]'>"+"</td>"+"</tr>"+ "<tr align='right'>" +"<td>"+ "ISDN Number " + (counter + 1) +" "+ ": <input type='text' name='isdn1[]'> "+"</td>" + "</tr>"+"<tr align='right'>" +"<td>"+ " Edition " + (counter + 1) + " "+": <input type='text' name='edi1[]'> "+"</td>" + "</tr>"+"<tr align='right'>" + "<td>"+ "Price"+(counter + 1) +" "+ " :<input type='number' name='cost1[]'>"+"</td>"+"</tr>"+"<tr align='right'>" + "<td>"+ "Number of copies"+(counter + 1) +" "+ ": <input type='number' name ='num1[]'> "+"</td>" + "</tr>"+ "</table>";
// alert("counter +1 is "+counter+1);
document.getElementById(divName).appendChild(newdiv);
counter=counter+1;
}
}
there is divsion in the html form to which all this is added.
Please help !
thanx in advance ..
here is your solution. http://codebins.com/codes/home/4ldqpbq
HTML
<div id="testDiv">
</div>
<button onclick="addInput('testDiv')">
Add New Items
</button>
<button onclick="validate('testDiv')">
Validate
</button>
JavaScript
var counter = 0;
var limit = 6
function addInput(divName) {
var bname1 = new Array();
var abname1 = new Array();
var cost1 = new Array();
var num1 = new Array();
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<table>" + "<tr align='right'>" + "<td>" + " Name of book" + (counter + 1) + " " + " : <input type='text' name='bname1[]' > " + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + " Name of Authour" + (counter + 1) + " " + ": <input type='text' name='aname1[]'>" + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "Publisher" + (counter + 1) + " " + ": <input tyme='text' name='pub1[]'>" + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "ISDN Number " + (counter + 1) + " " + ": <input type='text' name='isdn1[]'> " + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + " Edition " + (counter + 1) + " " + ": <input type='text' name='edi1[]'> " + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "Price" + (counter + 1) + " " + " :<input type='number' name='cost1[]'>" + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "Number of copies" + (counter + 1) + " " + ": <input type='number' name ='num1[]'> " + "</td>" + "</tr>" + "</table>";
// alert("counter +1 is "+counter+1);
document.getElementById(divName).appendChild(newdiv);
counter = counter + 1;
}
}
function validate(divName) {
var container = document.getElementById(divName).getElementsByTagName("input");
for (var len = container.length, i = 0; i < len; i++) {
// if only requried validation
if (container[i].value == "") {
container[i].style.borderColor = "red"
} else {
container[i].style.border = ""
}
//if you want saperate validation for each
switch (container[i].name) {
case "bname1[]":
//validate according to filed
break;
case "aname1[]":
//validate according to filed
break;
case "pub1[]":
//validate according to filed
break;
case "isdn1[]":
//validate according to filed
break;
case "edi1[]":
//validate according to filed
break;
case "cost1[]":
//validate according to filed
break;
case "num1[]":
//validate according to filed
break;
}
}
}
Couple of suggestions for you to consider:
1) consider grouping ALL the fields you want to duplicate inside a single div in your form.
Then when the user wants to add new item (book) all you will need to do will be copy the content of this div. This way you will maintain only one copy of field-set.
2) consider dynamic generic form validation too. You add the validation rules to your form field definition with extra attributes i.e. [<input ... validationRules="mandatory,minimumLength=10..." />] I think that you can achieve something similar with JQuery, but I personally prefer NOT to use large libraries to do small jobs.
3) consider giving your fields unique ids too.
use
var bname= document.getElementsByName('bname1[]');
var aname=document.getElementsByName('aname1[]'); .........
for(var i=0;i<bname.length;i++)
{
//Your validations
}
for(var i=0;i<aname.length;i++)
{
//Your validations
}.....
..
do this for all elements in your code..
Validation function example:
function validate_field(f) { // f is input element
var name = f.name; // or also f.getAttribute('name')
var value = f.value; // or also f.getAttribute('value'), but should be defined
var error_div = document.getElementById(name+'err');
//alert('name '+name+' value '+value);
if (name.indexOf('bname') == 0) { // if validate book name
if (value == '') { // e.g. book name should not be empty string?
error_div.innerHTML = 'book name cannot be empty!';
return false; // field is wrong
}
}
else if (name.indexOf('aname') == 0) { // if validate author name
if (value.length<2) {
error_div.innerHTML = 'author\'s name is too short!';
return false; // at least two characters long name? :)
}
}
else if (name.indexOf('pub') == 0) { // if validate publisher
if (value.length<2) {
error_div.innerHTML = 'publisher\'s name is too short!';
return false;
}
}
else if (name.indexOf('isdn') == 0) { // if validate ISDN Number
if (value == '') {
error_div.innerHTML = 'ISDN cannot be empty!';
return false;
}
}
else if (name.indexOf('edi') == 0) { // if validate Edition
if (value == '') {
error_div.innerHTML = 'edition cannot be empty!';
return false;
}
}
else if (name.indexOf('cost') == 0) { // if validate Price
if (value=='') {
error_div.innerHTML = 'Cannot be empty!';
return false;
}
if (isNaN(value)) {
error_div.innerHTML = 'Please write a price using digits!';
return false;
}
}
else if (name.indexOf('num') == 0) { // if validate Number of copies
if (value=='') {
error_div.innerHTML = 'Cannot be empty!';
return false;
}
if (isNaN(value)) {
error_div.innerHTML = 'Please number of copies via digits!';
return false;
}
}
error_div.innerHTML = 'ok';
return true; // field is ok
// you can also have a look at http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
}
Full working script here: pastebin.com/UkVP2uLb

Categories