Ajax POST function returning the same result - javascript

I just encountered a problem trying to populate two dropdown selection menus using jQuery, Ajax and php. The code keeps loading the same value from database even if a different option is selected from the dropdown menu. Here is a snippet of the code
test.html
<html>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<body>
<form method="post" action="self.php">
<table>
<tr>
<td><div><label><strong>class:</strong></label></div></td>
<td><div><select name="class_id" id="class_id_0">
<option value="" selected>Select a Class</option>
<option value="1">Nursery</option>
<option value="2">Primary</option>
<option value="3">Secondary</option>
</select></div></td>
</tr>
<tr>
<td><div><label><strong>Sub-Class:</strong></label></div></td>
<td><div><select name="sub_class_id" id="sub_class_id_0">
<option value="">Select a Sub - Class</option>
</select></div></td>
</tr>
<tr>
<td><div><label><strong>Subject:</strong></label></div></td>
<td><div><select name="subject_id" id="subject_id_0">
<option value="">Select a Subject</option>
</select></div></td>
</tr>
</table>
</form>
</body>
</html>
JQuery
<script>
(function($){
$("#class_id_0").change(function(){
var str = "";
var type = "sub_class";
$( "#class_id_0 option:selected" ).each(function() {
str += $( this ).val() + " ";
});
$.post( "data.php",{class_id:parseInt(str),type:""+type}).done(function(data){
alert(str);
alert( "Data Loaded:" + data );
$("#sub_class_id_0").html(data);
});
});
$("#sub_class_id_0").change(function(){
var str = "";
var type = "subject";
$( "#sub_class_id_0 option:selected" ).each(function() {
str += $( this ).val() + " ";
});
$.post( "data.php",{sub_class_id:parseInt(str),type:""+type}).done(function(data){
alert(str);
alert( "Data Loaded:" + data );
$("#subject_id_0").html(data);
});
});
})(jQuery);
</script>
data.php
<?php
$options = "";
$query = "";
$type = isset($_REQUEST["type"]);
switch($type){
case "sub_class":
$sub_class_id = intval($_REQUEST["sub_class_id"]);
$default_value = "";
$default_text = "Select a Sub - Class";
$options = "<option value='".$default_value."'>".$default_text."</option>";
if($class_id == "" || $class_id == 0)
{
$options = "<option value = >Select a Class First</option>";
}
$con = mysql_connect('localhost', 'root', '');
$database = mysql_select_db('admin_glisten');
$sql="SELECT sub_class_id,sub_class FROM sub_class WHERE class_id = '".$class_id."'";
$result = mysql_query($sql);
if (!$result) {
die("Query failed: " . mysql_error());
}
while ($row = mysql_fetch_assoc($result)) {
$options .= "<option value='".$row['sub_class_id']."'>".$row['sub_class']."</option>";
}
echo $options;
mysql_close($con);
break;
case "subject":
$sub_class_id = intval($_REQUEST["sub_class_id"]);
$default_value = "";
$default_text = "Select a Subject";
$options = "<option value='".$default_value."'>".$default_text."</option>";
if($sub_class_id == "" || $sub_class_id == 0)
{
$options = "<option value = >Select a Sub - Class First</option>";
}
$con = mysql_connect('localhost', 'root', '');
$database = mysql_select_db('admin_glisten');
$sql="SELECT subject_scheduler.subject_id,subject.subject_id,subject.name FROM subject_scheduler INNER JOIN subject ON subject_scheduler.subject_id=subject.subject_id WHERE sub_class_id = '".$sub_class_id."'";
$result = mysql_query($sql);
if (!$result) {
die("Query failed: " . mysql_error());
}
while ($row = mysql_fetch_assoc($result)) {
$options .= "<option value='".$row['subject_id']."'>".$row['name']."</option>";
}
echo $options;
mysql_close($con);
break;
default:
}
?>
PS
Never mind my insecure code am just trying to get it to work. Any help will be gratefully appreciated, as i have been on this for the past couple of hours now.

