Solved

Javascript DataTables problem with server_processing.php

Posted on 2013-06-08
8
705 Views
Last Modified: 2013-06-11
Hi
I'm trying to use the server_processing.php script to pull the data from the mySQL database. I have tried the following the example from site so I can understand why its not working.

I think the problem is some were in this code:
$(document).ready( function () {
	$('#table_id').dataTable({
    	"bSortClasses": false,
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": "server_processing.php"
    });
} );

Open in new window


Because when I run the server_processing.php file in the browser it gets the data from the database and i have this code in the script and it echo's all the data: "return Json($output, \"application/json\");", but when I run the index.php with the above block of code there is not datadump meaning its not being executed.

here is the code for the 2 files.

index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<title>Title</title>
	 
	<link rel="stylesheet" href="style.css"/>
	<style></style>
	<style type="text/css" title="currentStyle">
	    @import "DataTables/media/css/demo_table.css";
	</style>
 
	<script src="//localhost/scripts/jquery/jquery-1.9.1.js" type="text/javascript"></script>
	<script src="//localhost/scripts/jdatatable/jquery.dataTables.min.js" type="text/javascript"></script>
	<script src="//localhost/scripts/jeditable/jquery.jeditable.js" type="text/javascript"></script>
	<script src="//localhost/scripts/jui/jquery-ui.js" type="text/javascript"></script>
	<script src="//localhost/scripts/jvalidation/jquery.validate.js" type="text/javascript"></script>
	<script>
	
$(document).ready( function () {
	$('#table_id').dataTable({
    	"bSortClasses": false,
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": "server_processing.php"
    });

} );

	</script>
</head>
 
<body>
	<table cellpadding="0" cellspacing="0" border="0" class="display" id="table_id">
		<thead>
			<tr><th>JobID</th><th>Source</th><th>Customer</th><th>Ref</th><th>Product</th><th>Desc</th><th>Qty</th><th>Supplier</th><th>Cost</th><th>Status</th><th>DateLogged</th><th>LoggedBy</th><th>ETA</th><th>SentDate</th><th>CompDate</th><th>Delivery</th><th>Notes</th></tr>
		</thead>
		<tbody>
			<tr>
				<td colspan="17" class="dataTables_empty">Loading data from server</td>
			</tr>
		</tbody>
		<tfoot>
			<tr><th>JobID</th><th>Source</th><th>Customer</th><th>Ref</th><th>Product</th><th>Desc</th><th>Qty</th><th>Supplier</th><th>Cost</th><th>Status</th><th>DateLogged</th><th>LoggedBy</th><th>ETA</th><th>SentDate</th><th>CompDate</th><th>Delivery</th><th>Notes</th></tr>
		</tfoot>
	</table>

 
</body>
</html>

Open in new window


