Solved

In bedding javascript value with in php query

Posted on 2013-11-07
19
484 Views
Last Modified: 2013-11-08
Trying to pull a javascript value into a php query and having some issues. Blow is the code.

I need to put aData[1] into "SELECT * FROM site_router_interface_info WHERE router_interface_id = 'aData[1]'"



<script type="text/javascript" charset="utf-8">
			/* Formating function for row details */
			function fnFormatDetails ( oTable, nTr )
			{
				var aData = oTable.fnGetData( nTr );
				<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db('ats_sites');

$query_interface = mysql_query("SELECT * FROM site_router_interface_info WHERE router_interface_id = 'aData[1]'") or die (mysql_error());
				?>
				var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
				sOut += '<tr><td>Rendering engine:</td><td>'+aData[1]+'</td></tr>';
				sOut += '<tr><td><?php echo $string ?></td></tr>';
				sOut += '<tr><td>Link to source:</td><td>Could provide a link here</td></tr>';
				sOut += '<tr><td>Extra info:</td><td>And any further details here (images etc)</td></tr>';
				sOut += '</table>';
				
				return sOut;
			}
			
			$(document).ready(function() {
				/*
				 * Insert a 'details' column to the table
				 */
				var nCloneTh = document.createElement( 'th' );
				var nCloneTd = document.createElement( 'td' );
				nCloneTd.innerHTML = '<img src="images/details_open.png">';
				nCloneTd.className = "center";
				
				$('#router_information thead tr').each( function () {
					this.insertBefore( nCloneTh, this.childNodes[0] );
				} );
				
				$('#router_information tbody tr').each( function () {
					this.insertBefore(  nCloneTd.cloneNode( true ), this.childNodes[0] );
				} );
				
				/*
				 * Initialse DataTables, with no sorting on the 'details' column
				 */
				var oTable = $('#router_information').dataTable( {
	
					"bJQueryUI": true,
					"aaSorting": [[1, 'asc']],
					"sPaginationType": "full_numbers"
				});
				
				/* Add event listener for opening and closing details
				 * Note that the indicator for showing which row is open is not controlled by DataTables,
				 * rather it is done here
				 */
				$('#router_information tbody td img').live('click', function () {
					var nTr = $(this).parents('tr')[0];
					if ( oTable.fnIsOpen(nTr) )
					{
						/* This row is already open - close it */
						this.src = "images/details_open.png";
						oTable.fnClose( nTr );
					}
					else
					{
						/* Open this row */
						this.src = "images/details_close.png";
						oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
					}
				} );
			} );
		</script>

Open in new window

0
Comment
Question by:ats2012
  • 9
  • 5
  • 3
  • +2
19 Comments
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
That's not going to work. By the time your HTML and Javascript is viewed in the browser, the PHP code has already run.
0
 

Author Comment

by:ats2012
Comment Utility
Isn't the function called when you click on the plus sign to open it? So the php data would run after that.
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
Comment Utility
The way you have that written the php is actually inside of a javascript. So both the javascript and the php will throw fatal exceptions.

if you are trying to get a value from the client to the server for use in a query, then the client has to send the value across as a query string value on an url or as an input value on a submitted form.

Cd&
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
PHP runs on the server
JavaScript runs on the client (in the browser)
When someone requests your page any PHP is processed and executed before it gets sent back to the browser. It doesn't exist anymore at that point.

If you want to do some dynamic data manipulation then you need to look at Ajax.  
Using ajax depending on what the user does in the browser you can request new data from the server and update the webpage.
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
Isn't the function called when you click on the plus sign to open it? So the php data would run after that.

No. The javascript function is run, but the PHP has already been parsed by then. Look at this:

<script>
alert("<?php echo "Hello" ?>");
</script>

When you request the page, the PHP is parsed on the server, so by the time your page hits your screen, what you'll actually see in your browser's source is just:

<script>
alert("Hello");
</script>

There will be no sign of PHP because that's handled at the server. By the time you view the page, you're on the client-side.

