Dynamically sorting the table along with other few selection criteria via javascript and php

110 views Asked by At

I have two parts

First part is building dynamic queries based on various inputs

second part is sorting the result table ASC / DESC

PHP part is well tested and working fine

if( !empty( $_REQUEST['cond1'] ) ){
  $sql[] =  mysql_escape_string( $_GET['cond1'] );
}

so on....

until last condition

build the query and get the records

Trigger for sort order is as follows

<table>
   <th><a href="orderby=name&obtype=A">Name</a></th>


</table>

When i click the href

all the selection criteria passed as GET PARAM is lost

Now the query is run only with SORT ORDER of the field.

How do i properly append the

orderby=name&obtype=A

To play around with window.location I am using the following function

  // Function gets a param value from a URL when given a param name
  function getUrlParameter( url, name ) {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( url );
      if( results == null )
          return "";
      else
          return results[1];
  }

  //Attaching Event handler for the heading and
  //finding what column heading is clicked

  $("#result-tbl th").click(function(ev){

    ev.preventDefault();

    // Build a URL from the orderbytriggered
    // Problem is when I click the first column it works
    // When i click the second, third, It keeps on adding all the order by
    // column which is not wanted.
    // Pls help me in finding the problem.
    var c = getUrlParameter( ev.target.href , 'orderby' ),
        d = getUrlParameter( ev.target.href , 'obtype' ),
        newurl = window.location.href + '&orderby=' + c + '&obtype=' + d;
    alert( newurl );
    window.location.href =  newurl;


  });
1

There are 1 answers

2
ThatOneDude On

The current GET PARAMS will be given to you in $_SERVER['QUERY_STRING'] .

Sample output for html:

<?php 
if ($_SERVER['QUERY_STRING']) {
    myQueryString = $_SERVER['QUERY_STRING'] + "&orderby=name&obtype=A"
} else {
    myQueryString = "?orderby=name&obtype=A"
}    
?>

<table>
   <th><a href="<?=myQueryString?>">Name</a></th>
</table>