server_processing.php
<?php
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Easy set variables
	 */
	
	/* Array of database columns which should be read and sent back to DataTables. Use a space where
	 * you want to insert a non-database field (for example a counter or static image)
	 */
	$aColumns = array( 'JobID','Source','Customer','Ref','Product','Desc','Qty','Supplier','Cost','Status','DateLogged','LoggedBy','ETA','SentDate','CompDate','Delivery','Notes' );


	/* Indexed column (used for fast and accurate table cardinality) */
	$sIndexColumn = "JobID";
	
	/* DB table to use */
	$sTable = "jobs";
	
	/* Database connection information */
	$gaSql['user']       = "";
	$gaSql['password']   = "";
	$gaSql['db']         = "jobstatus";
	$gaSql['server']     = "localhost";
	

	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * If you just want to use the basic configuration for DataTables with PHP server-side, there is
	 * no need to edit below this line
	 */
	
	/* 
	 * Local functions
	 */
	function fatal_error ( $sErrorMessage = '' )
	{
		header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error' );
		die( $sErrorMessage );
	}

	
	/* 
	 * MySQL connection
	 */
	if ( ! $gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  ) )
	{
		fatal_error( 'Could not open connection to server' );
	}

	if ( ! mysql_select_db( $gaSql['db'], $gaSql['link'] ) )
	{
		fatal_error( 'Could not select database ' );
	}

	/* 
	 * Paging
	 */
	$sLimit = "";
	if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
	{
		$sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] ).", ".
			intval( $_GET['iDisplayLength'] );
	}
	
	
	/*
	 * Ordering
	 */
	$sOrder = "";
	if ( isset( $_GET['iSortCol_0'] ) )
	{
		$sOrder = "ORDER BY  ";
		for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
		{
			if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
			{
				$sOrder .= "`".$aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."` ".
					($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'desc') .", ";
			}
		}
		
		$sOrder = substr_replace( $sOrder, "", -2 );
		if ( $sOrder == "ORDER BY" )
		{
			$sOrder = "";
		}
	}
	
	
	/* 
	 * Filtering
	 * NOTE this does not match the built-in DataTables filtering which does it
	 * word by word on any field. It's possible to do here, but concerned about efficiency
	 * on very large tables, and MySQL's regex functionality is very limited
	 */
	$sWhere = "";
	if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" )
	{
		$sWhere = "WHERE (";
		for ( $i=0 ; $i<count($aColumns) ; $i++ )
		{
			if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" )
			{
				$sWhere .= "`".$aColumns[$i]."` LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
			}
		}
		$sWhere = substr_replace( $sWhere, "", -3 );
		$sWhere .= ')';
	}
	
	/* Individual column filtering */
	for ( $i=0 ; $i<count($aColumns) ; $i++ )
	{
		if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
		{
			if ( $sWhere == "" )
			{
				$sWhere = "WHERE ";
			}
			else
			{
				$sWhere .= " AND ";
			}
			$sWhere .= "`".$aColumns[$i]."` LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
		}
	}
	
	
	/*
	 * SQL queries
	 * Get data to display
	 */
	$sQuery = "
		SELECT SQL_CALC_FOUND_ROWS `".str_replace(" , ", " ", implode("`, `", $aColumns))."`
		FROM   $sTable
		$sWhere
		$sOrder
		$sLimit
		";
	$rResult = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
	
	/* Data set length after filtering */
	$sQuery = "
		SELECT FOUND_ROWS()
	";
	$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
	$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
	$iFilteredTotal = $aResultFilterTotal[0];
	
	/* Total data set length */
	$sQuery = "
		SELECT COUNT(`".$sIndexColumn."`)
		FROM   $sTable
	";
	$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
	$aResultTotal = mysql_fetch_array($rResultTotal);
	$iTotal = $aResultTotal[0];
	
	
	/*
	 * Output
	 */
	$output = array(
		"sEcho" => intval($_GET['sEcho']),
		"iTotalRecords" => $iTotal,
		"iTotalDisplayRecords" => $iFilteredTotal,
		"aaData" => array()
	);
	
	while ( $aRow = mysql_fetch_array( $rResult ) )
	{
		$row = array();
		for ( $i=0 ; $i<count($aColumns) ; $i++ )
		{
			if ( $aColumns[$i] == "version" )
			{
				/* Special output formatting for 'version' column */
				$row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
			}
			else if ( $aColumns[$i] != ' ' )
			{
				/* General output */
				$row[] = $aRow[ $aColumns[$i] ];
			}
		}
		$output['aaData'][] = $row;
	}
	
	echo "<script>";
	echo "return Json($output, \"application/json\");";
	echo "</script>";
	
	echo json_encode( $output );
?>

Open in new window

0
Comment
Question by:ACEAFTY
  • 5
  • 3
8 Comments
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 39232400
Comment out these three lines.
echo "<script>";
echo "return Json($output, \"application/json\");";
echo "</script>";

Open in new window

They don't do anything and also won't ever be executed.  It's not part of the JSON so it interferes with it.  Just let the next line return the JSON.
0
 
LVL 1

Author Comment

by:ACEAFTY
ID: 39232413
I just added that for debugging, Its so I tell if The Script has been executed but nothing is happening When the index.php file runs.
0
 
LVL 83

Accepted Solution

by:
Dave Baldwin earned 500 total points
ID: 39232418
When you run 'server_processing.php' by itself without those lines you should see the JSON on the screen.
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 39232419
This page http://www.datatables.net/release-datatables/examples/data_sources/ajax.html says:
DataTables expects an object with an array called "aaData" with the data source.
0
 
LVL 1

Author Comment

by:ACEAFTY
ID: 39232700
Hi,
For some reason its loading the data now which is good, but when I insert the additional code to allow row highlighting when hovering or incelling editing, adding/deleting rows, that was working when originally i used a static html table isn't working any more??

