I have a php script that pulls several rows of invoices from a database and displays them on the screen in table format. I have created an onclick per row within the while loop in order call another php script that runs a query to pull all the attachments for that particular invoice. The problem i'm having is that the onclick function only pulls the attachments for the first row returned in the table, no matter which row I click "view" on to trigger the onclick. The onclick is using getElementById, and all the ids are the SAME. So it is just finding the first instance of the id and displaying THAT no matter which row i click "view" in to see the attachments. Is there a way to allow the onclick to pull the right attachments for each row?

index.php

<?php session_start(); error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<!-- Load jQuery, SimpleModal and Basic JS files -->
<script type='text/javascript' src='/invoices/scripts/jquery.js'></script>
<script type='text/javascript' src='/invoices/scripts/jquery.simplemodal.js'></script>
<script type='text/javascript' src='/invoices/scripts/basic.js'></script>
	<title>Hoovestol Dashboard</title>
	<script type="text/javascript">
		function reFresh() {
			location.reload(true)
		}
		/* Set the number below to the amount of delay, in milliseconds,
		you want between page reloads: 1 minute = 60000 milliseconds. */
		window.setInterval("reFresh()",300000);
	</script>
	<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!

        try{
                // Opera 8.0+, Firefox, Safari
                ajaxRequest = new XMLHttpRequest();
        } catch (e){
                // Internet Explorer Browsers
                try{
                        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try{
                                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e){
                                // Something went wrong
                                alert("Your browser broke!");
                                return false;
                        }
                }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                        var ajaxDisplay = document.getElementById('basic-modal-content');
                        ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
        }
        [B]var invoice_num = document.getElementById('invoice_num').value[/B];
        var queryString = "?invoice_num=" + invoice_num;
        ajaxRequest.open("GET", "getattachments.php" + queryString, true);
        ajaxRequest.send(null);
}

//-->
</script>
</head>
<body>
<div style="margin:0 auto; width:800px;">
<!--Equipment Starts-->
<div style="text-align:left;"><h1 style="margin-bottom:3px; margin-right:20px;">Recent Invoices</h1></div>
	<table align="center" id="printview" class="qresults">
		<tr>
			<th style="width:150px;">Equipment Number</th><th style="width:150px;">Invoice Number</th><th style="width:400px;">Notes</th><th style="width:100px;">Action</th>
		</tr>
<?php
	$conn = mysql_connect('xxx','hoovdash','xxx');
	$db = mysql_select_db('hoov_dashboard',$conn);
	$sql = "SELECT * FROM invoices WHERE on_hold='1' ORDER BY create_date";
	$result = mysql_query($sql,$conn);
		while($row = mysql_fetch_assoc($result))
		{
			$id = $row['id'];
			$equip_num = $row['equip_num'];
			$invoice_num = $row['invoice_num'];
			$notes = $row['notes'];
			$row_class = ($row_count % 2) ? $class1 : $class2;
				echo"<tr><td class='$row_class'>$equip_num</td><td class='$row_class'>$invoice_num</td><td class='$row_class'>$notes</td><td class='$row_class' style='text-align:center;'>[B]<div id='basic-modal'><form name='myForm'><input type='text' id='invoice_num' value='$invoice_num' /><input type='button' onclick='ajaxFunction()' value='view' class='basic'/></form></div></td>[/B]</tr>";
		}
?>
</div>
</table><br /><br />
<div id='basic-modal-content'>[B][I]This is where the attachments are displayed (it actually is linked to a js file that uses a dialog box to display the attachments.)[/I][/B]</div>
<div style='display:none'>
    <img src='/invoices/images/x.png' alt='' />
</div>
</body>
</html>

getattachments.php

<?php
$conn = mysql_connect('xxx','hoovdash','xxx');
	$db = mysql_select_db('hoov_dashboard',$conn);
	$invoice_num = $_GET['invoice_num'];
	$invoice_num = mysql_real_escape_string($invoice_num);
	$sql = "SELECT * FROM attachments WHERE invoice_num='$invoice_num' ORDER BY create_date";
	$result = mysql_query($sql);
		while($row = mysql_fetch_array($result))
		{
			echo"<p>$row[file]</p>";
		}
?>

The problem is simple,that you are making those elements and buttons inside the php code run-time,without changing their ids.
So every time you click it will get only a first item,because all the elements are having the same ID,and if there exists more than one element with the same name or ID then it every time it will get the firts that appears and ignore the others.

1) So the solution here is to provide different IDS to each element that you want to access on click.
2) To change the ajaxcall funtion a bit,instead of calling it directly,call it with the ID that you fetch inside the ajax funtion with static code like document.getElementById('anelementname').value


Here is the changed code in your index.php


...
....

while($row = mysql_fetch_assoc($result))
		{
			$id = $row['id'];
			$equip_num = $row['equip_num'];
			$invoice_num = $row['invoice_num'];
			$notes = $row['notes'];
			$row_class = ($row_count % 2) ? $class1 : $class2;
echo "<tr><td class='$row_class'>$equip_num</td><td class='$row_class'>$invoice_num</td><td class='$row_class'>$notes</td><td class='$row_class' style='text-align:center;'>
<div id='basic-modal'><form name='myForm'><input type='text' id='<?php echo $id; ?>' value='$invoice_num' />
?>
<input type="button" onclick="ajaxFunction('<?php echo @id; ?>');"' value='view' class='basic'/>
<?php
echo "</form></div></td></tr>";
		}

..
....


And a change in your ajax call funtion

first change in your funtion declaration

