Monday, 14 April 2014

Australian Universities on Weibo

There are quite a number of Australian Universities on Sina Weibo 新浪微博. Below I list those I have found. I only include those Australian Universities that have verified (the big blue V after the username) Weibo accounts. The text in square brackets is the username on Weibo.
  1. Australian Catholic University [@ACUInternational] weibo.com/acuinternational
  2. Charles Darwin University [@查尔斯达尔文大学] weibo.com/charlesdarwinuni
  3. Curtin University [@科廷大学CurtinUniversity] weibo.com/CurtinWestAustralia
  4. Deakin University [@澳大利亚迪肯大学] weibo.com/deakinuniversity
  5. Federation University [@澳大利亚联邦大学FedUni] weibo.com/FedUniAustralia
  6. Flinders University [@FlindersUni弗林德斯大学] weibo.com/flinders2011
  7. La Trobe University [@澳大利亚拉筹伯大学] weibo.com/latrobeuniaus
  8. Macquaire University [@澳大利亚麦考瑞大学] weibo.com/mquni
  9. Monash University [@MonashUni澳大利亚蒙纳士大学] weibo.com/monashuniversityaust
  10. Queensland University of Technology [@QUT昆士兰科技大学] weibo.com/qutbrisbane
  11. Southern Cross University [@澳大利亚南十字星大学] weibo.com/scuchina
  12. Swinburne University of Technology [@澳洲斯威本科技大学] weibo.com/swinburneuniversity
  13. University of Adelaide [@澳大利亚阿德莱德大学] weibo.com/uniadelaide
  14. University of Canberra [@堪培拉大学] weibo.com/unicanberra
  15. University of Melbourne [@墨尔本大学官微] weibo.com/melbourneuni
  16. University of New South Wales [@澳洲新南威尔士大学] weibo.com/ozunsw
  17. University of Queensland [@昆士兰大学] weibo.com/myuq
  18. University of South Australia [@南澳大学官方微博] weibo.com/studyatunisa
  19. University of Southern Queensland [@澳大利亚南昆士兰大学] weibo.com/usqchina
  20. University of Western Sydney [@西悉尼大学UWS] weibo.com/uwsinternational
  21. University of Wollongong [@澳大利亚卧龙岗大学UOW] weibo.com/uowaustralia

Friday, 11 April 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");
}

Regular Expressions

Regular Expressions are not just about ASCII. They are (or should be) about Unicode, with ASCII being a very small subset of Unicode. The vast majority of Regular Expressions documentation and tutorials I have seen, only deal with ASCII. The consequence is that many/most will never consider non ASCII text strings.

If one considers Unicode text strings then one can process text strings consisting of non Latin Scripts and Symbols. Scripts such as: Cyrillic, Devanagari, Tamil, Georgian, Cherokee, Chinese and Sinhala. Symbols such as: Currency, Arrows, Mathematical Operators, Mahjong Tiles and Playing Cards. Unicode has a repertoire of over 100000 characters which can be processed with Regular Expressions.

Mostly, Regular Expressions are no different when using Unicode as compared to using the very limited ASCII. I will give some simple examples using Hangul, which is the Script used for writing Korean. The Hangul characters I will be using in the examples below are in Unicode block Hangul Syllables U+AC00-D7AF. I will intersperse other Unicode characters in my examples below. I present the examples in the form of a terminal session transcript.
苹果电脑 ~: egrep '바나나'
abcdef
abc바나나def
abc바나나def

苹果电脑 ~: egrep '바.나.나'
바诺丁汉나拉夫堡나
바拉나夫나堡
바拉나夫나堡

苹果电脑 ~: egrep '[바나다]'
abcdef
보노도고로
ДЖԶख나ખ༁
ДЖԶख나ખ༁

苹果电脑 ~: egrep '[가-힣]'
abcdef
abc현def
abc현def

苹果电脑 ~: egrep '^[ 가-힣]+$'
abcdef
abc서울def
서울은 아름답다
서울은 아름답다
Where you see a line duplicated that means there was a successful match with the Regular Expression. I have used egrep on OSX.

The transcript may look a bit odd because of the variety and unfamiliarity of the Unicode characters I have used. If, though, you carefully examine the above Regular Expressions you will see they have standard syntax and are actually elementary constructs. So, if you teach Regular Expressions, why not give your students an insight into processing Unicode strings and not just ASCII strings. Or, to put it another way, give your students an insight into processing multi-language strings and not just English strings. Or, to put it yet another way, code for the whole world and not just the English speaking world.

BTW — 苹果电脑 ~: is the prompt I setup for my iMac and the first four characters are Chinese for Apple Computer.

In the examples above, I have deliberately used one of the standard and common Regular Expression engines. I have accessed this engine via egrep. This type of engine is one which you will most likely encounter. Much less common, are the Regular Expression engines that have been extended with features specifically for Unicode. Such extensions, for instance, facilitate matching with Unicode characters having some specified property e.g. \p{Hangul} will match with any character belonging to the Hangul Script. More information on such engines is available at regular-expressions.info/unicode.html and unicode.org/reports/tr18/

Friday, 4 April 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>

How to pass a Javascript Array to PHP file using AJAX and JSON?

How to pass a Javascript Array to PHP file using AJAX and JSON?

I have an array in javascript and I need to pass this array to a PHP by using AJAX call to that PHP file. I will get this array in PHP file and assign this javascript array to PHP array. Then I will find out the count of that PHP array elements and return it back to the javascript. I will convert JS array in JSON format by JSON.stringify. This is a very simple example on how to pass javascript array to PHP asynchronously. You can perform a lot of operations on this array which you have passed to PHP file but for simplicity I am just returning its count. Let's have a look at the following code snippet.

Javascript Array

var myJSArray = new Array("Saab","Volvo","BMW");

ProcessAJAXRequest() function wil pass JS array to PHP file using AJAX request and will show count of array elements returned by PHP file.

function ProcessAJAXRequest()
{
    $.ajax
    ({
        type: "POST",
        url: "myphpfile.php",
        data: {"myJSArray" : JSON.stringify(myJSArray)},
        success: function (data) 
        {
            alert(data); //count of array elements
        }
    });
}

myphpfile.php

<?php 
    $myPHPArray = json_decode($_POST["myJSArray"]);
    echo count($myPHPArray);
 ?>