how to write javascript code within php - javascript

I have got a form, on clicking the submit button:
<form>
<h2 style="text-align: center">* * * PROJECTS * * *</h2>
<br>
<input type="button" name="submit" onclick="document.write('<?php GetCellValues() ?>');" Value="SAVE">
<br>
</form>
<?php
function GetCellValues()
{
echo("Save");
var str = '';
var rows = document.getElementsByTagName('tr');
var table=document.getElementById("project");
for (var i=0;i<table.rows[0].cells.length;i++)
{
str = str + (table.rows[0].cells[i].innerHTML) + ', ' ;
}
for (var c = 1 ; c < rows.length ; c++)
{
str += '\n' + "0" + c + ', ';
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0 ; k < inputs.length ; k++)
{
str += inputs[k].value + ', ';
}
}
}
?>
<?php
$handle = fopen("data.csv", "w");
$hide = $_REQUEST['hide'];
fwrite($handle,$hide);
$file = file('data.csv');
$lines = count($file);
echo'<table id = "projest" border = "1" cellpadding="2" cellspacing="0" style = "width: 60%; margin-left: auto; margin-right: auto; border-color: brown; background-color:gray;">';
echo'<tr cellpadding="100">
<th width="15%"><h3>Sl.No.</h3></th>
<th width="15%"><h3>Project Name</h3></th>
<th width="15%"><h3>ChangeDate</h3></th>
<th width="15%"><h3>Changed By</h3></th>
</tr>';
for ($i=1; $i<$lines; $i++)
{
$part = explode(',', $file[$i]);
echo'<tr>
<td align= "center" width="5%">'.$part[0].'</td>
<td align= "center" width="25%"><input type="text" value='.$part[1].'></td>
<td align= "center" width="25%"><input type="text" value='.$part[2].'></td>
<td align= "center" width="25%"><input type="text" value='.$part[3].'></td>
</tr>';
}
echo'</table>';
?>
But not able to submit the form, if I call the javascript code on onClick, it works.what is the problem in this code, Is there any work around for this?

You have to echo the whole JScript function because PHP doesn't know what you're doing:
echo "<script type = 'text/javascript'>function GetCellValues()
{
//echo('Save'); use document.write()?
var str = '';
var rows = document.getElementsByTagName('tr');
var table=document.getElementById("project");
for (var i=0;i<table.rows[0].cells.length;i++)
{
str = str + (table.rows[0].cells[i].innerHTML) + ', ' ;
}
for (var c = 1 ; c < rows.length ; c++)
{
str += '\n' + "0" + c + ', ';
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0 ; k < inputs.length ; k++)
{
str += inputs[k].value + ', ';
}
}
}</script>";

<?php
echo "<script> your javascript code </script>";
?>
php will work from server javascript will work from client side

You cannot mix javascript code (which is executed on client side) and php (which is server oriented).
First, your function GetCellValues is javascript, not php, so replace your firsts <?php and ?> by <script> and </script>.
Then, you need a form and a button type=submit, or an ajax call.

Related

Vaule javascript to php echo

<script type="text/javascript">
$(document).ready(function() {
var x;
var test = '';
var y = 0;
var a = 0;
day = 5;
for (i = 0; i < day; i++)
{
y++;
a++;
test = test + '<b>Masa Hari '+ y +' </b>- Masa Dari : <input type="text" placeholder="contoh 16:30" name="masakursus[]" value="<?php echo ' + a +'." ".$masakursus1['+ a +']; ?>"/> Masa Hingga : <input placeholder="contoh 16:30" type="text" name="masakursus[]" value="<?php echo $masakursus1[10];?>"/></br>';
}
document.getElementById("demo").innerHTML =test;
});
</script>
is it possible to put the value of var a into var test.? I want to view output from array php.

Delete a table row jquery