You are using $class_id variable to query the database, but $class_id is always going to be the same. Here is why:
On line 4 of PHP code
$class_id = intval(isset($_REQUEST["class_id"]));
Intval returns an integer, which is fine, however, you are also calling isset, which returns a boolean. In most cases isset results in true and then intval results in 1.
So in fact your query is always:
SELECT sub_class_id,sub_class FROM sub_class WHERE class_id = '1';

Related

Get value from select input in AJAX/PHP retrieved innerhtml for form submit

I'm new to the AJAX thing, but seems fairly simple. I have a form page that has a select input, when the user selects a certain option, the AJAX populates an innerhtml div with the timeslot.php. The timeslot.php has another dynamically created select input with the options that are populated from a Mysql database. My problem is getting the value back to the form page so when the user clicks submit, that value (hidden input) is included in the submit. I figured it would be pretty straight forward, but what I have does not work. Any help with this would be appreciated.
HTML form:
<?php
$omitDay = 'Sunday'; //Sunday is a permanant day off from curbside service
if ('17:00:00' <= date("H:i:s")){ //ADDED date("H:i:s", strtotime(time()))
$start = date("Y-m-d", strtotime("+1 day", strtotime(date("Y-m-d"))));
} else {
$start = date("Y-m-d");
}
$end = date("Y-m-d", strtotime("+6 day", strtotime(date("Y-m-d"))));
?>
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
var timeslotvalue = document.getElementByID("timeslot").value;
alert(timeslotvalue);
}
};
xmlhttp.open("GET","timeslot.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<div style="clear:both; margin-bottom: 20px;">
<input type="hidden" name="timeslot"> Javascript value from Timeslot select </input>
<select name="users" onchange="showUser(this.value)"><option value="">Select a Pickup Day</option>
<?php
$datediff = strtotime($end) - strtotime($start);
$datediff = floor($datediff/(60*60*24));
for($i = 0; $i < $datediff + 1; $i++){
$todaysDate = date("l, F d", strtotime($start . '+' . $i . 'day'));
$day = date('l', strtotime($start . '+' . $i . 'day'));
if($day != $omitDay) {
echo '<option value="' . strtotime($todaysDate) .'">'. $todaysDate . '</option>';
}
}
?>
</select>
</div>
</form>
<br>
<div id="txtHint">Select goes here</div>
</body>
</html>
This is my php file with select input (I do not have the SQL database in this code, not the issue)
<?php
date_default_timezone_set('America/New_York');
$startTime = time() + (60 * 60 * 4
);
$timeIncrements = array('08:15:00','08:20:00','08:25:00','08:30:00','08:35:00','08:40:00','08:45:00','08:50:00','08:55:00','09:00:00','09:05:00','09:10:00','09:15:00','09:20:00','09:25:00','09:30:00','09:35:00','09:40:00','09:45:00',
'09:50:00','09:55:00','10:00:00','10:05:00','10:10:00','10:15:00','10:20:00','10:25:00','10:30:00','10:35:00','10:40:00','10:45:00','10:50:00','10:55:00','11:00:00','11:05:00','11:10:00','11:15:00','11:20:00','11:25:00','11:30:00',
'11:35:00','11:40:00','11:45:00','11:50:00','11:55:00','13:00:00','13:05:00','13:10:00','13:15:00','13:20:00','13:25:00','13:30:00','13:35:00','13:40:00','13:45:00','13:50:00','13:55:00','14:00:00','14:05:00','14:10:00','14:15:00',
'14:20:00','14:25:00','14:30:00','14:35:00','14:40:00','14:45:00','14:50:00','14:55:00','15:00:00','15:05:00','15:10:00','15:15:00','15:20:00','15:25:00','15:30:00','15:35:00','15:40:00','15:45:00','15:50:00','15:55:00','16:00:00',
'16:05:00','16:10:00','16:15:00','16:20:00','16:25:00','16:30:00','16:35:00','16:40:00','16:45:00','16:50:00','16:55:00');
$omitTime = array('08:25:00'); // to be pulled from database as users select their timeslot and it's saved
$timeIncrements = array_diff( $timeIncrements, $omitTime ); // takes out the omitted times
$q = $_GET['q'] . '<br />';
// Database select here
echo '<select name="timeslot" id="timeslot"><option value="">Select a Pickup Time</option>';
foreach ($timeIncrements as $timeslot) {
if ($startTime <= strtotime($timeslot)) { //starttime = 0000000000 /timeslot = 00:00:00
echo '<option value="' . date("h:i a", strtotime($timeslot)) .'">'. date("h:i a", strtotime($timeslot)) . '</option>';
}
}
echo '</select>';
?>

How to put validation on a dynamic dropdown when inserting in PHP?

I'm constructing a survey and I have a textbox that generates dynamic dropdowns based on user input which displays the same data.
This is the script
<script>
function load_questions(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php??main=1&subcategory="+document.getElementById("subcategorydd").value +"&cnt="+document.getElementById("q_num").value,false);
xmlhttp.send(null);
document.getElementById("question").innerHTML=xmlhttp.responseText;
}
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
</script>
This is the insert code when I'm creating the survey
<?php
$con = mysqli_connect("localhost","root","","imetrics");
if(isset($_POST['submit'])){
$title = $_POST['surveytitle'];
$catdd = $_POST['catdd'];
$subcatdd = $_POST['subcatdd'];
$gender = $_POST['gender'];
$age = $_POST['age'];
$occupation = $_POST['occupation'];
$occupationtwo = $_POST['occupdd'];
$relstatus = $_POST['relationshipstatus'];
$q_num = $_POST['q_num'];
$insert = mysqli_query($con, "INSERT INTO `surveyform` (`surveytitle`,`surveycategory`,`surveysubcategory`,`gender`,`age`,`occupation`,`occupation_status`,`status`) VALUES ('$title','$catdd','$subcatdd','$gender','$age','$occupation','$occupationtwo','$relstatus')");
if(!$insert){
echo mysqli_errno();
}
else{
$getMaxID = mysqli_query($con, "SELECT MAX(survey_id) as maxid FROM surveyform");
$row_2 = mysqli_fetch_array($getMaxID);
$survey_id = $row_2[0];
for( $a = 1; $a <= $q_num; $a++)
{
mysqli_query($con, "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")");
//echo "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")";
}
echo '<script language="javascript">';
echo 'alert("Survey Created!")';
echo '</script>';
}
}
?>
And this is my dropdown code
if($question !="" && $cnt!="" && $addQues!="yes" && $main != 1){
$i = 0;
for ($i = 1; $i <= $cnt; $i++)
{
$query=mysqli_query($con, "SELECT * FROM question WHERE question_subcat = $question ");
echo "<b>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control-static' name='question_dropdowns".$i."'>";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
}
echo "</select>";
echo "<br />";
}
echo "<div id='insertQuesHere".$i."'></div>";
echo "<a href='#add_question' onclick='return addQues();'>Add Question</a>";
}
here's my submit button
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
What's the validation code that will prevent me from inserting if the data chosen from the dropdown is the same? For example I generated 2 dropdowns and I chose the same datas from the dropdown, what's the validation code for it?
Please call checkValues method your submit button click
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
checkValues method below :
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
Also , you can see an example Example

