Solved

In bedding javascript value with in php query

Posted on 2013-11-07
19
494 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 5
  • 3
  • +2
19 Comments
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39630747
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
ID: 39630851
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
ID: 39630870
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
Are You Using the Best Web Development Editor?

The worlds of web hosting and web development are constantly evolving. Every year we see design trends change, coding standards adapt and new frameworks/CMS created. With such a quick pace of change it’s easy to get lost trying to keep up.

See if your editor made the list.

 
LVL 58

Expert Comment

by:Gary
ID: 39630902
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 43

Expert Comment

by:Chris Stanyon
ID: 39630933
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 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39630935
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
ID: 39631369
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 110

Expert Comment

by:Ray Paseur
ID: 39631464
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
ID: 39631583
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
 

Author Comment

by:ats2012
ID: 39631608
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 43

Expert Comment

by:Chris Stanyon
ID: 39631618
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 43

Expert Comment

by:Chris Stanyon
ID: 39631627
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
ID: 39631651
I got an alert when I clicked on the button but nothing after that.
0
 

Author Comment

by:ats2012
ID: 39631819
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
ID: 39631839
Once I click the button I am showing the page being loaded with the correct id using Chrome debug.
0
 

Author Comment

by:ats2012
ID: 39631913
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 43

Expert Comment

by:Chris Stanyon
ID: 39632169
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
ID: 39633232
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 110

Expert Comment

by:Ray Paseur
ID: 39633237
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

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

623 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