I have the following script :
<script type="text/javascript">
$(document).ready(function() {
var rowCount = 1;
$(".add_more_rows").click(function() {
rowCount++;
var recRow = '<p id="rowCount' + rowCount + '"><table><tr><td><label>Key Population Type :</label><?php
$query = "SELECT * FROM `kp_types` ORDER BY Name ASC";
if ($result = mysqli_query($link, $query)) { ?> \n\ < select class = "kp_types fieldstyle_with_label"
required = ""
name = "kp_typess[]"
id = "kp_types" > \n\ <? php
while ($idresult = mysqli_fetch_row($result)) {
$kp_type_id = $idresult[0];
$kp_type_name = $idresult[1]; ?> \n\ < option id = "partner_id"
value = "<?php echo $kp_type_id; ?>" > <? php echo $kp_type_name.
' '; ?> < /option>\n\<?php } ?> \n\ < /select>\n\<?php } ?> < /td>\n\ < td > < input name = "kp_targetss[]"
type = "text"
maxlength = "120"
style = "margin: 4px 5px 0 5px;" / > < /td>\n\\
n\
< td > < span id = "remove_row' + rowCount + '"
onClick = "javascript:fnRemove(this);"
class = "remove_row' + rowCount + '"
style = "font:normal 12px agency, arial; color:blue; text-decoration:underline; cursor:pointer;" > Delete Entry < /span> </td > < /tr> </table > < /p>';
$('.remove_row' + rowCount + '').click(function() {
alert('.remove_row' + rowCount + '');
$('#rowCount' + rowCount).remove();
alert('#rowCount' + rowCount);
});
$('#addedRows').append(recRow);
});
});
function fnRemove(t) {
$(t).parent('p').remove();
}
</script>
I have tried deleting the entry using the function fnRemove(t) which is a table data in the table but it fails but when I do it while I remove the table elements and remain only with the tr and td , it deletes an entry well. How can I solve this error inside the table element ?
in function fnRemove your parent('p') is mistake
and correct is parents('p')
try this,it worked for me
function fnRemove(t) {
$(t).parents('p').remove();
}

export to CSV from dynamic table data via PHP

Let's say I have a dynamic table in php page.... is there a way I can export what I have from the dynamic table to a CSV file (and text file [if possible]) via PHP...
Here I am getting data from table and show it in alert box. But I want to save it in a file. Using php.
Here is my code:
<html>
<head>
<script>
function GetCellValues()
{
var str = '';
var rows = document.getElementsByTagName('tr');
var table=document.getElementById("project");
for (var i=0;i<table.rows[0].cells.length;i++)
{
if (i > 2 )
{
str = str + table.rows[0].cells[3].innerHTML.replace(", ");
}
else
{
str = str + (table.rows[0].cells[i].innerHTML) + ', ' ;
}
}
for (var c = 1 ; c < rows.length ; c++)
{
str += '\n' + "0" + c + ', ';
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0 ; k < inputs.length ; k++)
if (k > 1)
{
str += inputs[k].value.replace(", ");
}
else
{
str += inputs[k].value + ', ';
}
}
document.getElementById('hiden').value = str;
alert(document.getElementById('hiden').value);
}
</script>
</head>
<body>
<form>
<br>
<h1><u>PROJECT</u> :</h1>
<br>
<input type = "hidden" id = "hiden" name = "hiden" value = "">
<input type = "button" name = "submit" onclick = "GetCellValues()" Value = "SAVE">
<br>
</form>
<?php
$handle = fopen("data.csv", "w");
$hide = $_REQUEST['hide'];
fwrite($handle,$hide);
$file = file('data.csv');
$lines = count($file);
echo'<table id = "project" border = "1" cellpadding="2" cellspacing="0"
style = "width: 60%; margin-left: auto; margin-right: auto; border-color: brown; background-color:silver;">';
echo'<tr cellpadding="100">
<th width="15%">Sl.No.</th>
<th width="15%">Project Name</th>
<th width="15%">ChangeDate</th>
<th width="15%">Changed By</th>
</tr>';
for ($i=1; $i<$lines; $i++)
{
$part = explode(',', $file[$i]);
echo'<tr>
<td align= "center" width="5%">'.$part[0].'</td>
<td align= "center" width="25%"><input type="text" value='.$part[1].'></td>
<td align= "center" width="25%"><input type="text" value='.$part[2].'></td>
<td align= "center" width="25%"><input type="text" value='.$part[3].'></td>
</tr>';
}
echo'</table>';
?>
</body>
</html>
you could use the built in PHP5 function fputcsv
here is a sample code
$result = mysqli_query($con, 'SELECT * FROM table_name');
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$fp = fopen('file.csv', 'w');
foreach ($row as $val) {
fputcsv($fp, $val);
}
fclose($fp);
It will return a comma separated string for each row written to file.csv:

Export HTML visible table column content to client side, 2010 Excel page

