Posts Tagged Tutorials

Implementing Quick Table Search using jQuery filter

Before sometime I had written a post on jQuery case-insensitive expression filter. Now today we will learn about how to put simple filter for our HTML table using jQuery and it's case-insensitive expression.

It's takes just few lines of Javascript / jQuery code to implement quick filter for an HTML table, here you go:

The HTML

 
<label for="kwd_search">Search:</label>
<input type="text" id="kwd_search" value=""/>
<table id="my-table" border="1" style="border-collapse:collapse">
<thead>
<tr>
<th>Name</th>
<th>Sports</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>Sachin Tendulkar</td>
<td>Cricket</td>
<td>India</td>
</tr>
<tr>
<td>Tiger Woods</td>
<td>Golf</td>
<td>USA</td>
</tr>
<tr>
<td>Maria Sharapova</td>
<td>Tennis</td>
<td>Russia</td>
</tr>
</tbody>
</table>
 

Read the rest of this entry »

Tags: , , ,

Truncate last N lines of a file using PHP

For one of my project I needed to remove certain footer / tail-end lines from the large-file to make it clean as it was containing some summary of records within the file. Because if I do that it can be directly loaded into database by LOAD DATA command.

Usually one can read file into an array using PHP's file function but that's okay when size of file is in few hundred KB, if your file-size is running in to few MB to few hundred MB we need to find and use some efficient way to play with them. Because with large file reading as an array we can (and certainly will) run into memory outage issue.

To remove lines from the end of file you can use following snippet of code:

 
// Function to truncate last N lines from the file
function truncate_last_n_lines_of_file($file, $lines_to_remove, $chunk = 1024)
{
	// Open file in read+write mode
	$handle = @fopen($file, "a+");
	$lines_found = array();
 
	// Check if it's a valid file handle
	if($handle)
	{
		// size of file
		$max_length = $file_size = filesize($file);
		if(intval($file_size) == PHP_INT_MAX)
		{
			$max_length = PHP_INT_MAX;
		}
 
		// loop through file as long as we are not done with truncating required files
		for($length = 0; $length < $max_length; $length += $chunk)
		{
			if( ($max_length - $length) > $chunk)
			{
				$seek_size = $chunk;
			}
			else
			{
				$seek_size = $max_length - $length;
			}
 
			// read data in chunk
			fseek($handle, ($length + $seek_size) * -1, SEEK_END);
			$data = fread($handle, $seek_size) . $data;
 
			// Loop thorugh chunk to see if we are done with truncate
			for($i = $chunk; $i > 0; $i--)
			{
				if($data[$i-1] == "\n")
				{
					$lines_found[] = $i;
				}
				if(count($lines_found) == $lines_to_remove+1)
				{
					ftruncate($handle, ($max_length) - ($seek_size - $lines_found[$lines_to_remove]));
					return true;
				}
			}
			fclose($handle);
		}
		return false;
	}
}
 

Read the rest of this entry »

Tags: , , ,

Simple / Plain Ajax – without any JavaScript library

Yes, we are in the world of AJAX where we don't live without jQuery, Prototype or Mootools but when it comes to explaining someone that how raw ajax works, you need an example of plain AJAX which we have been using 5 years back when these libraries were either just born and were not as famous as today. Because my favorite jQuery has become a de facto standard when it comes to DOM manipulation or AJAX.

Recently I have to give an example to one of my friend on how raw AJAX works and here I am sharing that sample with my blog readers as a reference.

Raw AJAX Example:

The Problem Statement: We want to SUM 2 values and we want to achieve that using server-side scripting as we don't want to do that using JavaScript due to some ABC reason.

The HTML:

Raw AJAX Example Demo
 
Val 1: 
<input id="val1" name="val1" type="text" />
 + 
Val 2: 
<input id="val2" name="val2" type="text" />
<input onclick="doSum()" type="button" value="=" />
<input id="sum" name="sum" type="text" />

The Javascript:

function doSum()
{
	var url = "simple_ajax_server.php";
	var data = "val1=" + document.getElementById("val1").value + "&amp;val2=" + document.getElementById("val2").value;
	var method = 'POST';
	var async = true;
	var xmlHttpRequst = false;
 
	// Mozilla/Safari/Non-IE
    if (window.XMLHttpRequest)
	{
        xmlHttpRequst = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject)
	{
        xmlHttpRequst = new ActiveXObject("Microsoft.XMLHTTP");
    }
 
	// If AJAX supported
	if(xmlHttpRequst != false)
	{
		// Open Http Request connection
		xmlHttpRequst.open(method, url, async);
		// Set request header (optional if GET method is used)
		xmlHttpRequst.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		// Callback when ReadyState is changed.
		xmlHttpRequst.onreadystatechange = function()
		{
			if (xmlHttpRequst.readyState == 4)
			{
				document.getElementById("sum").value = xmlHttpRequst.responseText;
			}
		}
		xmlHttpRequst.send(data);
	}
	else
	{
		alert("Please use browser with Ajax support.!");
	}
}