Increment a Formatted Code in PHP

I have a code format for every category selected from the drop down menu.
Say for Category A, the code to be retrieved in the textbox is "A - 1001" and for Category B, "B - 2003". My problem is that I can't increment the code into "A - 1002" for category A, for example because it's already read as string.
How can I retrieve a formatted code from the database which will increment its value?
Here's my code for the selection of category and for the retrieval of the code:
Category:
<script type="text/javascript">
function GetSelected (selectTag) {
var selIndexes = "";
for (var i = 0; i < selectTag.options.length; i++) {
var optionTag = selectTag.options[i];
if (optionTag.selected) {
if (selIndexes.length > 0)
selIndexes += ", ";
selIndexes = optionTag.value;
}
}
var info = document.getElementById ("viocode");
if (selIndexes.length > 0) {
viocode.innerHTML = selIndexes;
}
else {
info.innerHTML = "There is no selected option";
}
}
</script>
<select option="single" name= "viocat" id="viocat" onchange="GetSelected (this);" class = "form-control">
<option>Choose category ...</option>
<option value="
<?php
$con = ...
$sql = "SELECTcategory, MAX(code) AS highest_id FROM tbl_name where category = 1";
$result = mysql_query ($sql,$con);
while($row = mysql_fetch_array($result))
{
$i = $row['highest_id'];
$i++;
echo "A - " .$i;
$cat = 1;
}
?>">DlR</option>
<option value="
<?php
$con = ...
$sql = "SELECT category, MAX(code) AS highest_id FROM tbl_name where category = 2";
$result = mysql_query ($sql,$con);
while($row = mysql_fetch_array($result))
{
$i = $row['highest_id'];
$i++;
echo "B - " .$i;
$cat = 2;
}
?>">B</option>
<option value="
<?php
$con = ...
$sql = "SELECT category, MAX(code) AS highest_id FROM tbl_name where category = 3";
$result = mysql_query ($sql,$con);
while($row = mysql_fetch_array($result))
{
$i = $row['highest_id'];
$i++;
echo "C - " .$i;
$cat = 3;
}
?>">C</option>
</select>
And here's the codes for the textbox where the formatted code is to be displayed:
Violation Code:
<strong><text type= "text" id="viocode" name="viocode" />
If I understand it correctly, you need to increment a number ($i), from $row['highest_id'].
The extra line will try to parse the $row['highest_id'] as an int, then your code uses it, and the last line of the while loop increments $i with 1.
while($row = mysql_fetch_array($result))
{
$i = intval($row['highest_id']);
//$i = $row['highest_id'];
echo "A - " .$i;
$cat = 1;
$i++;
}
Try parsing your variable to integer.
Instead of using $row['highest_id']
use: $i = intval($row['highest_id'];

How to change the name, but not the value of a dynamically filled select list?

I have a select list that is dynamically filled with data from my database. But I don't want the users to see the real column names, so I created a extra column in my database called column_alias. What I want, is to show the column_alias names in the dropdown but keep the real values of column names.
This is how I'm filling the select list with the real column names at the moment:
function loadTables() {
$.getJSON("dropdown_code/get_tables.php", success = function(data)
{
console.log('inside callback');
var optionsTables = "";
for(var i = 0; i < data.length; i++)
{
optionsTables += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#slctTable").append(optionsTables);
$("#slctTable").change();
});
}
And this is the code that get's the data outof my database:
<?PHP
require "opendb.php";
$query = "select table_name
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
while ($row = pg_fetch_array($data))
{
array_push($table_names, $row["table_name"]);
}
echo json_encode($table_names);
require "closedb.php";
?>
Update
This is what my database table looks like:
So I want the table_alias to be visible in my select list, but I want the value to be table_name so it can interact with my database.
Firstly you will need to fetch the alias as well from the database.Change your server side code to the following.
<?PHP
require "opendb.php";
$query = "select table_name,table_alias
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
while ($row = pg_fetch_array($data))
{
array_push($table_names, $row);
}
echo json_encode($table_names);
require "closedb.php";
?>
Then in your client side code simply output the table_alias as option name and table_name as option value.
function loadTables() {
$.getJSON("dropdown_code/get_tables.php", success = function(data)
{
console.log('inside callback');
var optionsTables = "";
for(var i = 0; i < data.length; i++)
{
optionsTables += "<option value='" + data[i]['table_name'] + "'>" + data[i]['table_alias'] + "</option>";
}
$("#slctTable").append(optionsTables);
$("#slctTable").change();
});
}
html
<select id="xoxo_select">
<option value="foo_value">foo</option>
<option value="xoxo_value">xoxo</option>
</select>
js
$('#xoxo_select option[value="xoxo_value"]').text('bar'); // change name of option
$('#xoxo_select option[value="xoxo_value"]').attr('value', 'bar_value'); // change value of option
jsfiddle https://jsfiddle.net/tg126u7g/
Change in fetch data from DB:
<?PHP
require "opendb.php";
$query = "select table_name,table_alis
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
$i=0;
while ($row = pg_fetch_array($data))
{
array_push($table_names[$i], $row["table_name"]);
$i++;
}
echo json_encode($table_names);
require "closedb.php";
?>
Then Change in javascript code:
optionsTables += "<option value='" + data[i][0] + "'>" + data[i][1] + "</option>";

Why php code inside the javascript cannot change the value of innerHTML? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 8 years ago.
This page include two web page, insert6.php is using iframe.
This full code of the web site of the page.
form6.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5" />
<title>CCC</title>
<style>
#tlist tr:last-child td {
background-color:#CCCCCC;
}
table{
table-layout: fixed;
}
th, td {
overflow: hidden;
}
#container
{
margin-left:auto;
margin-right:auto;
width:600px;
}
</style>
</head>
<body>
<h3>New Record</h3>
<script language="JavaScript" type="text/javascript">
function addRowToTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// left cell
var cellLeft = row.insertCell(0);
var che = document.createElement('input');
che.type = 'checkbox';
che.id = 'op'+ iteration;
che.name= 'checkbox';
cellLeft.appendChild(che);
// right cell
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.name = 'txtRow[]';
el.id = 'txtRow' + iteration;
el.size = 40;
el.onkeypress = keyPressTest;
cellRight.appendChild(el);
// select cell
var cellRightSel = row.insertCell(2);
var sel = document.createElement('select');
//sel.type = 'text';
sel.name = 'selRow[]';
sel.id = 'selRow' + iteration;
sel.options[0]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="FF")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
sel.options[1]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="DD")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
sel.options[2]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="TT")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
sel.options[3]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="GG")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
sel.options[4]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="RR")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
sel.options[5]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="AA")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
cellRightSel.appendChild(sel);
}
function keyPressTest(e, obj)
{
var validateChkb = document.getElementById('chkValidateOnKeyPress');
if (validateChkb.checked) {
var displayObj = document.getElementById('spanOutput');
var key;
if(window.event) {
key = window.event.keyCode;
}
else if(e.which) {
key = e.which;
}
var objId;
if (obj != null) {
objId = obj.id;
} else {
objId = this.id;
}
displayObj.innerHTML = objId + ' : ' + String.fromCharCode(key);
}
}
function openInNewWindow(frm)
{
// open a blank window
var aWindow = window.open('', 'TableAddRowNewWindow',
'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
// set the target to the blank window
frm.target = 'TableAddRowNewWindow';
// submit
frm.submit();
}
function validateRow(frm)
{
var chkb = document.getElementById('chkValidate');
if (chkb.checked) {
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length - 1;
var i;
for (i=1; i<=lastRow; i++) {
var aRow = document.getElementById('txtRow' + i);
if (aRow.value.length <= 0) {
alert('Row ' + i + ' is empty');
return;
}
}
}
openInNewWindow(frm);
}
function deleteAll(obj){
var checked = document.getElementsByName(obj);
debugger
for(var i = 0; i < checked.length; i ++){
if(checked[i].checked){
var tr=checked[i].parentNode.parentNode;
var tbody=tr.parentNode;
tbody.removeChild(tr);
i--;
}
}
}
</script>
<!--Input Data-->
<form action="insert6.php" method="post" target="myframe">
Series:
<?php
function series(){
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT Series_NAME FROM series;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
echo("<option>".$row[$i]."</option>");
}
}
mysql_free_result($result);
}
?>
<select name="choose series">
<?php series(); ?>
</select><br>
<?php
function height(){
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT height FROM width_height GROUP BY height;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
echo("<option>".$row[$i]."</option>");
}
}
mysql_free_result($result);
}
?>
<p>Height(MM):
<select name="height" id="height0">
<?php height(); ?>
</select></p>
<?php
function width(){
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT width FROM width_height GROUP BY width;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
echo("<option>".$row[$i]."</option>");
}
}
mysql_free_result($result);
}
?>
<p>Width (MM):
<select name="width" id="width0">
<option><?php width(); ?></option>
</select><br>
<table border="1" id="tblSample">
<tr>
<td><input type="checkbox" id="op0" name="checkbox">
</td>
<td><input type="text" name="txtRow[]"
id="txtRow0" size="40"/></td>
<td>
<select name="selRow[]" id="selRow0">
<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
echo("<option>".$row[$i]."</option>");
}
}
mysql_free_result($result);
?>
</select>
</td>
</tr>
</table>
<input type="button" value="Add" onClick="addRowToTable();" />
<input type="button" name="delete_button" value="Delete" onClick="deleteAll('checkbox');" />
<input type="submit" name="submit" value="Submit" onclick="test();"/>
</form>
<script src="https://dl.dropboxusercontent.com/u/19096175/blog/selectDate/selectDate.js" type="text/javascript"></script>
Choose Dateļ¼š<input onfocus="HS_setDate(this)" readonly="" type="text" value="Check" />
<br />
<hr/>
<iframe src="insert6.php" name="myframe" id="myframe" width="650" height="400" scrolling="no" frameborder="0">
</iframe>
</body>
</html>
This full code of the web site of the page.
insert6.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DDD</title>
<style>
#tlist tr:last-child td {
background-color:#CCCCCC;
}
table{
table-layout: fixed;
}
th, td {
overflow: hidden;
}
#container
{
margin-left:auto;
margin-right:auto;
width:600px;
}
</style>
</head>
<body>
<?php
/*
$name = $_POST['selRow'];
$qty = $_POST['txtRow'];
foreach( $qty as $v ) {
print $v."<br>";
}
foreach( $name as $v ) {
print $v."<br>";
}
*/
?>
<script>
function delrecord(obj)
{
obj.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode);
var delbutton=document.getElementsByName("del");
var newzum=0;
for(var j=1;j <document.getElementsByName("del").length+1;j++)
{
newzum+=parseFloat(document.getElementById('total'+j).innerHTML);
}
znum.innerHTML =newzum;
}
function caltotal(e){
var fqty=document.getElementById('qty' +iteration);
var fprice=document.getElementById('price' + iteration);
var ftotal=document.getElementById('total'+ iteration);
var delbutton=document.getElementsByName("del");
ftotal.innerHTML= fqty.innerHTML * fprice.innerHTML;
newzum =0;
for(var j=1;j <=document.getElementsByName("del").length;j++)
{
newzum += parseFloat(document.getElementById('total'+j).innerHTML);
}
znum.innerHTML = newzum;
}
</script>
<div class="container">
<table width="450" border="0" cellspacing="1" cellpadding="0" class="tb" id="tlist">
<tr class="tit2">
<td>QTY </td>
<td>TILE </td>
<td>HEIGHT </td>
<td>WIDTH </td>
<td>PRICE </td>
<td>TOTAL </td>
<td>Action </td>
</tr>
<tr class="tit3">
<?php
if(isset($_POST["submit"])){
$t=count($_POST['selRow']);
$w=count($_POST['txtRow']);
for($i=0;$i<$t;$i++)
{
$qty[$i]= $_POST['txtRow'][$i];
$tile[$i]= $_POST['selRow'][$i];
$height = $_POST['height'];
$width = $_POST['width'];
echo "<tr class='tit3'><td>";
echo "".$qty[$i]."<br>";
echo "</td>";
echo "<td>";
echo "".$tile[$i]."<br>";
echo "</td>";
echo "<td>";
echo "".$height."<br>";
echo "</td>";
echo "<td>";
echo "".$width."<br>";
echo "</td>";
echo "<td>";
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
//foreach($_POST['selRow'] as $tile){
$query = "SELECT `Price` FROM `actualpanelmaterialsize` WHERE `Material ID` IN (SELECT `Material_ID` FROM `material` WHERE `Tile` = '".$tile[$i]."') AND `Width_Height ID` IN (SELECT `Width_Height ID` FROM `width_height` WHERE `Width` =".$_POST['width']." AND `Height` =".$_POST['height'].");";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
$price = $row[0];
echo $price."<br>";
}
//}
echo "</td>";
echo "<td id='total[$i]'>";
echo $total[$i]=$price*$qty[$i];
echo "</td>";
echo "<td>";
echo "<input type='button' value='Delete' name='del' onclick='delrecord(this);'>";
echo "</td>";
echo "</tr>";
}
echo "<script>";
echo "newzum =0;";
echo "for(var j=0;j <=document.getElementsByName('del').length+1;j++) {" ;
echo "for (var i=0;i<=document.getElementById('total['+i+']').innerHTML.length;i++){";
echo "newzum += parseFloat(document.getElementById('total['+i+']').innerHTML);";
echo "}";
echo "}";
echo "document.getElementById('znum').innerHTML = newzum;";
echo "</script>";
}
?>
</tr>
<tr class="tit3"> <td>Total </td> <td colspan=3> </td> <td colspan=2 align='right'> <b id="znum">0</b> </td> <td colspan=1> </td> </tr>
</table>
<script>
/*
for (var i=0;i<=document.getElementById("total["+i+"]").innerHTML.length;i++){
window.alert(document.getElementById("total["+i+"]").innerHTML);
}
*/
function Check(){
for (var i=0;i<=document.getElementById("total["+i+"]").innerHTML.length;i++){
window.alert(newzum);
}
}
</script>
<input type="button" value="Check" onClick="Check();"/>
</div>
</body>
</html>
Last, I was ask you guys about why znum.innerHTML cannot change the value.
Now, I put the javascript code inside the php language, the result still wrong...
My expected result:
Now I see the result:
After click the Check button to see newznum is correct but znum.innerHTML could not change this value
When pass the form to insert6.php, the total should be change the value.
Now, I cannot do it.
Anyone see the problem here?
Please you help me, I dun know where i get a mistake.
Thank you for reading my question!
I hope i will received the answer to help me to solve the problem
At first, Separation of logic is very important and what i see frmo your code is you are making DB calls from your view itself. Which shows poor way of coding. It will make it difficult to manager your code.
sel.options[0]= new Option("<?php
mysql_connect("localhost", "root", "root") or
die("Could not connect: " . mysql_error());
mysql_select_db("partition");
$query = "SELECT tile FROM material ORDER BY `material`.`Material_ID` ASC ;";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_data_seek($result,0);
while ($row=mysql_fetch_row($result))
{
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if ($row[$i]=="FF")
echo($row[$i]);
}
}
mysql_free_result($result);
?>");
Now answer to your question:
echo "newzum =0;";
echo "for(var j=0;j <=document.getElementsByName('del').length+1;j++) {" ;
echo "for (var i=0;i<=document.getElementById('total['+i+']').innerHTML.length;i++){";
echo "newzum += parseFloat(document.getElementById('total['+i+']').innerHTML);";
echo "}";
echo "}";
echo "document.getElementById('znum').innerHTML = newzum;";
echo "</script>";
This lines of code will be executed before the page is loaded as its php.
as a result, when the page is rendered the script will not find document.getElementsByName('del') so it will throw undefined error.
To overcome this, Do those actions in onload function.
window.onload = function() {
// Inside this method put those lines. It will work.
}
Your code is too long, but I will try to answer from your title.
You must understand how php and javascript work. php is a server-side language, while javascript is a client side language. You can NOT execute php inside javascript. php does the processing on the server and then returns the results to the client. After this, the server is not aware of the client state.
In order to change the value of innerHTML, you can just use javascript. If you need to somehow interact with php, you should send AJAX calls to the server, where the php script can process and return new data.
The PHP will just echo the Javascript code, which is fine, but needlessly complex. You can just enter the Javascript code in the page.
The actual problem right now is this line:
document.getElementById('znum').innerHTML = newzum;
It is a line of Javascript in the global scope, and it will be executed as soon as the browser encounters it during the loading of the page.
But the element is should modify ('znum') is a couple of lines lower on the page:
<b id="znum">0</b>
That basically means that the element is not ready yet when the script is executed, so it cannot be found.
The solution is relatively simple: Execute the Javascript later (at the bottom) of the page, so it will execute when all relevant elements are already loaded.
Script errors like this result in an error or a warning which should be visible in the Console tab in the developer tools (F12) of your browser. So make sure you always look at that when debugging Javascript. It's really a tool you should master as a web developer. :)

Categories

Resources