With F12 debug, the JQuery codes is able to skip hidden column cell, only exort cells not hidden, but the >last statement, window.open NOT able to bring it up on the 2010 EXCEL page.
The following code has been simplied to focus the problem, not able to export HTML table to 2010 Execel
<body>
<table id="myGrid">
<tr><th style="display:">First Column</th>
<th style="display:">Second Column</th>
<th style="display:">Third Column</th>
<th style="display: none">Forth Column</th>
</tr>
<tr><td> 2</td><td> two</td><td> deux</td><td style="display: none"> zwei</td></tr>
<tr><td> 3</td><td> three</td><td> trois</td><td style="display: none"> drei</td></tr>
<tr><td> 4</td><td> four</td><td>quattre</td><td style="display: none"> vier</td></tr>
<tr><td> 5</td><td> five</td><td> cinq</td><td style="display: none">fünf</td></tr>
<tr><td> 6</td><td> six</td><td> six</td><td style="display: none"> sechs</td></tr>
</table>
<br />
Test: <input id="ExportExcel" type='submit' value='Export Excel'>
<script type="text/javascript">
$(document).ready(function () {
$('#ExportExcel').click(function () {
var html;
var numofRows;
var gTable = document.getElementById('myGrid');
numofRows = gTable.rows.length - 1;
var numofCells;
var trhtml = "";
numofCells = gTable.rows[0].cells.length - 1;
for (r = 0; r <= numofRows; r++) {
var c = 0;
var tdhtml = "";
for (c = 0; c <= numofCells; c++) {
if (!(gTable.rows[r].cells[c].currentStyle.display == "none")) {
var tempstr = gTable.rows[r].cells[c].innerText;
tdhtml = tdhtml + "<td>" + gTable.rows[r].cells[c].innerText + "</td>";
}
}
trhtml = trhtml + "<tr>" + tdhtml + "</tr>";
}
html = "<table border='1'>" + trhtml + "</table>";
// MS OFFICE 2003 : data:application/vnd.ms-excel
// MS OFFICE 2007 : application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
window.open('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,' + encodeURIComponent(html));
});
});
</script>
</body>
Ans For the above question:
Here i added class to hidden td
<table id="myGrid">
<tr><th style="display:">First Column</th>
<th style="display:">Second Column</th>
<th style="display:">Third Column</th>
<th style="display: none">Forth Column</th>
</tr>
<tr><td> 2</td><td> two</td><td> deux</td><td class="xyz" style="display: none"> zwei</td></tr>
<tr><td> 3</td><td> three</td><td> trois</td><td class="xyz" style="display: none"> drei</td></tr>
<tr><td> 4</td><td> four</td><td>quattre</td><td class="xyz" style="display: none"> vier</td></tr>
<tr><td> 5</td><td> five</td><td> cinq</td><td class="xyz" style="display: none">fünf</td></tr>
<tr><td> 6</td><td> six</td><td> six</td><td class="xyz" style="display: none"> sechs</td></tr>
</table>
when click on export add this statement -> $('.xyz').remove();
like this
$('#ExportExcel').click(function () {
$('.xyz').remove();
// add export statements here
});
it will work
After export, the class xyz related td's are not displaying in your excel.
The attached JQuery codes will export visible column header, and row cell content to client side Excel ; just copy and paste the following codes to become part of Javascript codes (insert into question codes), and change button id to ExportExcel2. NOTE: assumption: client has Excel installed.
$('#ExportExcel2').click(function () {
str = "";
var myTable = document.getElementById('myGrid');
var rows = myTable.getElementsByTagName('tr');
var rowCount = myTable.rows.length;
var colCount = myTable.getElementsByTagName("tr")[0].getElementsByTagName("th").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelWorkbook = ExcelApp.Workbooks.Add();
var ExcelSheet = ExcelWorkbook.ActiveSheet; //new ActiveXObject("Excel.Sheet");
//ExcelSheet.Application.Visible = true;
ExcelApp.Visible = true;
ExcelSheet.Range("A1", "Z1").Font.Bold = true;
ExcelSheet.Range("A1", "Z1").Font.ColorIndex = 23;
//Format table headers
var tarcol = 0;
for (var i = 0; i < 1; i++) {
targetCol = 1;
for (var j = 0; j < colCount; j++) {
if (!(myTable.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].currentStyle.display == "none")) {
str = myTable.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].innerHTML;
//ExcelSheet.Cells(i + 1, j + 1).Value = str;
ExcelSheet.Cells(i + 1, targetCol).Value = str;
targetCol += 1;
}
}
ExcelSheet.Range("A1", "BD1").EntireColumn.AutoFit();
}
for (var i = 1; i < rowCount; i++) {
targetCol = 1;
for (var k = 0; k < colCount; k++) {
if (!(myTable.getElementsByTagName("tr")[i].getElementsByTagName("td")[k].currentStyle.display == "none")) {
str = rows[i].getElementsByTagName('td')[k].innerHTML;
//ExcelSheet.Cells(i + 1, k + 1).Value = myTable.rows[i].cells[k].innerText;
ExcelSheet.Cells(i + 1, targetCol).Value = myTable.rows[i].cells[k].innerText;
targetCol += 1;
}
}
ExcelSheet.Range("A" + i, "Z" + i).WrapText = true;
ExcelSheet.Range("A" + 1, "Z" + i).EntireColumn.AutoFit();
}
//ExcelSheet.SaveAs("C:\\TEST.XLS");
//ExcelSheet.Application.Quit();
});

How get the textbox values in array.....to store in database

