Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, 23 August 2018

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 protocal like following,

$.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",

Monday, 19 February 2018

Javascript select list with search by typing in the list

Often we encounter scenarios where we have a long list and the user needs to select an element from the never ending list.

This can be solved by using a simple jQuery plugin.

Here you go chosen is what you need. This page gives you an idea how can you use and which scenarios it can be used. Download it and copy its resouces into you web resources directory.

How to use:

$("#selectList").chosen({
                'width': '25%',
                allow_single_deselect: true
            });   


Update list:

$('#selectList').trigger("chosen:updated");

If you have any doubts please let us know in comment section.

Wednesday, 27 December 2017

Capitalizing first letter and replaceAt particular index of String in Javascript

These are the two functions that will help in most cases where we need to replace index of a particular stiring.

Capitalizing first letter of a string can also be done using css property text-transform:capitalize, in many cases such as if we want to show a stirng with first letter capital in title attribute on hover this does'nt work. So this is handy javascript function that will be useful.


//replaceAt index of particluar string

 
function replaceAt(str, index, replacement) {
    return str.substr(0, index) + replacement + str.substr(index + replacement.length);
}


//capitalize first letter of a string

function capitalizeFirstLetter(string) {

    if(typeof string != "undefined" && string != "" && string != "undefined"){

    return string.charAt(0).toUpperCase() + string.slice(1);

    } else {

            return string;

    }

}

Monday, 27 November 2017

Make a list 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 solutuion): 


//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.

Monday, 18 September 2017

Escape HTML entities in JavaScript variables to render as plain text

Rendering strings containing HTML entities would require special attention as browser can only understand HTML tags and are formatted according to the HTML entities. So this post will help in dealing with such cases which will render HTML entities as plain text in browser.

First step:

1
2
3
4
5
function escapeHtml (string) {
        return String(string).replace(/[&<>"'`=\/]/g, function (s) {
        return entityMap[s];
      });
}

This is the major function that does the espcaping of HTML entities. As you can see it require an entityMap which contains all HTML entities that you want to require.

So here is our enitityMap:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var entityMap = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#39;',
        '/': '&#x2F;',
        '`': '&#x60;',
        '=': '&#x3D;'
};

As you can notice that these are the possible basic HTML entities, you can convert them to escape string that browser understands as plain text.

So what next:

We are all ready and I am giving you a sample text to test this.

1
2
text = escapeHtml(text);
$("#demo").html(text);

When you do all the above mentioned steps correctly, you would get the following result.

1
<स्क्रिप्ट भाषा = PHP> ... </ script> </ Body> # यह एक टिप्पणी है, और print <<<END $ 4 <tab> = <tab2 <tab> + <tab> 2// रिक्त स्थान और टैब <? Php ?>

Observe that all HTML tags are restored as it is.

Still having a problem you can check our live demo over here.



Downloading A Zip File Using Javascript Is Not Rocket Science! Know how!

Initially, the prerequisite for downloading a simple text file in javascript requires FileSaver.js. This can be downloaded from here.

Next step would be the creation of zip file.

1. Download jSZip and load it in your html.

2. Here comes the core part where we initalize jSZip and download a zip file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 var zip = new JSZip();         

    //skip this step if you don't want your files in a folder.
    var folder = zip.folder("example");
    folder.file("myfile1.txt", "HELLO WORLD IN 1ST FILE"); //requires filesaver.js
    folder.file("myfile2.txt", "HELLO WORLD IN 2ND FILE");

    //...so on until you have completed adding files

    zip.generateAsync({type:"blob"})
               .then(function(content) {
                //see FileSaver.js
                saveAs(content, "example.zip");
      });