Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Friday, April 11, 2014

How to use Javascript localStorage to retain values of HTML input elements on Page Refresh?

How to use Javascript localStorage to retain values of HTML input elements on Page Refresh?

localStorage in Javascript is used to retain the values of the HTML input elements on the page refresh. setItem() and getItem() methods are used to set and get the data from the localStorage. clear() method is used to clear the data from the localStorage.

Suppose I have following 2 textboxes and buttons in my HTML page. 

<input type="text" id="text1" value="" />
<button type="button" id="myButton1" onclick="myButtonClicked('text1')">Click Me</button>

<input type="text" id="text2" value="" />
<button type="button" id="myButton2" onclick="myButtonClicked('text2')">Click Me</button>

I fill some data in each textbox. Now when I refresh the page, the data is lost. I want to retain that data on the page refresh. I will use localStorage for this purpose. 

//Store values on button click
function myButtonClicked(id)
{
var aLocalStorage = [];
if(localStorage.getItem('myLocalStorage') != null)
{
aLocalStorage = JSON.parse(localStorage.getItem('myLocalStorage'));
//get stored item from localStorage by json parsing
}
    aLocalStorage.push(id);
    aLocalStorage.push(document.getElementById(id).value);
    localStorage.setItem('myLocalStorage', JSON.stringify(aLocalStorage));
    //stored the entered element id and value in localStorage by doing stringify
}

Now when the page is refresh, call the following function on $(Idocument).ready event like this

$(document).ready(function()
{
retainValues();
});

function retainValues()
{
if(localStorage.getItem('myLocalStorage') != null)
{
var aLocalStorage =[];
aLocalStorage = JSON.parse(localStorage.getItem('myLocalStorage'));

var i = 0;
while (i < aLocalStorage.length)
{   
if (document.getElementById(aLocalStorage[i]) != null)
{
document.getElementById(aLocalStorage[i]).value = shoppingCartList[i+1];
}
i = i + 2;
}
}
}

How to call both Javascript function with PHP file on the click on HTML link?

How to call both Javascript function with PHP file on the click on HTML link?

Recently, I was trying to implement logout functionality while working with PHP website. I had put logout logic in logout.php file and I was calling that file on the click of logout link like following:

<a href="logout.php">Logout</a>

This was working fine. But later on I realised that I also have to clear localstorage maintained by using Javascript before logging out the user. So, I had to call the javascript function that clears the localstorage before calling the logout.php file. 

Javascript function for clearing the localstorage:

function ClearMyLocalStorage()
{
localStorage.clear();
}

I investigated two approaches to accomplish my task.

Approach 1:

<a href="logout.php" onclick="ClearMyLocalStorage()">

Approach 2:

<a href="javascript:;" onclick="ClearMyLocalStorage();">Logout</a>

And in your function you have to write like

function ClearMyLocalStorage()
{
    localStorage.clear();
    window.location.href = 'logout.php';
}

How to change InnerHTML of all the HTML Buttons in one go using jQuery?

How to change InnerHTML of all the HTML Buttons in one go using jQuery?

Suppose, I have 5 buttons on my page. How can I change the innerHTML of the buttons in one go using jQuery? I want that buttons having text "Clicked" should get changed to "Click me" when Change InnerHTML button is clicked. I will use jQuery to solve this problem. Refer the following example.

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function ChangeInnerHTML()
{
//Iterate all the buttons with innerHTML = "Clicked" in the DOM and set them to "Click me".
}
</script>
</head>
<body>
<button type="button" id="myButton1">Click me</button>
<button type="button" id="myButton2">Clicked</button>
<button type="button" id="myButton3">Click me</button>
<button type="button" id="myButton4">Clicked</button>
<button type="button" id="myButton5">Click me</button>

<button type="button" id="btnChangeInnerHTML"      onclick="ChangeInnerHTML()">Change InnerHTML</button>

</body>
 </html>

 There are many approaches for doing this task.