function ajaxFunction(){


to

function ajaxFunction(docId){


And second inside your funtion definition,now your dont need to fetch id in that manner.

var invoice_num = document.getElementById('invoice_num').value;
 var queryString = "?invoice_num=" + invoice_num;
 ajaxRequest.open("GET", "getattachments.php" + queryString, true);
 ajaxRequest.send(null);

Replace this with

var invoice_num = document.getElementById(docId).value;
 var queryString = "?invoice_num=" + invoice_num;
 ajaxRequest.open("GET", "getattachments.php" + queryString, true);
 ajaxRequest.send(null);

I hope you get it :)

MArk it as solved,so it can help others...

Pass current Input Element in ajaxFunction(): ajaxFunction(this);

<?php
	$conn = mysql_connect('xxx','hoovdash','xxx');
	$db = mysql_select_db('hoov_dashboard',$conn);
	$sql = "SELECT * FROM invoices WHERE on_hold='1' ORDER BY create_date";
	$result = mysql_query($sql,$conn);
		while($row = mysql_fetch_assoc($result))
		{
			$id = $row['id'];
			$equip_num = $row['equip_num'];
			$invoice_num = $row['invoice_num'];
			$notes = $row['notes'];
			$row_class = ($row_count % 2) ? $class1 : $class2;
				echo"<tr><td class='$row_class'>$equip_num</td><td class='$row_class'>$invoice_num</td><td class='$row_class'>$notes</td><td class='$row_class' style='text-align:center;'><div id='basic-modal'><form name='myForm'><input type='text' id='invoice_num' value='$invoice_num' /><input type='button' onclick='ajaxFunction(this)' value='view' class='basic'/></form></div></td></tr>";
		}
?>

and your ajax function will be now:

function ajaxFunction(buttonEl){ // Passed current clicked button element
        var ajaxRequest;  // The variable that makes Ajax possible!

        try{
                // Opera 8.0+, Firefox, Safari
                ajaxRequest = new XMLHttpRequest();
        } catch (e){
                // Internet Explorer Browsers
                try{
                        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try{
                                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e){
                                // Something went wrong
                                alert("Your browser broke!");
                                return false;
                        }
                }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                        var ajaxDisplay = document.getElementById('basic-modal-content');
                        ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
        }
        var invoice_num = buttonEl.previousSibling.value; // Get previous element ie text input
        var queryString = "?invoice_num=" + invoice_num;
        ajaxRequest.open("GET", "getattachments.php" + queryString, true);
        ajaxRequest.send(null);
}

Thanks guys! This was very helpful, as this is my first go around with AJAX and Javascript! I actually got it working with Luckychaps method. It did exactly as I wanted.

Hi,Luckychap's method is absolutely right,but is has certain limitations, just because in case of multiple fields,you will definitely not want to find previous siblings's previous siblings and so on.
So giving a unique Id will also help at that time.
:)

Akash Saikia, I see what you're saying. I will definitely keep that in mind while I continue on with this project. Thanks for the advise!

Hi,Luckychap;s method is absolutely right,but is has certain limitations, just because in case of multiple fields,you can will definitely not want to find previous siblings's previous siblings and so on.
So giving a unique Id will also help at that time.
:)

Also, I did notice on line 11 of your post:

Shouldn't this --> onclick="ajaxFunction('<?php echo @id; ?>');"'

Be this --> onclick="ajaxFunction('<?php echo $id; ?>')"

Notice, I took off the --> ; and '

Yep,sure.
My mistake.

Yep,sure.
My mistake.

Perfect! Your method is working for me as well! - Thanks again for all the help. It is always good to know more than one way of doing these things.

Ok, I lied. I am getting a "Syntax Error ajaxFunction("

<script language="javascript" type="text/javascript">
<!--
	//Browser Support Code
	function ajaxFunction(docId){
        var ajaxRequest;  // The variable that makes Ajax possible!
        try{
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
			// Something went wrong
            alert("Your browser broke!");
            return false;
			}
        }
		}
		// Create a function that will receive data sent from the server
			ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                        var ajaxDisplay = document.getElementById('basic-modal-content');
                        ajaxDisplay.innerHTML = ajaxRequest.responseText;
				}
			}
        //var invoice_num = document.getElementById('invoice_num').value;
		var invoice_num = document.getElementById(docId).value; // Get previous element ie text input
        var queryString = "?invoice_num=" + invoice_num;
			ajaxRequest.open("GET", "/invoices/scripts/getattachments.php" + queryString, true);
			ajaxRequest.send(null);
	}
//-->
</script>

Turns out that:

onclick="ajaxFunction('<?php echo $id; ?>') doesn't need the singled quotes.
should be: onclick="ajaxFunction(<?php echo $id; ?>)

so now is it working or not?

so now is it working or not?

It is working great, Thanks!

The ONLY issue I would like to solve is this:

The ajax runs a php query and pulls the data into a div (which I have as a popup dialog box.) Since it takes awhile to pull the data from MySQL, the dialog box is empty for about 2-3 seconds. I would like to add a "loading" image to let the user know it is loading data. Instead of just a blank dialog box. Is there an good way of doing this?

Ya.
1 )You need to add a Div tag somewhere where you can have a simple loading image or a static text as Loading....

2 )After this is done,

call ur ajax funtion in this way...

<script language="JAVASCRIPT">
function getData()
{

document.getElementById('Loading').style.display = 'block';
ajaxFunction();
document.getElementById('Loading').style.display = 'none';
return;
}

</script>

And here is the structure of your Loading div.

<DIV ID="Loading" STYLE="position:absolute;z-index:100;top:30%;left:42%;display:none;">
Please Wait....
</DIV>

3 ) And a bit of change here.

<input type='button' onclick='getData();//i replaced your ajaxFuntion() call from here' value='view' class='basic'/></form></div></td></tr>";

Remember to not to put Loading div inside your ajax div. Otherwise it won't show you any thing.
If you find some difficulty in the style attribute of this div then remove the style attribute entirely.

:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.