this is my code...
How get the textbox array value to store in database...
<html>
<head>
<script type="text/javascript">
var max = 4; //highest number to go to
var currentIndex = 0;
function btnClick() {
if(currentIndex < max){
currentIndex++;
postClick();
}
}
function Previous(){
if(currentIndex>0){
currentIndex--;
postClick();
}
}
function postClick() {//whatever you want to happen goes here
var sahans = new Array();
sahans[currentIndex] == d;
var d = document.getElementById("div");
d.innerHTML = "<p><input type='text' name='name"+currentIndex+"[]'>";
d.innerHTML += "<p><input type='text' name='topic"+currentIndex+"[]'>";
document.getElementById("div").style.display = "";
}
</script>
</head>
<body>
<form id="form1">
<div>
<input type="button" value="Previous" onclick="Previous();" />
<input type="button" value="Next" onclick="btnClick();" />
<div id="div"></div>
</div>
</form>
</body>
</html>
JavaScript:
function store(form) {
var input = form.getElementsByTagName('input');
var myarray = Array();
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') == 'text') {
myarray[input[i].getAttribute('name')] = input[i].value;
}
}
for (var i in myarray) {
alert(i + ': ' + myarray[i]);
}
}
HTML:
<form onsubmit="store(this); return false">
<p>
<input type="text" name="name" /><br />
<input type="text" name="topic" />
</p>
<p>
<input type="submit" value="Store in database" />
</p>
</form>
Edit:
Ok, now I made a full example with AJAX and the actual saving to the database. The AJAX call uses 'POST'. Simply fill in the number of fields that you want in the max variable.
JavaScript:
var max = 10;
var current = 0;
function goto(form, pos) {
current += pos;
form.prev.disabled = current <= 0;
form.next.disabled = current >= max - 1;
var fields = form.getElementsByTagName('fieldset');
for (var i = 0; i < fields.length; i++) fields[i].style.display = 'none';
fields[current].style.display = 'block';
form['name' + current].focus();
}
function store(form) {
var input = form.getElementsByTagName('input');
var data = '';
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') == 'text')
data += '&' + input[i].getAttribute('name') + '=' + input[i].value;
}
data = encodeURI('n=' + max + data);
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('POST', 'store.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', data.length);
xhr.setRequestHeader('Connection', 'close');
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText != '')
alert(this.responseText);
else {
form.submit.value = 'Saved!';
setTimeout(function() { form.submit.value = 'Save to database' }, 500);
}
}
}
xhr.send(data);
}
window.onload = function() {
var form = document.forms[0];
var container = form.getElementsByTagName('div')[0];
container.innerHTML = '';
for (var i = 0; i < max; i++)
container.innerHTML += '<fieldset><legend>Entry ' + (i + 1) + ' / ' + max + '</legend><input type="text" name="name' + i + '" /><br /><input type="text" name="topic' + i + '" /></fieldset>';
goto(form, 0);
}
HTML:
<form action="submit.php" method="post" onsubmit="store(this); return false">
<p>
<input type="button" name="prev" onclick="goto(this.form, -1)" value="Previous" />
<input type="button" name="next" onclick="goto(this.form, +1)" value="Next" />
</p>
<div>
<noscript>Please enable JavaScript to see this form correctly.</noscript>
</div>
<p>
<input type="submit" name="submit" value="Store in database" />
</p>
</form>
Users who have JS disabled will see what's in the <noscript> tag, otherwise it's replaced with the fieldsets. Also it's good to make an alternative submit page (submit.php) for users who have JS disabled. Below is store.php, the AJAX submit script.
PHP (store.php):
<?php
if (empty($_POST['n']) || $_POST['n'] < 1) die('Invalid request!');
$fields = array('name', 'topic');
$errors = '';
for ($i = 0; $i < $_POST['n']; $i++) {
foreach ($fields as $field) {
if (empty($_POST[$field . $i]))
$errors .= '- ' . $field . ' ' . ($i + 1) . "\n";
}
}
if ($errors != '')
die("Please fill in the following fields:\n" . $errors);
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('mydb', $db);
for ($i = 0; $i < $_POST['n']; $i++) {
$name = mysql_real_escape_string($_POST['name' . $i]);
$topic = mysql_real_escape_string($_POST['topic' . $i]);
mysql_query(' INSERT INTO entries (id, name, topic) VALUES (' . $i . ', "' . $name . '", "' . $topic . '")
ON DUPLICATE KEY UPDATE name = "' . $name . '", topic = "' . $topic . '"
') or die('Database error!');
}
mysql_close($db);
?>
The output text of this script (if there is an error) is displayed in the JavaScript alert.
I hope it's working for you now.
This would be help ful for you
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<script type="text/javascript">
function validateText(event){
var tar_ele = $(event.target);
if(tar_ele.val() is not valid)
tar_ele.focus();
}
</script>
<input type="text" name="Tue[]" onblur="validateText(event)"/>
javascript text box array and get values and focus on particular field

Categories

Resources