Approach 1:

 function ChangeInnerHTML() {
    $('button').each(function() {
        if ($.trim($(this).html()) == "Clicked") 
            $(this).html('Click me');
    });
}

Approach 2:

Use Attribute selector in jquery.

function ChangeInnerHTML() 
{
$("[id^=myButton]:contains('Clicked')").click(function() {
$(this).text("Click Me");

});
}

Approach 3:

function ChangeInnerHTML()
{
document.body.innerHTML=
document.body.innerHTML.replace(/Clicked/g,'Click me');
}

Approach 4:

Without jQuery

function ChangeInnerHTML() 
{
    var btns = document.querySelectorAll('button[id^=myButton]');
    for (var i = 0; i < btns.length; i++) {
        if (btns[i].innerHTML.trim() == 'Clicked') {
            btns[i].innerHTML = 'Click Me'
        }
    }
}

Approach 5:

This will change the innerHTML of all the buttons.

function ChangeInnerHTML()
{
    $("button[id*=myButton]").html("Click me");
}

Friday, April 4, 2014

How to return value from child window to parent window using window.open in Javascript?

How to return value from child window to parent window using window.open in Javascript?

It is very easy to return a value from a child window to parent window which has been opened from parent window using window.open method in Javascript. In many scenarios, it is possible to do some calculations on the child window and parent window need the result of that calculations to perform some task. So, let's try to resolve this problem.

In Parent Window

I have following Javascript function which will open a child window named childWin. I also have a function which will catch the value returned by the child window.

