PDA

View Full Version : Ajax and DOM



Farree
08-05-2010, 09:37 PM
I am trying to Add rows to my table through DOM. I have two drop downs and one text field in one row. One drop down is populated from database and the second drop down is populated through Ajax after selecting value from first drop down. As far as one row is concerned it is doing good but when I add another row through DOM the values of second drop down of that row doesn't change, instead it change the values of second drop down of the first row. I am new to DOM and Ajax and totally lost what should I do to solve the problem.

jscheuer1
08-05-2010, 11:48 PM
Please provide your code or a link to the page where you are having this problem.

Farree
08-05-2010, 11:55 PM
function ajaxpage(category, containerid)
{
var strURL="getSourceList.php?category_name="+category;
var req = false;

if (window.XMLHttpRequest) // if Mozilla, Safari etc
req = new XMLHttpRequest();
else if (window.ActiveXObject)
{ // if IE
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
else
return false;

req.onreadystatechange=function()
{
loadpage(req, containerid);
}
req.open('GET', strURL, true);
req.send(null);
}

function loadpage(req, containerid)
{
if (req.readyState == 4 && (req.status==200))
document.getElementById(containerid).innerHTML = req.responseText;
}

function addRowToTable() {

var iTable = document.getElementById('addIncomeTable');
var rowNo = iTable.rows.length;
var iteration = rowNo;
var row = iTable.insertRow(-1);

/* Adding left most td */
var textCell = row.insertCell(0);
var textNode = document.createTextNode(iteration);
textCell.appendChild(textNode);

/* Adding category select box */
categoryCell = row.insertCell(1);
var categorySelect = document.createElement('select');
categorySelect.name = 'category_name' + iteration;
categorySelect.id = 'category_name' + iteration;
rowName = 'sourcediv' + iteration;

categorySelect.options[0] = new Option('-- <?php echo 'Select Category Name'; ?> --', '-1');
<?php
for($i=1; $i<=$categoryCount; $i++)
{
$record = mysql_fetch_array($result);
?>
categorySelect.options[<?php echo $i ?>] = new Option('<?php echo $record['description']; ?>', '<?php echo $record['description']; ?>');
<?php
}
?>
categorySelect.setAttribute("onChange", "ajaxpage(this.value, 'sourcediv')");
categoryCell.appendChild(categorySelect);

/* Adding source select box */
sourceCell = row.insertCell(2);
var sourceRow = document.createElement('tr');
sourceRow.name = 'sourcediv' + iteration;
var sourceSelect = document.createElement('select');
sourceSelect.name = 'source' + iteration;
sourceSelect.id = 'source' + iteration;
sourceSelect.options[0] = new Option('-- <?php echo 'Select Category First'; ?> --', '-1');
sourceRow.appendChild(sourceSelect);
sourceCell.appendChild(sourceRow);


/* Adding input box */
amountCell = row.insertCell(3);
var amountInput = document.createElement('input');
amountInput.type = 'text';
amountInput.name = 'amount'+ iteration;
amountInput.id = 'amount' + iteration;
amountCell.appendChild(amountInput);
}


Here's the HTML code:


<td>
<select id="category_name-<?php echo $k; ?>" name="category_name-<?php echo $k; ?>" onchange="ajaxpage(this.value, 'sourcediv')">
<option value="-1" selected="selected">-- Select Category Name --</option>
<?php
//Create query
$query1 = "SELECT * FROM ss_income_category ORDER BY icategory_id";
$result1 = mysql_query($query1);

while($row1 = mysql_fetch_array($result1))
{
?>
<option value="<?php echo $row1['description']; ?>">
<?php echo $row1['description'] ?>
</option>
<?php
}
?>
</select>
</td>

<td id="sourcediv">
<select id="source-<?php echo $k; ?>" name="source-<?php echo $k; ?>" >
<option value="-1" selected="selected">-- Select Category First--</option>
</select>
</td>

<td><input type="text" id="amount-<?php echo $k; ?>" name="amount-<?php echo $k; ?>" /></td>

<?php $k++; ?>

jscheuer1
08-07-2010, 05:33 PM
I'm having a little trouble following your code. $k is undefined, though it appears to be a number, other parts are a little less clear. I can tell you that the highlighted parts here:



categorySelect.options[0] = new Option('-- <?php echo 'Select Category Name'; ?> --', '-1');
<?php
for($i=1; $i<=$categoryCount; $i++)
{
$record = mysql_fetch_array($result);
?>
categorySelect.options[<?php echo $i ?>] = new Option('<?php echo $record['description']; ?>', '<?php echo $record['description']; ?>');
<?php
}
?>

Will be set once on page load and cannot change unless the page is reloaded and the values these tokens fetch have changed. In other words, each time the function addRowToTable() is run, they will have the same value as the first time.

However, from the code you show, addRowToTable() is never run.

If it does run, this line:



categorySelect.setAttribute("onChange", "ajaxpage(this.value, 'sourcediv')");

will fail in at least some, if not all browsers. It should be:


categorySelect.onchange = function(){ajaxpage(this.value, 'sourcediv');};

Perhaps more important (since none of the above appears to actually be used), I would point out that you are always referencing 'sourcediv' as the id of the target container, the one that will receive:



function loadpage(req, containerid)
{
if (req.readyState == 4 && (req.status==200))
document.getElementById(containerid).innerHTML = req.responseText;
}

There can (when manipulating elements via javascript) be only one element on the page with this id. If there are more than one, depending upon the browser, it will either throw an error, probably a fatal error (stops script processing), or it will pick the first one it finds and use that.

From what you say, it sounds as though the latter is happening.

Farree
08-07-2010, 05:57 PM
Thanks for the help John. I really appreciate your kind help :)