As Gary said, if you want your page to dynamically run PHP code, you will have to create an AJAX request. This will then allow the client-side code (javascript) to request new data from the server-side (PHP), but the 2 never directly interact (one makes a request / the other responds)
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
If you read these three articles and still have some confusion about it, please post back and I'll try to clarify.

How client/server systems work:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/A_11271-Understanding-Client-Server-Protocols-and-Web-Applications.html

How to use jQuery to send data from the client to the server and get an answer back:
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/A_10712-The-Hello-World-Exercise-with-jQuery-and-PHP.html

Good learning resources for anyone new to web development and PHP:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

Best of luck with your project, ~Ray
0
 

Author Comment

by:ats2012
Comment Utility
I am looking at using, seen at http://www.w3schools.com/php/php_ajax_database.asp

xmlhttp.open("GET","display_information.php?id="+str,true);
xmlhttp.send();

How would I convert this so when you click on the plus sign it runs this page and displays the data?
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Don't use that -- it's old and outmoded (perhaps 10 years old!).  We've had jQuery since 2005.  Go that way instead for the front end.  The PHP server side script looks OK to me.
0
 

Author Comment

by:ats2012
Comment Utility
This is what I go so far. I setup a php script that does the query but the below is not pulling it up.


			function fnFormatDetails ( oTable, nTr )
			{
				var aData = oTable.fnGetData( nTr );
				
				$.ajax({
            type: "GET",
            url: "display_computerv2.php",
            data: { id: aData[1] },
            dataType: "json",
            success: function (msg) {
                if (msg.success) {
                    $("#one").html(msg);
                } else {
                    alert("error");
                }
            }
        });
			}

Open in new window

0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:ats2012
Comment Utility
This is the full script plus the display script.

<!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">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>ATS Management</title>
<head>
<style type="text/css" title="currentStyle">
			@import "css/demo_page.css";
			@import "css/demo_table_jui.css";
			@import "css/smoothness/jquery-ui-1.8.4.custom.css";
		</style>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" language="javascript" src="scripts/jquery.dataTables.js"></script>

<script type="text/javascript" charset="utf-8">
			/* Formating function for row details */
			function fnFormatDetails ( oTable, nTr )
			{
				var aData = oTable.fnGetData( nTr );
				
				$.ajax({
            type: "GET",
            url: "display_computerv2.php",
            data: { id: aData[1] },
            dataType: "json",
            success: function (msg) {
                if (msg.success) {
                    $("#one").html(msg);
                } else {
                    alert("error");
                }
            }
        });
			}
			
			$(document).ready(function() {
				/*
				 * Insert a 'details' column to the table
				 */
				var nCloneTh = document.createElement( 'th' );
				var nCloneTd = document.createElement( 'td' );
				nCloneTd.innerHTML = '<img src="images/details_open.png">';
				nCloneTd.className = "center";
				
				$('#router_information thead tr').each( function () {
					this.insertBefore( nCloneTh, this.childNodes[0] );
				} );
				
				$('#router_information tbody tr').each( function () {
					this.insertBefore(  nCloneTd.cloneNode( true ), this.childNodes[0] );
				} );
				
				/*
				 * Initialse DataTables, with no sorting on the 'details' column
				 */
				var oTable = $('#router_information').dataTable( {
	
					"bJQueryUI": true,
					"aaSorting": [[1, 'asc']],
					"sPaginationType": "full_numbers"
				});
				
				/* Add event listener for opening and closing details
				 * Note that the indicator for showing which row is open is not controlled by DataTables,
				 * rather it is done here
				 */
				$('#router_information tbody td img').live('click', function () {
					var nTr = $(this).parents('tr')[0];
					if ( oTable.fnIsOpen(nTr) )
					{
						/* This row is already open - close it */
						this.src = "images/details_open.png";
						oTable.fnClose( nTr );
					}
					else
					{
						/* Open this row */
						this.src = "images/details_close.png";
						oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
					}
				} );
			} );
		</script>


<?php
include ("site_navigation.php");
dropdown_script();
?>

