Hyperlink to Call JavaScript Function

You can show hyperlink using set_col_link for static link or set_col_dynalink for dynamic link. What about if you want to do something even fancier, like open a new window, or trigger a JavaScript event when hyperlink is clicked?

To call JavaScript function on hyperlink click, use “showlink” in set_col_format method.

In the following example, the first set_col_format displays text in alert window using JavaScript function “myFunction” to retrieved text from a different cell in the same row. The second does a phpgrid.com site search using jQuery Ajax function “phpGridSiteAjaxSearch”, and displays the result in a alert message window.

PHP:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Always include namespace and conf.php on TOP of the script.
use phpCtrl\C_DataGrid;
require_once("/file/path/to/conf.php");  

$dg = new C_DataGrid("select * from products", "productCode", "products");
$dg -> set_col_title("productCode", "Product Code");
$dg -> set_col_title("productName", "Product Name");
$dg -> set_col_title("productLine", "Product Line");

$dg->set_col_format("productLine", "showlink", array("baseLinkUrl"=>"javascript:", "target"=>"_self",
"showAction"=>"myFunction(jQuery('#products'),'",
"addParam"=>"');"));

$dg->set_col_format("productName", "showlink", array("baseLinkUrl"=>"javascript:", "target"=>"_self",
"showAction"=>"phpGridSiteAjaxSearch(jQuery('#products'),'",
"addParam"=>"');"));
$dg -> display();

JavaScript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
myFunction = function(grid, param) {
    var ar = param.split('=');
    if (grid.length > 0 && ar.length === 2 && ar[0] === '?id') {
        var rowid = ar[1];
        var prodDesc = grid.getCell(rowid, 'productDescription');

        alert(prodDesc);
    }
};

phpGridSiteAjaxSearch = function(grid, param) {
    var ar = param.split('=');
    if (grid.length > 0 && ar.length === 2 && ar[0] === '?id') {
        var rowid = ar[1];
        var productName = grid.getCell(rowid, 'productName');

        jQuery.ajax({
            url: 'https://phpgrid.com',
            data: {
                s: productName
            },
            type: 'GET',
            dataType: 'text',
            success: function(data, status) {
                // your code goes here for a successul Ajax call .e.g open a new window
                alert(data);
            },
            error: function(data, status, err) {
                alert(data + status);
            }
        });
    }
};

See Live Example