Vaule javascript to php echo - javascript

<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.

Related

Reset dropdown menu using checkbox PHP and Javascript

I have a function called cek2(). The function works like this, if checkbox is not checked it will reset the dropdown menu.
Here is my code.
This is my PHP code.
<?php
while ($r = mysql_fetch_array($sql)) {
echo "<tbody><td>Apakah <b>$r[nama_kriteria]</b> mobil sangat penting bagi anda?</td><td>"
. "<select disabled id='bobot' name='bobot[]' class='bobot'>"
. "<option id='kosong' value=0 hidden selected> Pilih Bobot</option>"
. "<option value=1> Sangat Tidak Penting </option>"
. "<option value=2> Tidak Penting </option>"
. "<option value=3> Cukup Penting </option>"
. "<option value=4> Penting </option>"
. "<option value=5> Sangat Penting </option>"
. "</select>"
. "<td><input type='checkbox' class='kriteria' id='kriteria' name='kriteria[]' onClick='cek();cek2();'</td>"
. "</tbody>";
}
?>
This is my Javascript code.
function cek2() {
var x = document.getElementsByName('kriteria[]');
var y = document.getElementsByName('bobot[]');
var y2 = document.getElementById('kosong').selected = "true";
n = x.length;
for (var i = 0; i < n; i++) {
y[i].y2 = !x[i].checked;
}
}
EDIT
I just find a simple solution. Here is my code.
function cek2() {
var x = document.getElementsByName('kriteria[]');
var y = document.getElementsByName('bobot[]');
n = x.length;
for (var i = 0; i < n; i++) {
if (!x[i].checked) {
y[i].selectedIndex = "0";
}
}
}
function cek2() {
var x = document.getElementsByName('kriteria[]'); // will give checkbox
var y = document.getElementsByName('bobot[]');
var y2 = document.getElementById('kosong').selected = "true";
n = x.length; // you have only one checkbox with name 'kriteria[]' hence length is 1 , valueof n ==1
for (var i = 0; i < n; i++) { // for (var i=0 ; i< 1 ; i++)
y[i].y2 = !x[i].checked; // Hence loop will run only once
}
}

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:

how to write javascript code within php

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.

Checking times with regular expressions