function openChildWin() 
{   
    var childWin = window.open("childWin.html", "_blank", "height=400, width=550, status=yes, toolbar=no, menubar=no, location=no,addressbar=no); 
}

function setValue(val1) 
{
   //you can use the value here which has been returned by your child window
}

ChildWin.html page

Following is my childWin HTML page. There is a button on this HTML page which when clicked will return a value to the parent window which has setValue function. Basically, child window is accessing parent's setValue function here. After this, child window is closed.

<!DOCTYPE html>
<html lang="en">
  <head>

<script type="text/javascript">

function OKClicked()
{
window.opener.setValue('Hello');; //I want to return true here
window.close(); //Close this child window  
}

</script>

  </head>
  <body>
<button type="button" id="OKButton" onclick="OKClicked()">Click ME</button>
  </body>
 </html>

Friday, December 20, 2013

How to allow HTML Textbox to accept Numbers only using Javascript?

How to allow HTML Textbox to accept Numbers only using Javascript?

While web development, you often encounter the need of functionality where your textboxes should be filled with numbers only.

For example, you want your users to fill the quantity of anything, ID (if it is composed on integers only), price of anything (excluding decimal) etc. In short, you want only numbers plus some keys like backspace, delete. left and right arrow to be typed in the textbox. You can use javascript to restrict your users to fill only numbers in the textbox. It is very simple. On the KeyPress event of any HTML text, just call a simple javascript function which checks the keycodes for the numbers and on the basis of keycodes, it returns true or false. Here is how?

HTML Text

<input type="text" id="txtSample" name="txtSample" onkeypress="return CheckNumeric(event)" />

Javascript 

function CheckNumeric(event)
{
       var key = window.event ? event.keyCode : event.which;

        //Check for backspace, delete, left arrow and right arrow keys

if (event.keyCode == 8  || event.keyCode == 46 ||  
           event.keyCode == 37 || event.keyCode == 39) 
{
return true;
}

        //All other keys excluding numeric keys 

else if ( key < 48 || key > 57 ) 
{
return false;
}

else return true; //Numeric keys from 0 to 9
};

Wednesday, November 27, 2013

HTML5 MENU Tag Redefined

HTML5 <menu> Tag Redefined

The <menu> tag provides an easy way to create menus on a web page. The HTML <menu> element was deprecated in HTML 4.01 but is redefined in HTML5. The HTML <menu> tag defines a list/menu of commands. The <menu> tag is used for context menus, toolbars and for listing form controls and commands.

<li> tag is used within the <menu> tag. For example:

Which pet do you own?
<menu>
 <li>Dog</li>
 <li>Cat</li>
</menu>

You can also place radio buttons and check boxes inside <menu> tags. Have a look at following simple example of <menu> tag

radiobuttons inside <menu> tag

<menu>
   <li><input type="radio" id="radDog" class="radPets" name="radDog"/>Dog</li>
   <li><input type="radio" id="radCat" class="radPets" name="radCat"/>Cat</li>
</menu>

checkboxes inside <menu> tag

<menu>
   <li><input type="checkbox" id="cbDog" class="cbPets" name="cbDog"/>Dog</li>
   <li><input type="checkbox" id="cbCat" class="cbPets" name="cbCat"/>Cat</li>
</menu>

<menu> tag is used instead of <ul> tag

Earlier we used to make an unordered list by using <ul> tag like this:

<ul class="toolbar">
  <li>New</li>
  <li>Open</li>
  <li>Save</li>
  <li>Quit</li>
</ul>

But as I earlier said, <menu> is redefined in HTML5. The <menu> element represents an unordered list of commands. It has a type attribute, which can be set to popup or toolbar.

<menu type="toolbar">
  <li>New</li>
  <li>Open</li>
  <li>Save</li>
  <li>Quit</li>
</menu>

Please note: The <menu> tag is valid within blockquote, body, button, center, dd, div, fieldset, form, iframe, li, noframes, noscript, object, td and th tags.

Saturday, November 23, 2013

How to secure jQuery AJAX calls in PHP from hackers?

How to secure jQuery AJAX calls in PHP from hackers?

If you are making jQuery AJAX calls in your PHP website, please ensure that those jQuery AJAX calls are secure from website hackers. Your code should not be vulnerable to hackers. Below are some methods and steps which need to be taken to secure your jQuery AJAX calls to PHP files. I am writing this post because I had written a simple post "How to call PHP function from JavaScript function? Always use AJAX." without mentioning any security code. I got following comment on that post:

"Your code is very vulnerable. You're not filtering the $_POST variable at all. This opens yourself to HTML injection. A hacker could pwn your web site very quickly if you used this code. Careless examples like yours is exactly why so many web sites are hacked."

That's why this is my small attempt to make your jQuery AJAX calls secure. 

1. Use $_SERVER['HTTP_X_REQUESTED_WITH']

This is a basic check to see if the request is an Ajax request or not?

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&       strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
{
    //Request identified as ajax request
}

However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.

2. Use $_SERVER['HTTP_REFERER']

if(@isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
{
 //Request identified as ajax request
}

But not all browsers set it. So don't properly rely on it but yes, to some extent it can secure your webpage.

Nobody can AJAX your site from other domain, but always can connect and drieclty send http request, for example by cURL.

JavaScript running on another domain cannot access any page on your domain because this is a violation of the Same-Origin Policy. The attacker would need to exploit an XSS vulnerability in order to pull this off. In short you don't need to worry about this specific attack, just the same old attacks that affect every web application.

3. Generate Access Tokens

$token = md5(rand(1000,9999)); //you can use any encryption
$_SESSION['token'] = $token; //store it as session variable

You can create some token in cookies, that will be also seen from jquery request, but that solution can also be hacked.

4. Always check $_POST variables in your PHP file whether those are set or not? Whether there is valid value in $_POST or not before executing the actual PHP code.

Basic code snippet for securing your jQuery AJAX calls in PHP

Step-1 : Generate Token System For All Web-Service:

Generating Token :

<?php
  session_start();
  $token = md5(rand(1000,9999)); //you can use any encryption
  $_SESSION['token'] = $token; //store it as session variable
?>

Step-2 : Use it while sending ajax call:

var form_data = 
{
  data: $("#data").val(), //your data being sent with ajax
  token:'<?php echo $token; ?>', //used token here.
  is_ajax: 1
};

$.ajax({
  type: "POST",
  url: 'yourajax_url_here',
  data: form_data,
  success: function(response)
  {
    //do further
  }
});

Step-3 : NOW, Let's secure ajax handler PHP file with,

session_start(); 
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') 
{
  //Request identified as ajax request

  if(@isset($_SERVER['HTTP_REFERER']) &&    $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
  {
   //HTTP_REFERER verification
    if($_POST['token'] == $_SESSION['token']) {
      //do your ajax task
      //don't forget to use sql injection prevention here.
    }
    else
   {
      header('Location: http://yourdomain.com');
    }
  }
  else 
  {
    header('Location: http://yourdomain.com');
  }
}
else 
{
  header('Location: http://yourdomain.com');
}

Thursday, October 18, 2012

HTML5: List of New Features

HTML5: List of New Features

1. In HTML5, there is only one <!doctype> declaration: <!DOCTYPE html>

2. HTML5 is totally based on HTML, CSS, DOM, and JavaScript.

3. HTML5 includes new elements for better structure, better form handling, drawing, and for media content.

4. HTML5 has much more markups to replace scripting.

5. HTML5 has new form controls, like calendar, date, time, email, url, search.

6. HTML5 has new content-specific elements, like <article>, <aside>, <footer>, <header>, <nav>, <section>, <details>, <summary>, <figure>, <progress> etc.

7. Media Elements: HTML5 eliminates the need of Flash. HTML5 has added new media elements like <video>, <audio>, <source>, <embed>, <track> for media playback.
  
   <video width="320" height="240" controls="controls" autoplay="autoplay">
      <source src="movie.mp4" type="video/mp4">
      Your browser does not support the video tag.
   </video>
  

   <audio controls="controls">
       <source src="horse.ogg" type="audio/ogg">
      <source src="horse.mp3" type="audio/mpeg">
      Your browser does not support the audio element.
   </audio>

The control attribute adds audio controls, like play, pause, and volume.

You should also insert text content between the <audio> and </audio> tags for browsers that do not support the <audio> element.

The <audio> element allows multiple <source> elements. <source> elements can link to different audio files. The browser will use the first recognized format.

8. Canvas Element: HTML5 has <canvas> element for 2D drawing. The HTML5 <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript).
The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, characters, and adding images. A canvas is a rectangular area on an HTML page, and it is specified with the <canvas> element. 
 
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>

You can use following javascript code to draw a 2 dimensional rectange and fill it with red color:
 
<script>
   var c=document.getElementById("myCanvas");
   var ctx=c.getContext("2d");
   ctx.fillStyle="#FF0000";
   ctx.fillRect(0,0,150,75);
</script> 
The default fillStyle is #000000 (black).

9. Local Storage: HTML5 supports local storage and replaces the need of cookies. With HTML5, web pages can store data locally within the user's browser.

Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website's performance. The data is stored in key/value pairs, and a web page can only access data stored by itself.
 
10. HTML5 Web Worker Feature: A web worker is a javaScript running in the background, without affecting the performance of the page. When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. A web worker is a javaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

11. HTML Server-Sent Events(SSE) Feature(One Way Messages): A server-sent event is when a web page automatically gets updates from a server. This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.

Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.
 
12. HTML5 Application Cache Feature: HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection.

Application cache gives an application three advantages:
  • Offline browsing - users can use the application when they're offline
  • Speed - cached resources load faster
  • Reduced server load - the browser will only download updated/changed resources from the server

13. Geolocation: HTML5 supports Geolocation API which is used to get the geographical position of a user.

14. Drag and Drop: HTML5 supports Drag and Drop feature.

15. SVG: HTML5 has support for inline SVG(Scalable Vector Graphics).

16. HTML5 is device independent.

17. HTML5 has better error handling.

18. Removed Elements: HTML5 has removed <acronym>, <applet>, <basefont>, <big>, <center>, <dir>, <font>, <frame>, <frameset>, <noframes>, <strike> and <tt> elements.