index.php - with the additional code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<title>Title</title>
	 
	<link rel="stylesheet" href="style.css"/>
	<style>

		#table_id tbody tr.highlighted:hover{
		    background-color: #00f;
		}
		
	</style>
	<style type="text/css" title="currentStyle">
	    @import "DataTables/media/css/demo_table.css";
	</style>
 
	<script src="//localhost/scripts/jquery/jquery-1.9.1.js" type="text/javascript"></script>
	<script src="//localhost/scripts/jdatatable/jquery.dataTables.min.js" type="text/javascript"></script>
	<script src="//localhost/scripts/jeditable/jquery.jeditable.js" type="text/javascript"></script>
	<script src="//localhost/scripts/jui/jquery-ui.js" type="text/javascript"></script>
	<script src="//localhost/scripts/jvalidation/jquery.validate.js" type="text/javascript"></script>
	<script>
		var oTable1;
		
		$(document).ready( function () {
			var oTable = $('#table_id').dataTable({
		    	"bSortClasses": false,
		        "bProcessing": true,
		        "bServerSide": true,
		        "sAjaxSource": "server_processing.php"
		    });

		    oTable.$('tr').hover( function() {
		        var iCol = $('td', this.parentNode).index(this) % 17;
		        oTable.$('tr').addClass( 'highlighted' );
		    }, function() {
		        oTable.$('tr.highlighted').removeClass('highlighted');
		    } );




		    /* Add a click handler to the rows - this could be used as a callback */
		    $("#table_id tbody tr").click( function( e ) {
		        if ( $(this).hasClass('row_selected') ) {
		            $(this).removeClass('row_selected');
		        }
		        else {
		            oTable1.$('tr.row_selected').removeClass('row_selected');
		            $(this).addClass('row_selected');
		        }
		    });
		     
		    /* Add a click handler for the delete row */
		    $('#delete').click( function() {
		        var anSelected = fnGetSelected( oTable );
		        if ( anSelected.length !== 0 ) {
		            oTable1.fnDeleteRow( anSelected[0] );
		        }
		    } );

		    /* Init the table */
		    oTable1 = $('#table_id').dataTable( );





		    /* Apply the jEditable handlers to the table */
		    oTable1.$('td').editable( 'editable_ajax.php', {
		        "callback": function( sValue, y ) {
		            var aPos = oTable1.fnGetPosition( this );
		            oTable1.fnUpdate( sValue, aPos[0], aPos[1] );
		        },
		        "submitdata": function ( value, settings ) {
		            return {
		                "row_id": this.parentNode.getAttribute('id'),
		                "column": oTable1.fnGetPosition( this )[2]
		            };
		        },
		        "height": "14px",
		        "width": "100%"
		    } );

		
		} );

		/* Get the rows which are currently selected */
		function fnGetSelected( oTableLocal )
		{
		    return oTableLocal.$('tr.row_selected');
		}
		
		
		function fnClickAddRow() {
		    $('#table_id').dataTable().fnAddData( [
		
			"4",
			"Source",
			"Customer",
			"Ref",
			"Product",
			"Desc",
			"Qty",
			"Supplier",
			"Cost",
			"Status",
			"DateLogged",
			"LoggedBy",
			"ETA",
			"SentDate",
			"CompDate",
			"Delivery",
			"Notes"
		
		    ] );
		}		


	</script>
</head>
 
<body>
	<div><a onclick="fnClickAddRow();" href="javascript:void(0);">Click to add a new row</a><br><a id="delete" href="javascript:void(0)">Delete selected row</a><br><br></div>
	
	<table cellpadding="0" cellspacing="0" border="0" class="display" id="table_id">
		<thead>
			<tr><th>JobID</th><th>Source</th><th>Customer</th><th>Ref</th><th>Product</th><th>Desc</th><th>Qty</th><th>Supplier</th><th>Cost</th><th>Status</th><th>DateLogged</th><th>LoggedBy</th><th>ETA</th><th>SentDate</th><th>CompDate</th><th>Delivery</th><th>Notes</th></tr>
		</thead>
		<tbody>
			<tr>
				<td colspan="17" class="dataTables_empty">Loading data from server</td>
			</tr>
		</tbody>
		<tfoot>
			<tr><th>JobID</th><th>Source</th><th>Customer</th><th>Ref</th><th>Product</th><th>Desc</th><th>Qty</th><th>Supplier</th><th>Cost</th><th>Status</th><th>DateLogged</th><th>LoggedBy</th><th>ETA</th><th>SentDate</th><th>CompDate</th><th>Delivery</th><th>Notes</th></tr>
		</tfoot>
	</table>

 
</body>
</html>

Open in new window

0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 39233089
My guess would be that it is conflicting with the 'datatables' code.  Often with a framework like that, you have to use their methods.  In their examples http://www.datatables.net/examples/ , they have a link to "Highlight rows and columns".
0
 
LVL 1

Author Comment

by:ACEAFTY
ID: 39237048
Hi
Not having much luck with this, but the original problem has been fixed, thank you. I'll post another questions for any further issues.
0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 39237064
You're welcome, thanks for the points.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Generate Numbers in JQuery file 11 66
How to combine and minify CSS and JS files 5 17
Start Auto-download of File when page loads? 1 21
html border input line 7 13
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

839 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