</head>
<?php
require "config.php";
require ('scripts/db.php');
include ("scripts/DB-ats.php");
include ("authenticate.php");
authenticate();
?>
<body>
<?php

navigation();

   	$con = mysql_connect("localhost","root","pass");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db('ats_sites');
$id=24;
$router_id = 5;
$query = mysql_query("SELECT * FROM site_router_interface WHERE router_id = '$router_id' ORDER BY id ASC") or die (mysql_error());
?>


 <div id="content">
 <br>
<br>
<b>Router Interfaces</b>
<div style="width:700px;" id="example_wrapper">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="router_information">

<?php
echo "<thead>";
echo "<tr>";
echo "<th>";
echo "<b>ID:</b>";
echo "</th>";
echo "<th>";

echo "</th>";
echo "<th>";
echo "<b>Delete Interface:</b>";
echo "</th>";
echo "<th>";
echo "<b>Add Interface Info:</b>";
echo "</th>";
echo "<th>";
echo "<b>Edit Interface:</b>";
echo "</th>";
echo "<th>";
echo "<b>Interface Type:</b>";
echo "</th>";
echo "<th>";
echo "<b>IP Address:</b>";
echo "</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while ($data = mysql_fetch_assoc($query))
{
$interface_type = $data['interface_type'];
$ip_address = $data['ip_address'];
$interface_id = $data['id'];
?>
<tr>
<?php
echo "<td>";
echo $interface_id;
echo "</td>";
echo "<td>";
echo "<center><img src='images/router.png' width='76' height='15' align='middle'/></center>";
echo "</td>";
echo "<td align='middle'>";
?>
<a href=remove_router_interface.php?id=<?php echo $id; ?>&interface_id=<?php echo $interface_id ?>&router_id=<?php echo $router_id ?> onclick="return confirm('Are you sure you want to Delete this Item?')"><img src='images/decommission_asset.png' width='30' height='30' align='middle'/></a>
<?php
echo "</td>";
echo "<td>";
echo "<center><a href='add_router_interface_info.php?id=$id&router_id=$router_id&interface_id=$interface_id'><img src='images/add-icon.png' width='25' height='25' /></a></center>";
echo "</td>";
echo "<td align='middle'>";
?>
<a href=edit_interface.php?id=<?php echo $id; ?>&router_id=<?php echo $router_id ?>&interface_id=<?php echo $interface_id; ?>><img src='images/computer_development.png' width='30' height='30' align='middle'/></a>
<?php
echo "</td>";
echo "<td class='navigation'>";
echo "<a href='#' data-id='$interface_id'>$interface_type</a>";
echo "</td>";
echo "<td>";
echo $ip_address;
echo "</td>";
echo "</tr>";

}
?>

</tbody>
			</table>
			
</div>







</div>



</body>

</html>

Open in new window







<?php
error_reporting(E_ALL);
$compID = $_GET['id'];

   	$con = mysql_connect("localhost","root","pass");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db('ats_sites');

$query_interface = mysql_query("SELECT * FROM site_router_interface_info WHERE router_interface_id = '$compID'") or die (mysql_error());

?>

<b>Interface Data</b>

<table>
<?php
echo "<tr>";
echo "<th>";
echo "<b>Name:</b>";
echo "</th>";
echo "<th>";
echo "<b>Speed:</b>";
echo "</th>";
echo "<th>";
echo "<b>Vendor:</b>";
echo "</th>";
echo "<th>";
echo "<b>Lec ID:</b>";
echo "</th>";
echo "<th>";
echo "<b>DID:</b>";
echo "</th>";
echo "<th>";
echo "<b>Account ID:</b>";
echo "</th>";
echo "<th>";
echo "<b>Circuit ID:</b>";
echo "</th>";
echo "<th>";
echo "<b>Support Number:</b>";
echo "</th>";
echo "<th>";
echo "<b>Notes:</b>";
echo "</th>";
echo "</tr>";
while ($data_interface = mysql_fetch_assoc($query_interface))
{
echo "<tr>";
echo "<td>";
echo $data_interface['name'];
echo "</td>";
echo "<td>";
echo $data_interface['speed'];
echo "</td>";
echo "<td>";
echo $data_interface['vendor'];
echo "</td>";
echo "<td>";
echo $data_interface['lec'];
echo "</td>";
echo "<td>";
echo $data_interface['did'];
echo "</td>";
echo "<td>";
echo $data_interface['account_id'];
echo "</td>";
echo "<td>";
echo $data_interface['circuit_id'];
echo "</td>";
echo "<td>";
echo $data_interface['support_number'];
echo "</td>";
echo "<td>";
echo $data_interface['notes'];
echo "</td>";
echo "</tr>";

			}
			?>
			</table>