I have the following function:
function calcTotal(event)
{var myId = event.currentTarget.id;
myId = myId.replace(/[^0-9]/g, '');
var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
if($('#start'+myId).val().match(timeRegex) && $('#end'+myId).val().match(timeRegex) && $('#pause'+myId).val().match(timeRegex))
{ alert('win');
var minutes = 0;
var n = $('#end'+myId).val().split(':');
minutes = parseInt(n[0])*60 + parseInt(n[1]);
var n = $('#start'+myId).val().split(':');
minutes -= parseInt(n[0])*60 + parseInt(n[1]);
var n = $('#pause'+myId).val().split(':');
minutes -= parseInt(n[0])*60 + parseInt(n[1]);
var hours = Math.floor(minutes/60);
minutes = minutes % 60;
alert(hours + ':' + minutes);
$('#total' + myId).val(hours + ':' + minutes);
}
else
{ alert('fail');
$('#total' + myId).val('00:00');
}
}
</script>
Let's assume myID equals 1 and the lets assume the following values:
start1 = 00:00
end1 = 10:00
pause1 = 02:00
I would like to for this function to match the previous three values to a regular expression to determine if they are valid times.
After that I would like to calculate the total time worked that day: end1-start1-pause1.
For some reason even with these correct values the function nevers enters the if(....){ alert('win')...}.
I think there is something wrong with my regex, but I already checked (stackoverflow question) and used that regex.
Could anybody tell me what I am doing wrong?
the entire code:
<?php
if(isset($_POST['date']))
{ $sql = "INSERT INTO `hour_administration`.`hours` (`h_id`, `date`, `start`, `end`) VALUES";
foreach($_POST['date'] as $k => $v)
{
if(empty($_POST['date'][$k]))
break;
if($k > 0)
$sql .= ",";
$sql .= "(NULL, '".$_POST['date'][$k]."', '".$_POST['start_time'][$k].":00', '".$_POST ['end_time'][$k].":00')";
}
$sql .= ";";
echo " Query: ".$sql. "</BR>";
mysql_query($sql) or die('Could not query: ' . mysql_error());
}
if(isset($_POST['rows']))
{
$rows = $_POST['rows'];
}else
{
$rows = 5;
}
?>
<script>
$(document).ready(function() {
$( ".date" ).datepicker({ dateFormat: "yy-mm-dd" });
$(".time").mask("99:99");
$('.start_time').change(function(e) {
calcTotal(e);
});
$('.end_time').change(function(e) {
calcTotal(e);
});
$('.pause').change(function(e) {
calcTotal(e);
});
});
function calcTotal(event)
{ var myId = event.currentTarget.id;
myId = myId.replace(/[^0-9]/g, '');
var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
if($('#start'+myId).val().match(timeRegex) && $('#end'+myId).val().match(timeRegex) && $('#pause'+myId).val().match(timeRegex))
{
var minutes = 0;
var n = $('#end'+myId).val().split(':');
minutes = parseInt(n[0])*60 + parseInt(n[1]);
var n = $('#start'+myId).val().split(':');
minutes -= parseInt(n[0])*60 + parseInt(n[1]);
var n = $('#pause'+myId).val().split(':');
minutes -= parseInt(n[0])*60 + parseInt(n[1]);
var hours = Math.floor(minutes/60);
minutes = minutes % 60;
alert(hours + ':' + minutes);
$('#total' + myId).val(hours + ':' + minutes);
}
else
{ alert($('#start'+myId).val());
$('#total' + myId).val('00:00');
}
}
</script>
<div class="inner_container">
<form name="input" method="POST" id="input">
<table border="1">
<tr>
<td>Date</td>
<td>Start time</td>
<td>End time</td>
<td>Pause</td>
<td>Total</td>
</tr>
<tr>
<?php for($i = 0;$i < $rows;$i++)
{?>
<td><input type="text" class="date" name="date[]" id="start<?php echo $i;?>"></td>
<td><input type="text" class="start_time time" name="start_time[]" id="start<?php echo $i;?>"></td>
<td><input type="text" class="end_time time" name="end_time[]" id="end<?php echo $i;?>" ></td>
<td><input type="text" class="pause time" name="pause[] " id="pause<?php echo $i;?>"></td>
<td><input type="text" class="total" name="total[]" id="total<?php echo $i;?>"></td>
</tr>
<?php }?>
</table>
<input type="submit" id="submit_inner_container"value="Submit">
</form>
<form name="amount" method="POST">
<label for="name">How many rows would you like?</label>
<input type="text" name="rows" size="3" id="rows" value="<?php echo $rows; ?>"/>
<input type="submit" value="Rows"
</form>
</div>
Your HTML shows that you have two input fields with the same id attribute:
<td><input type="text" class="date" name="date[]" id="start<?php echo $i;?>"></td>
<td><input type="text" class="start_time time" name="start_time[]" id="start<?php echo $i;?>"></td>
Should the first one here use "date" instead of "start"?
var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
timeRegex.test('00:00') // true
timeRegex.test('10:00') // true
timeRegex.test('02:00') // true
Meaning your problem is not with the regex, and I do not see a problem with the if statement. The problem must be with either the selector, or the value in the text box. I would look for whitespace or other characters coming through in the val.
The regex is working fine.
See this jsfiddle
var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
var start = "00:00"
var end = "10:00"
var pause = "02:00"
if(start.match(timeRegex) && end.match(timeRegex) && pause.match(timeRegex))
{
alert('win');
}
else
{
alert('fail');
}
Please post your HTML code that your selectors are accessing, if you want more of an answer

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