# How does it work?
As you can see in above JavaScript example code that, first we need to initialize XMLHttpRequest object. For IE and non-IE there is a different way to initialize that object. IE being Microsoft product supports XMLHTTPRequest object creation using ActiveX while rest of the browser does it the common way.
If you're successful creating the HTTP-Request object then you open the connection to URL/URI with which you want to interact to perform desired operation; with method either POST or GET. 3rd optional parameter to open method indicates whether you want to make async request or sync request.
# What is sync / async?
Due to the behavior of JavaScript when you perform any operation in JavaScript statements start executing in parallel. So if you go the async way your next line of code will start getting executed irrespective of whether request is completed or not?
# When to use sync? When you have to perform some operation which is dependent on the result of AJAX request and you can't define them in request-handler function (one which is defined as onreadystatechange) than you must use sync request.
# When to use async? When you're loading some static content which is for information purpose and there is no dependent operation to be performed on the data being received from the AJAX request at that time you have to use async.
If you omit that argument it defaults to true meaning an asynchronous request to the server.

# What is readyState? Read the rest of this entry »

Tags: , , ,

jQuery case-insensitive Contains Expression..!

Most of the time to search through DOM and filter text we need a jQuery Expression/filter which gives us case-insensitive result. I believe it's required to have it as a part of jQuery base-library but anyway writing your own is very simple.

I have gone through some of other implementation before writing this but here this version is complete copy of jQuery library's "contains" filter except it is case-insensitive.

In below code when it's using $(elem).text() it's calling Sizzle.getText internally which is Utility function for retreiving the text value of an array of DOM nodes.

$.extend($.expr[":"],
{
    "contains-ci": function(elem, i, match, array)
	{
		return (elem.textContent || elem.innerText || $(elem).text() || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
	}
});

Here are some other nice jQuery Selectors and Expressions: Read the rest of this entry »

Tags: , , ,

Reading MSSQL BLOG column data with PHP

I was working on a migration script to transfer data from legacy desktop software to Portal we have developed. While migrating attachments (stored as TIFF files) in BLOB (Binary Large Object) in Microsoft SQL Database Server using PHP it was not a cake-walk. When I observed every time it was creating a file of same size (4KB). I quickly understood that there is some limitation (of size) for reading records in PHP configuration.

I searched through PHP.INI file and found following settings:

; Valid range 0 - 2147483647.  Default = 4096.
;mssql.textlimit = 4096
 
; Valid range 0 - 2147483647.  Default = 4096.
;mssql.textsize = 4096

I removed ";" and made values as zero, thinking that it will let PHP read unlimited size of data but didn't work out. So changed it to max value specified as following and worked perfect: Read the rest of this entry »

Tags: , , , , ,

Printing data table vertically..! Why? and How?

Last week one of my friend called me up as he got stuck when he has to print data table vertically. Yes vertical table, it means that you want your data to print from top to bottom and not left to write, which is standard conventional way to generate html table.

Vertical Table (Printing array data from top to bottom)

Vertical Table (Printing array data from top to bottom)

I took it as a challenge and wrapped that up in few minutes. But at that time I was so close to the problem that I could not see that PHP has some inbuilt functions which can help me do that and I did it other way around without using inbuilt PHP function. Here is the sample code for the same, which prints table vertically with the help of inbuilt PHP function array_chunk.

Array is the most powerful feature of PHP and playing with array is always been fun.

Sample code below uses array_chunk but I must say it was not a great help but it makes you less logic.!
// Function to print array data vertically
function print_vertical_table_sys($data_list, $rows)
{
	$columns = (count($data_list)/$rows);
	$data_list = array_chunk($data_list, $rows);
 
	echo '
<table border="1" style="border-collapse:collapse">';
	for($row_index = 0; $row_index < $rows; $row_index++)
	{
		echo '
<tr>' . "\r\n";
		for($column_index = 0; $column_index < $columns; $column_index++)
		{
			echo '
<td>' . $data_list[$column_index][$row_index] . '' . "\r\n";
		}
		$column_index = 0;
		echo '' . "\r\n";
	}
	echo '</table>
 
';
}
 
// Function Usage
$list = array();
for($i = 0; $i &lt;= 59; $i++)
{
	$list[] = $i+1;
}
//print_vertical_table_sys ($list, 10);

Now my question to you is how would you do that if you come across such requirement? Assume that you have list of array items starting from 1, 2, 3, ..... N and you want to print it with fixed length rows which starts like 1 and next cell will have 11 or something similar (similar to what you see in above image).

It's not that difficult but I would suggest give it a try and you will enjoy. Doesn't matter what technology you work with as the example which I will show you not will not use any functionality specific to PHP. Basically above code snippet is very close to that but I would suggest that before reading further more you give it a try. Come out of your regular work and make this fun exercise. Read the rest of this entry »

Tags: , , , ,

Using Views to avoid cross database connection – MySQL

Table Views can be used as an unconventional way to avoid cross/multiple database connections sometimes..! Yes, it can be. I came across such case and found that it can be handy in some simple cases when we just want to avoid connection to another database on the same MySQL server and we can't afford to create that table in the same database due to some reasons.
Views

Views - Image courtesy Flickr

It's very simple. You can have your table "contacts" in "my_db" database and you want to access this table (not just read need to write/insert and update too) in another database named "another_db".
You can have your "contacts" table in "my_db" with following syntax: Read the rest of this entry »

Tags: ,

Paying the bills.!