Open in new window

router-info.PNG
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
What errors are you getting. Is you PHP script expecting the data to be passed by GET or POST. Does your PHP script work when you call it manually.

Do you have a live link we could look at.

Seeing bits of code in isolation makes it very difficult to diagnose your problem.

In your success function, it looks like you are expecting a JSON array back (msg.success), so you may need to set the HTML to one of the msg properties - not just msg
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
OK. That script won't create JSON, so there will be no msg.success value, and you shouldn't be requesting JSON. Try this:

$.ajax({
   type: "GET",
   url: "display_computerv2.php",
   data: { id: aData[1] },
   success: function (msg) {
      $("#one").html(msg);
      alert("Done");
   }
});

Open in new window

0
 

Author Comment

by:ats2012
Comment Utility
I got an alert when I clicked on the button but nothing after that.
0
 

Author Comment

by:ats2012
Comment Utility
What I am not understanding is how do I display the page with this. Its looking for an id with one but there isn't one.


function fnFormatDetails ( oTable, nTr )
			{
				var aData = oTable.fnGetData( nTr );
				
				$.ajax({
   type: "GET",
   url: "display_computerv2.php",
   data: { id: aData[1] },
   dataType: 'html',
   success: function (msg) {
      $("#one").html(msg);
      alert("Done");

   }
});

			}

Open in new window

0
 

Author Comment

by:ats2012
Comment Utility
Once I click the button I am showing the page being loaded with the correct id using Chrome debug.
0
 

Author Comment

by:ats2012
Comment Utility
I got this to work using the below, but the issue The issue now is one isnt unique so if you open multiple new tables it displays incorrectly because its looking for the id=one.

function fnFormatDetails ( oTable, nTr )
			{
				var aData = oTable.fnGetData( nTr );
				
				$.ajax({
   type: "GET",
   url: "display_computerv2.php",
   data: { id: aData[1] },
   dataType: 'html',
   success: function (msg) {
      $("#one").html(msg);
   }
});



var sOut = '<div id="one"></div>';
 return sOut;

			}

Open in new window

0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
I'm getting a little confused. You say the code is looking for an element with an ID of 'one' but there isn't one, yet in the code you posted, you had this:

$("#one").html(msg);

Where do you want to put the AJAX response?
0
 

Author Comment

by:ats2012
Comment Utility
Got this working. This is what I used.

function fnFormatDetails ( oTable, nTr )
			{
				var aData = oTable.fnGetData( nTr );
				
				$.ajax({
   type: "GET",
   url: "display_computerv2.php",
   data: { id: aData[1] },
   dataType: 'html',
   success: function (msg) {
      $("#one" + aData[1]).html(msg);
   }
});



var sOut = '<div id="one' + aData[1] + '"></div>';
 return sOut;

			}

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
issue now is one isnt unique
In markup, there are three different "counts" of markup elements: zero, one and many.  Obviously zero elements do not need markup.  

If there is one element (unique) it is identified by the id= attribute.  It is tagged with the # character.

If there are multiple elements (or potentially multiple elements) they are identified with the class= attribute.  They are tagged with the . (period) character.

If you have more than one element with an identical id= attribute, you have invalid markup and you need to redesign the document.  You can use the W3 validator to check for errors like that.
http://validator.w3.org/
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now