Category: jQUery

Handling special characters in jQuery selectors

When we make dynamic id in Javascript sometimes it may happen that it can contain special characters like @/space/ something which might be difficult to access the element back using the jQuery selector.

So this article will help you manage such special characters so that the Javascript on that page does not break and throw any error for smooth accessing of the web page.

First create a function like below and place it in a common place where you will access it.

function escapeSelector( myid ) {
console.log(myid);
return myid.replace( /[:|.|[|]|,|=|@ ]/g, "\$&" );
}

Notice that the function accepts a parameter id which will escape the special characters using regex and then return it.

Now just call the above function whenver you are using jQuery selector to select that element.

For exmaple:

var element = $('tr[id^=' + escapeSelector(id) + ').attr("data-filename");

So the above line of code is selecting a particular td element with the id which is now being escaped to handle special characters.

HTTPS to HTTP Ajax Request, Same Origin Policy.

Often there are times where we need to make a request that might not obey the Same Origin Policy . So here I am going to address Different Protocal issue in Same Origin Policy. Suppose we are making a http request from a server with HTTPS protocol in the following way.

$.ajax({
        url: 'http://MyAjaxHTTP Path',
        type: 'POST',
        data: 'param1=value1&param2=value',
        header: "application/x-www-form-urlencoded",

The above request cannot be made because it violates same origin policy. So we have to write a layer code between JavaScript and the HTTP server that directly interacts with HTTP. So first we have to choose a server side language for this. I am choosing PHP.

In PHP (phplayer.php):

$param1 = $_POST["param1"];
$param2 = $_POST["param2"];
$data = array(“param1”=>$param1, "$param2"=>$param2);

$data = http_build_query($data);
header('content-type: application/json');
$context_options =  array(
        'http' => array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $data
        ));
$context  = stream_context_create($context_options);

//notice that our actual HTTP URL is called here
$result = file_get_contents("http://MyAjaxHTTPPath", false, $context);
echo $result;

In JavaScript everything remains same except that we have to make a call to our layer PHP code that will actually make a HTTP request and get back the response.

$.ajax({
        url: 'phplayer.php',
        type: 'POST',
        data: "param1=value1&param2=value",
        header: "application/x-www-form-urlencoded",

Make a list menu element active when included using php include

Often there is a requirement to make a menu element active when we import something using php include. Its quite simple and this is how its done.

<? php include "includes/sidebar.php"; ?>  

(sidebar.php):

<ul id="sidebar">
  <li><a href="link1.html">Link1</a></li>
  <li><a href="link2.html">Link2</a></li>
  <li><a href="link3.html">Link3</a></li>
  <li><a href="link4.html">Link4</a></li>
</ul>

CSS:

ul#sidebar > li.active {
 background-color:#6495ED;
 color:#fff;
}

JavaScript (jQUery solution):

//current url being access
 var cur_href = window.location.href;
 $(document).ready(function(){
  $("#sidebar li a").each(function(){
   //get current href link
   var cur_attr =$(this).attr('href');  
   //save into regex
   var regex = new RegExp(cur_attr,"ig");
   //test if current link and current href matched
   if(regex.test(cur_href)) {
    $(this).parent().addClass('active'); //if yes then addClass 'active'
   } else {
    $(this).parent().removeClass('active'); //else removeClass 'active'
   }
  });
 });

This will make current menu link active in sidebar.