Yes, you are absolutely right, it picks the first div and add drop down in that div. Can you please help me to solve this problem. Can you please suggest me any solution for it. I'll be very thankful to you. I really tried a lot but it is driving me crazy now. Please suggest me any solution to this problem.

Farree
08-07-2010, 06:07 PM
I am posting the code again with little bit changes as you said. Please review my code and help me to solve my problem



<?php
$query = "SELECT *
FROM ss_income_category
ORDER BY icategory_id";
$result = mysql_query($query);

$categoryCount = mysql_num_rows($result);

?>


Here's the Javascript Code:



<script type="text/javascript">

function ajaxpage(category, containerid)
{
var strURL="getSourceList.php?category_name="+category;
var req = false;

if (window.XMLHttpRequest) // if Mozilla, Safari etc
req = new XMLHttpRequest();
else if (window.ActiveXObject)
{ // if IE
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
else
return false;

req.onreadystatechange=function()
{
loadpage(req, containerid);
}
req.open('GET', strURL, true);
req.send(null);
}

function loadpage(req, containerid)
{
if (req.readyState == 4 && (req.status==200))
document.getElementById(containerid).innerHTML = req.responseText;
}


function addRowToTable() {

var iTable = document.getElementById('addIncomeTable');
var rowNo = iTable.rows.length;
var iteration = rowNo;
var row = iTable.insertRow(-1);

/* Adding left most td */
var textCell = row.insertCell(0);
var textNode = document.createTextNode(iteration);
textCell.appendChild(textNode);

/* Adding category select box */
categoryCell = row.insertCell(1);
var categorySelect = document.createElement('select');
categorySelect.name = 'category_name' + iteration;
categorySelect.id = 'category_name' + iteration;
var rowName = 'sourcediv-' + iteration;

categorySelect.options[0] = new Option('-- <?php echo 'Select Category Name'; ?> --', '-1');
<?php
for($i=1; $i<=$categoryCount; $i++)
{
$record = mysql_fetch_array($result);
?>
categorySelect.options[<?php echo $i ?>] = new Option('<?php echo $record['description']; ?>', '<?php echo $record['description']; ?>');
<?php
}
?>
categorySelect.onchange = function(){ajaxpage(this.value, 'rowName');};
categoryCell.appendChild(categorySelect);

/* Adding source select box */
sourceCell = row.insertCell(2);
var sourceRow = document.createElement('td');
sourceRow.name = 'sourcediv-'+iteration;
var sourceSelect = document.createElement('select');
sourceSelect.name = 'source' + iteration;
sourceSelect.id = 'source' + iteration;
sourceSelect.options[0] = new Option('-- <?php echo 'Select Category First'; ?> --', '-1');
sourceRow.appendChild(sourceSelect);
sourceCell.appendChild(sourceRow);


/* Adding input box */
amountCell = row.insertCell(3);
var amountInput = document.createElement('input');
amountInput.type = 'text';
amountInput.name = 'amount'+ iteration;
amountInput.id = 'amount' + iteration;
amountCell.appendChild(amountInput);
}
</script>


Here, is the html cde:


<body>
<div id="content">
<div id="back">

<?php include("header.php"); ?>


<!-- content begins -->
<div id="main">
<div id="right">
<h3>Add New Income</h3>

<form id="addIncomeForm1" name="addIncomeForm1" method="post" action="">
<div class="tabber" >
<div class="tabbertab">
<h2>Add Income</h2>
<b><font color="#0033CC">Step 1:</font> Please select the income category to add</b><br /><br />

<input name="addRow" type="button" value="Add New Row" class="myFormButton" onclick="addRowToTable()" />

<table id="addIncomeTable" class="myTable">


<tr align='justify'>
<th>&nbsp;</th>
<th>&nbsp;Category Name</th>
<th>&nbsp;Source Name</th>
<th>&nbsp;Amount</th>
</tr>

<tr align='justify' style="background-color:<?php echo $row_color ?>" > <?php $k = 0; ?>
<td><?php echo $k+1; ?></td>
<td>&nbsp;
<select id="category_name-0>" name="category_name-0" onchange="ajaxpage(this.value, 'sourcediv')">
<option value="-1" selected="selected">-- Select Category Name --</option>
<?php
//Create query
$query1 = "SELECT * FROM ss_income_category ORDER BY icategory_id";
$result1 = mysql_query($query1);

while($row1 = mysql_fetch_array($result1))
{
?>
<option value="<?php echo $row1['description']; ?>">
<?php echo $row1['description'] ?>
</option>
<?php
}
?>
</select>
</td>
<td id="sourcediv">&nbsp;
<select id="source-0" name="source-0" >
<option value="-1" selected="selected">-- Select Category First--</option>
</select>
</td>
<td><input type="text" id="amount-0" name="amount-0" /></td>
</tr>
</table>
</div>




<br />
<div align="center">
<input name="btnSave" type="submit" value="Save" class="myFormButton" onClick="return addIncome();" />
<input name="btnReset" type="reset" value="Reset" class="myFormButton" />
<input name="btnCancel" type="button" value="Cancel" class="myFormButton" onClick="window.location.href='show_all_incomes.php';" />
</div>
</div>
</form>
</div>
<?php include("menu.php"); ?>
</div>
</div>
<!--content ends -->


</div>
<!-- footer ends-->
</body>

jscheuer1
08-08-2010, 10:31 AM
OK, now where you have:



categorySelect.onchange = function(){ajaxpage(this.value, 'rowName');};

I don't think you want the literal string 'rowName', rather the value of the earlier declared variable:



var rowName = 'sourcediv-' + iteration;

in which case you should do (without the quotes):


categorySelect.onchange = function(){ajaxpage(this.value, rowName);};

That way you will be propagating/populating a td with a unique id each time.

There could also be other problems, but that should resolve the major issue from my last post.

I say should, because if there is/are other problems, even though using the unquoted variable name is clearly the way to go here, other errors could prevent it from being used/executed.

There are tools that can help you check your work as you go. In any browser you can navigate to the page and use the browser's 'View Source'. This will show you how the PHP code is being resolved. In Firefox with the Web Developer extension (similar tools are available in/for other browsers, but may not always be equivalent), you may also 'View Generated Source'. If you do that after adding a row, it will show you the id of the td, and all of the markup that was generated via javascript. Using Firefox's DOM Inspector extension will show you if the onchange event that was added to the select, and if so, what it is.

Farree
08-10-2010, 08:50 AM
Thank you so much John for your great help. It really solve my problem :)