How to print rows with JavaScript - php

I am currently using
rows.length
in JS and it's giving me the number of rows as output.
The actual code is like this
oResources.html("<h3>Number of Rows = "+ rows.length+"</h3>");
The output is Number of Rows = 1
But I want to see the values of the rows not the number of rows.
The whole function looks like below after editing:
this.get_resources = function(rows)
{ var oResources = $('#resources-'+ options.plugin_uuid);
//oResources.html("<h3>Number of Rows = "+ rows.length+"</h3>");
//oResources.html("<h3>Content of Rows = "+ rows.join(' :: ')+"</h3>");
var data = ""; // Temporary `data` variable
for(var key in rows) { // Loop through the rows
if(rows.hasOwnProperty(key)){
data += rows[key] + "<br />\n"; // Add the current row to the data
}
}
oResources.html(data); // Display the data
//console.log(rows.length);
};
Now it's printing out [object] [object]
My question is:
The output is supposed to be an email id instead of [object] [object]. How to solve this?

Something like that?
oResources.html("<h3>Content of Rows = "+ rows.join(' :: ')+"</h3>");
EDIT: As your data format seems to have another level of depth, I've made a fiddle to give some insight on what you could do. http://jsfiddle.net/TyeQE/

try this:
var data = ""; // Temporary `data` variable
for(var key in rows) { // Loop through the rows
if(rows.hasOwnProperty(key)){
data += rows[key] + "<br />\n"; // Add the current row to the data
}
}
oResources.html(data); // Display the data

Yes, 'rows' looks like an array. You need a for loop to go over the array and print it out.
var str = ""
for(var i = 0; i < rows.length; i++) {
str = rows[i] + "<br>";
}
oResources.html($str);

Try console.log(rows). Open console (usualy F12) in the browser to see the result.

Related

Processing json where the number of json array is dynamic

I have a json response from php to ajax. The thing is depending on the value entered in a text box the number of json arrays vary. Example: sometimes it may return {"count1":10, "ccc1":30} and sometimes like this {"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}. I extract the value in jquery this way:
success: function(response){
var count = response.count1;
//do something
}
But now since the number of counts are different I used a loop. Question is I can figure out how many of them I am receiving but how can I process them? The var count = response.count needs to be specific right? I cannot just concate any strings like this:
var count = 0;
while(something){
count = count + 1;
var str = "count"+count;
var whatever = response.str;
}
So, can someone please help me with a suitable solution in this case?
You are on the right track there. Something like this should work for you.
var i = 1;
while(response['count' + i]) {
var count = response['count' + i++];
}
You can access the properties as if they were array indices. so response['count'+i] works.
Loop through all properties and add them in a variable like following.
var response = { "count1": 10, "ccc1": 32, "count2": 40, "ccc2": 123, "count3": 32, "ccc3": 21 };
var count = 0;
for (var prop in response) {
if (prop.startsWith('count'))
count += response[prop];
}
console.log(count);
To retrieve all values use jQuery $.each function.
var data_tmp = '{"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}';
var data = $.parseJSON(data_tmp);
$.each(data, function(k,val){
if(k.toLowerCase().indexOf("count") >= 0){
$('.wr').append('<div>' + val + '</div>')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="wr"></div>
success: function(response){
var count = response.count1;
var object = JSON.parse(response);
alert(object.length);
for (i = 0; i < object.length; i++) {
console.log(object[i]);
}
}

How to find the cell index when rowspans are involved

I am working on a scheduling project and have run into an issue with finding the column index of a selected cell (so that i may then get the appropriate header for the column). The issue comes into play when a previous cell(or cells) have/has a rowspan. In which case the cell index is off by that amount of cells. I have been at this since yesterday. My current attempt involves using a solution I found in previous posts, and this is this:
parentTr.find('>td, >th').each(function(i,o) {
if ( this == reference )
{
cellNum = i;
var counter = columnNum;
while ( counter-- )
{
$(this).closest('tr').next().find('>td,>th').each(function(i,o)
{
if ( cellNum == i )
{
$(this).addClass('rowspan-affected');
$(this).attr('colNum', columnNum);
}
});
}
}
});
})
The problem is that this solution counts the number of rowspanned cells on the entire page. I need a count of the rowspanned cells for only the current clicked cell, and then be able to add that count to index so I can get the proper header. What I have been trying looks like this:
var $this = $(this);
//get the row header contents
var row = $this.parent('tr').contents('th:eq(0)').html();
//trying this
var colCount = $(this).prevAll().find('td').parent('tr').attr('rowspan');
alert (colCount);
//used to get the cell index
var rowIndex = $(this).parent().index('.main tbody tr');
var tdIndex = $(this).index('.main tbody tr:eq('+rowIndex+') td');
//alert ("tdindex " + (tdIndex+1));
var headerObj = $(this).parents('.main').find('th').eq(tdIndex+1);
//strip whitespace before passing
var toPass = $.trim(headerObj.text());
//toPass = $.trim(toPass)
//alert (toPass);
This information is gathered and then passed to a new form with the selected information used to populate the form.
If anyone can help me with this, I would be greatly appreciative!!!

compare values of cells in different rows in table using jquery

I have a dynamically generated table with php that has same rows. Need to get value from cell 1 in row 1 and value from cell 1 in row 2 and compare them. If they are the same remove entire row or hide... Do that for the whole table... Any help is appreciated.. Thanks!!
Haave this so far:
var numRows = $('table#changeSubjectKatedra tr').lenght;
var i = 0;
do {
var cur = $('input#'+i).val();
var next = $('input#'+(i+1)).val();
if(cur == next){
$('tr#'+i).remove();
}
i++;
} while(i<numRows);
The row in table looks like this:
<tr id='idNum'><td>someText<input type='hidden' value='someData' id='idNum'>
</td><td>someText</td></tr>
Note 1. You should do in on server side with PHP, not with JavaScript.
Note 2. You must use unique id for each element.
Note 3. Avoid using numerical ids of elements.
Note 4. You don't need ids at all for doing what you want.
If you still want to do it in JavaScript, I suggest you to do it this way: (live demo here)
var rows = $("#changeSubjectKatedra tr");
for(var i = 0; i <= rows.length - 2; i++) {
if ($(rows[i]).find("input").val() ==
$(rows[i+1]).find("input").val()) {
$(rows[i]).remove();
}
}
You can use jQuery's .each function. This should work according to the description you provided:
$('table#changeSubjectKatedra tr').each(function() {
if (repeat == $(this).children("input")[0].value) {
$(this).remove();
}
repeat = $(this).children("input")[0].value;
});

Populate Select list Menu though Ajax Jquery

Before anybody says this is a duplicate of this and that question, let me assure you I have tried the solutions there and I have failed. I am using a solution offered in this website to come up with my solution and I believe I am 90% done except for one error. I want to display a list of all codes that have a certain common ID associated with them.
Here is my PHP code that I am using to get a list of codes
<?php
$budgetcode=$_POST['budgetcode'];
//$budgetcode=2102;
$selectcodes="SELECT * FROM tblbudget_codes WHERE T1 = $budgetcode";
$query=$connection->query($selectcodes);
$count=$query->num_rows;
if($count < 1)
{
die('0');
}
else{
while($row=$query->fetch_array()){
$T1=($row['T1']);
$T2=($row['T2']);
$T3=($row['T3']);
$T4=($row['T4']);
$optionValue = $T1."-".$T2."-".$T3."-".$T4;
echo json_encode("<option>$optionValue</option");
// echo json_encode('1');
}
}
?>
Here is the ajax call i am using to fetch the codes
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(data!='0')
{
$("#budgetcode").html(data).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
//alert(budgetid);
})
The problem here is that jquery does not understand the data it is receiving if it is not numeric. E.g if I comment out the json_encode('1') and put random html code instead of data in my success part, I get results displayed in my browser. Can anybody tell me why jquery is only recognizing numeric values that are being echoed from PHP and not varchar values. Using jquery 1.4.2. Any help appreciated.
EDIT
I have managed upto some point and now i am stuck. I have used John's Answer and here is my jquery code. i just need to split the array and append each element to a variable one at a time like here
here is the code. Somebody please tell how I split (data). i can alert it but it is comma seperated. Just need to get the individual items append them to variable html and then display it.
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(!$.isEmptyObject(data))
{
//alert (data);
// alert(split (data))
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option>' +data+ '</option>';
}
$("#budgetcode").html(html).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
I would skip JSON altogether:
PHP
echo "<option>$optionValue</option>";
Everything else should work.
Finally figured it out. Here is the php code
$selectcodes="SELECT * FROM tblbudget_codes WHERE T1 = $budgetcode";
$query=$connection->query($selectcodes);
$count=$query->num_rows;
if($count < 1)
{
die('0');
}
else{
while($row=$query->fetch_array()){
$data[] = $row;
}
echo json_encode($data);
}
?>
Here is the jquery code
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(!$.isEmptyObject(data))
{
//alert (data);
var html = '';
var joiner='';
var len = data.length;
for (var i = 0; i< len; i++) {
joiner=([data[i].T1,data[i].T2,data[i].T3, data[i].T4].join('-'));
//alert(joiner);
html += '<option>'+joiner+'</option>';
}
$("#budgetcode").html(html).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
Had to use join to join the multiple codes using a dash. Hope this helps. The PHP part and part of the jquery was inspired by this question
FWIW, for populating select lists I usually use the following jQuery code:
// populates select list from array of items given as objects: {
name: 'text', value: 'value' }
function populateSelectList(parent, items) {
parent.options.length = 0;
if (parent.options.length === 0) {
parent.options[0] = new Option("Please select something...", "");
}
$.each(items, function (i) {
if (typeof (this) == 'undefined') { return; }
parent.options[el.options.length] = new Option(this.name, this.value);
});
}
and to call the above function i pass the results of an ajax call using the map method where #select is the selector for the parent select element. I am setting the Text property to the name and Value to the value but that should change according to the objects returned by the ajax call (e.g. assuming the returned objects have a Value and Text properties).
populateSelectList($('#select').get(0), $.map(results, function
(result) { return { name: result.Text, value: result.Value} }));

php + jqgrid + export to excel

Somebody knows a way to export the data from a jqgrid to excel?
I want to do a report using this jqgrid that i think is awsome. But i need to save or print this report somehow, because is information to be keeped.
Somebody knows any way??
This is my approach, just add this code to your js/html file
$("#list").jqGrid('navGrid', '#pager',{view:true, del:false, add:false, edit:false, excel:true})
.navButtonAdd('#pager',{
caption:"Export to Excel",
buttonicon:"ui-icon-save",
onClickButton: function(){
exportExcel();
},
position:"last"
});
function exportExcel()
{
var mya=new Array();
mya=$("#list").getDataIDs(); // Get All IDs
var data=$("#list").getRowData(mya[0]); // Get First row to get the labels
var colNames=new Array();
var ii=0;
for (var i in data){colNames[ii++]=i;} // capture col names
var html="";
for(i=0;i<mya.length;i++)
{
data=$("#list").getRowData(mya[i]); // get each row
for(j=0;j<colNames.length;j++)
{
html=html+data[colNames[j]]+"\t"; // output each column as tab delimited
}
html=html+"\n"; // output each row with end of line
}
html=html+"\n"; // end of line at the end
document.forms[0].csvBuffer.value=html;
document.forms[0].method='POST';
document.forms[0].action='csvExport.php'; // send it to server which will open this contents in excel file
document.forms[0].target='_blank';
document.forms[0].submit();
}
PHP script
header('Content-type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=file.xls");
header("Pragma: no-cache");
$buffer = $_POST['csvBuffer'];
try{
echo $buffer;
}catch(Exception $e){
}
very good question, i was scratching my head off about this as well.
I made it by choosing Felix's suggestion, let me complete it by adding following lines to your
html body.
<form method="post" action="csvExport.php">
<input type="hidden" name="csvBuffer" id="csvBuffer" value="" />
</form>
The only problem i have is the excel file exported doesnt include my column names in jqgrid, also is there a way to exclude a particular or several columns when exporting to excel file?
thank you ~
Great function!
I have made changes.
function exportExcel($id){
var keys=[], ii=0, rows="";
var ids=$id.getDataIDs(); // Get All IDs
var row=$id.getRowData(ids[0]); // Get First row to get the labels
for (var k in row) {
keys[ii++]=k; // capture col names
rows=rows+k+"\t"; // output each Column as tab delimited
}
rows=rows+"\n"; // Output header with end of line
for(i=0;i<ids.length;i++) {
row=$id.getRowData(ids[i]); // get each row
for(j=0;j<keys.length;j++) rows=rows+row[keys[j]]+"\t"; // output each Row as tab delimited
rows=rows+"\n"; // output each row with end of line
}
rows=rows+"\n"; // end of line at the end
var form = "<form name='csvexportform' action='"+php_path+"csvexport.php' method='post'>";
form = form + "<input type='hidden' name='csvBuffer' value='"+rows+"'>";
form = form + "</form><script>document.csvexportform.submit();</sc"+"ript>";
OpenWindow=window.open('', '');
OpenWindow.document.write(form);
OpenWindow.document.close();
}
function gridcsvexport(id) {
$('#'+id).jqGrid('navButtonAdd','#'+id+'_pager',{
caption:'',
title:'export',
buttonicon:'ui-icon-newwin',
position:'last',
onClickButton:function (){
exportExcel($(this));
}
});
}
Here is a clever solution to save the jqGrid data as excel sheet without calling the php script: (You just need to call this function with GridID and an optional Filename)
var createExcelFromGrid = function(gridID,filename) {
var grid = $('#' + gridID);
var rowIDList = grid.getDataIDs();
var row = grid.getRowData(rowIDList[0]);
var colNames = [];
var i = 0;
for(var cName in row) {
colNames[i++] = cName; // Capture Column Names
}
var html = "";
for(var j=0;j<rowIDList.length;j++) {
row = grid.getRowData(rowIDList[j]); // Get Each Row
for(var i = 0 ; i<colNames.length ; i++ ) {
html += row[colNames[i]] + ';'; // Create a CSV delimited with ;
}
html += '\n';
}
html += '\n';
var a = document.createElement('a');
a.id = 'ExcelDL';
a.href = 'data:application/vnd.ms-excel,' + html;
a.download = filename ? filename + ".xls" : 'DataList.xls';
document.body.appendChild(a);
a.click(); // Downloads the excel document
document.getElementById('ExcelDL').remove();
}
We first create a CSV string delimited with ;. Then an anchor tag is created with certain attributes. Finally click is called on a to download the file.
You could have a look at several excel MIME Types : MIME Type List
I solved your problem .and now iam able to export data excel with column names please refer my code.
function exportExcel()
{
var mya=new Array();
mya=$("#tblnoupdate").getDataIDs(); // Get All IDs
var data=$("#tblnoupdate").getRowData(mya[0]); // Get First row to get the labels
var colNames=new Array();
var ii=0;
for (var i in data){colNames[ii++]=i;} // capture col names
var html="";
for(k=0;k<colNames.length;k++)
{
html=html+colNames[k]+"\t"; // output each Column as tab delimited
}
html=html+"\n"; // Output header with end of line
for(i=0;i<mya.length;i++)
{
data=$("#tblnoupdate").getRowData(mya[i]); // get each row
for(j=0;j<colNames.length;j++)
{
html=html+data[colNames[j]]+"\t"; // output each Row as tab delimited
}
html=html+"\n"; // output each row with end of line
}
html=html+"\n"; // end of line at the end
document.forms[0].csvBuffer.value=html;
document.forms[0].method='POST';
document.forms[0].action='<?php echo $baseurl;?>csvexport.php'; // send it to server which will open this contents in excel file
document.forms[0].target='_blank';
document.forms[0].submit();
}
Please let me know if you face any problem.
create a form and a hidden element with the name "csvBuffer". This element gets set by the function.
I had to change the line
html = html+"\n"
to
html = html+"\\n"
in order to escape it properly.

Categories