Showing posts with label Java Script. Show all posts
Showing posts with label Java Script. Show all posts

Friday, 19 June 2015

Json Parsing using Javascript


In this post we parse a json file display the content of that file in a html page. Here we parse the file using javascript's function JSON.parse()



Here is the Json file we used:
[
  {
    "_id": "5582f8f983abbf96aff0867f",
    "index": 0,
    "guid": "431562f6-3197-4aad-8d85-165a6b28c1bf",
    "isActive": false,
    "balance": "$1,945.59",
    "picture": "http://placehold.it/32x32",
    "age": 36,
    "eyeColor": "blue",
    "name": "Norma White",
    "gender": "female",
    "company": "MAZUDA",
    "email": "normawhite@mazuda.com",
    "phone": "+1 (886) 518-2133",
    "address": "162 Vernon Avenue, Clayville, South Carolina, 9710",
    "about": "Minim elit tempor dolor pariatur ex irure officia 
reprehenderit proident excepteur ea in in non. Consequat 
eiusmod nostrud dolore reprehenderit eu laborum sunt. Eiusmod 
nostrud cillum officia elit et incididunt incididunt commodo 
dolore non. In minim nisi in id commodo ut.\r\n",
    "registered": "2015-06-02T01:21:13 -06:-30",
    "latitude": -50.456627,
    "longitude": -140.03817,
    "tags": [
      "dolor",
      "elit",
      "ipsum",
      "Lorem",
      "laboris",
      "sint",
      "aliqua"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Maribel Wheeler"
      },
      {
        "id": 1,
        "name": "Letha Reid"
      },
      {
        "id": 2,
        "name": "Jenkins Mcbride"
      }
    ],
    "greeting": "Hello, Norma White! You have 4 unread 
messages.",
    "favoriteFruit": "apple"
  },
  {
    "_id": "5582f8f9cc0397850d491ea2",
    "index": 1,
    "guid": "7f980900-413b-4647-8254-ffb70fe5d394",
    "isActive": false,
    "balance": "$3,427.90",
    "picture": "http://placehold.it/32x32",
    "age": 34,
    "eyeColor": "green",
    "name": "Delores Cash",
    "gender": "female",
    "company": "INFOTRIPS",
    "email": "delorescash@infotrips.com",
    "phone": "+1 (934) 465-3926",
    "address": "602 Tudor Terrace, Croom, Alaska, 3367",
    "about": "Ex incididunt incididunt dolore sunt non aliqua 
exercitation aute elit ad ex. Non irure sunt excepteur ex et id 
nisi ipsum adipisicing nisi. Non aliquip nulla ullamco ullamco 
anim fugiat ullamco dolore magna reprehenderit mollit tempor 
fugiat.\r\n",
    "registered": "2014-03-30T11:28:04 -06:-30",
    "latitude": 20.412092,
    "longitude": -24.360202,
    "tags": [
      "adipisicing",
      "qui",
      "aute",
      "consequat",
      "incididunt",
      "sunt",
      "do"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Cherry Giles"
      },
      {
        "id": 1,
        "name": "Liz Brooks"
      },
      {
        "id": 2,
        "name": "Estela Thompson"
      }
    ],
    "greeting": "Hello, Delores Cash! You have 2 unread 
messages.",
    "favoriteFruit": "strawberry"
  },
  {
    "_id": "5582f8f952fc2e8172d3d49f",
    "index": 2,
    "guid": "f456df49-1082-4cd1-a989-08f580b8a39f",
    "isActive": false,
    "balance": "$3,487.59",
    "picture": "http://placehold.it/32x32",
    "age": 28,
    "eyeColor": "blue",
    "name": "Cortez Thomas",
    "gender": "male",
    "company": "SPLINX",
    "email": "cortezthomas@splinx.com",
    "phone": "+1 (954) 590-3960",
    "address": "801 Roosevelt Court, Vale, Ohio, 9448",
    "about": "Consequat dolor aliqua do minim ipsum minim elit 
sint minim minim sit dolor. Id et cupidatat esse consectetur 
voluptate id cillum non excepteur laboris laboris anim do 
aliqua. Dolor nisi labore ea ipsum enim magna ea tempor eiusmod 
id. Esse occaecat aliquip laborum officia duis laboris 
nisi.\r\n",
    "registered": "2014-10-29T07:15:24 -06:-30",
    "latitude": 4.709781,
    "longitude": 73.445115,
    "tags": [
      "excepteur",
      "incididunt",
      "eu",
      "non",
      "proident",
      "sit",
      "nisi"
    ],
   
    "greeting": "Hello, Cortez Thomas! You have 3 unread 
messages.",
    "favoriteFruit": "apple"
  },
  {
    "_id": "5582f8f94359b04b61961764",
    "index": 3,
    "guid": "642c9764-f136-43fa-b9ee-c9fbdb14f5db",
    "isActive": true,
    "balance": "$3,932.63",
    "picture": "http://placehold.it/32x32",
    "age": 23,
    "eyeColor": "brown",
    "name": "Christine Levine",
    "gender": "female",
    "company": "HELIXO",
    "email": "christinelevine@helixo.com",
    "phone": "+1 (966) 487-3878",
    "address": "757 Imlay Street, Summerset, Utah, 169",
    "about": "Exercitation ad nostrud enim commodo aute anim 
dolor adipisicing incididunt. Cillum ex commodo dolor nisi 
nulla id proident occaecat amet adipisicing eiusmod duis. 
Eiusmod nisi exercitation deserunt in incididunt magna dolor. 
Fugiat do nulla non est. Enim magna labore irure in.\r\n",
    "registered": "2014-09-03T05:45:06 -06:-30",
    "latitude": -66.575199,
    "longitude": -66.479327,
    "tags": [
      "eiusmod",
      "qui",
      "aute",
      "ea",
      "ut",
      "qui",
      "qui"
    ],
    
    "greeting": "Hello, Christine Levine! You have 6 unread 
messages.",
    "favoriteFruit": "apple"
  },
  {
    "_id": "5582f8f96b9f9e87d16f4544",
    "index": 4,
    "guid": "ec7cd607-dd0b-466f-9c8a-38bf430c145f",
    "isActive": true,
    "balance": "$2,895.67",
    "picture": "http://placehold.it/32x32",
    "age": 21,
    "eyeColor": "brown",
    "name": "Naomi Miller",
    "gender": "female",
    "company": "RONELON",
    "email": "naomimiller@ronelon.com",
    "phone": "+1 (950) 583-2168",
    "address": "339 Keap Street, Singer, Oklahoma, 9244",
    "about": "Esse fugiat consectetur id magna nisi. Elit 
laboris tempor tempor laboris aute consectetur labore mollit 
anim veniam do dolore. Magna quis irure deserunt sunt ex esse 
esse cillum. Incididunt irure laboris tempor et mollit 
adipisicing ullamco in elit. Commodo incididunt sint sunt sunt 
nostrud consequat magna proident anim ea. Cillum nulla ad ea 
enim officia occaecat reprehenderit nostrud nulla do 
adipisicing cillum.\r\n",
    "registered": "2014-10-18T20:21:26 -06:-30",
    "latitude": -18.367898,
    "longitude": -117.26177,
    "tags": [
      "cupidatat",
      "deserunt",
      "consectetur",
      "et",
      "laboris",
      "duis",
      "proident"
    ],
    
    "greeting": "Hello, Naomi Miller! You have 4 unread 
messages.",
    "favoriteFruit": "banana"
  }
]
This is random json data generated from http://json-generator.appspot.com/
The link for this file is http://json-generator.appspot.com/api/json/get/bMGRMYBGEO?indent=2


Now we parse that data using javascript functon JSON.parse we also use XMLHttpRequest function to get this file over the internet.

Source Code :

<!DOCTYPE html>
<html>
<body>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://json-generator.appspot.com/api/json/get/bMGRMYBGEO?indent=2";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var myArr = JSON.parse(xmlhttp.responseText);
    document.getElementById("btn").onclick = function() {myFunction(myArr)};
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
    var result = "";
    var i;
  
    for(i = 0; i < arr.length; i++) {
        result += "<h1>Person "+ i + "</h1><table><tr><td>Id:
</td><td>"+arr[i]._id+"</td></tr><tr><td>Name:</td>
<td>"+arr[i].name+"</td></tr><tr><td>Age:</td>
<td>"+arr[i].age+"</td></tr><tr><td>Gender:</td>
<td>"+arr[i].gender+"</td></tr><tr><td>Picture:</td><td><img 
src="+arr[i].picture+"/></td></tr><tr><td>Company:</td>
<td>"+arr[i].company+"</td></tr><tr><td>Email:</td>
<td>"+arr[i].email+"</td></tr><tr><td>Phone :</td>
<td>"+arr[i].phone+"</td></tr><tr><td>Address:</td>
<td>"+arr[i].address+"</td></tr><tr><td>About:</td>
<td>"+arr[i].about+"</td></tr><tr><td>Latitude:</td>
<td>"+arr[i].latitude+"</td></tr><tr><td>Longitude:</td>
<td>"+arr[i].longitude+"</td></tr><tr><td>Balance:</td>
<td>"+arr[i].balance+"</td></tr><tr><td>Greeting :</td>
<td>"+arr[i].greeting+"</td></tr><tr><td>Fav Fruit :</td>
<td>"+arr[i].favoriteFruit+"</td></tr><tr><td>guid:</td>
<td>"+arr[i].guid+"</td></tr><tr><td>Registered:</td>
<td>"+arr[i].registered+"</td></tr><tr><td>Active ?:</td>
<td>"+arr[i].isActive+"</td></tr><tr><td>Eye Color::</td>
<td>"+arr[i].eyeColor+"</td></tr><tr><td>Index:</td>
<td>"+arr[i].index+"</td></tr><tr><td>Tags:</td>
<td>"+arr[i].tags+"</td></tr></table><br><hr><br>"    

    }
 
    document.getElementById("showResult").innerHTML = result;
}
</script>
<button type="button" id="btn">Parse Text </button>
<div id="showResult"></div>

</body>

</html>


Result : 


Sunday, 18 January 2015

Java Script alert Example


This is a simple tutorial on how to create a Java Script alert.
In Java Script there is a predefined function called alert() we now just invokes that function. Here we create a button and when button is clicked we call the alert() function with a custom text .

Lets see,

Java Script alert Example


Java Script alert Example


PROGRAM :

<!DOCTYPE html>
<html>
<body>
 
    <p>Click the button to display an alert box.</p>
 
    <button onclick="alert('This is a sample alert !');">Click me</button>
 
</body>
</html>


OUTPUT :

Click the button to show an alert box.

Fibonacci Series with JavaScript


This is a simple Java Script code which displays the fibonacci series upto the range given.

First we create a text field to enter some value and a button which on clicked calls the JavaScript function.

The HTML part is ,
Enter Some Value :<input type = "text" id= "val" ></input></br>
 <input type = "button" value ="Calculate"  onclick="fibonacci()">


then it looks like,
JavaScript  - Fibonacci Series

Now when  we enter the value and click the 'Calculate' button the script for calculating fibonacci will run,
<script type="text/javascript">
 function fibonacci(){
        var a = 0, b = 1, c = 0;
        var res = document.getElementById("val").value;
    
        while (b <= res) {

            document.write(c);
   document.write("</br>");
   
            c = a + b;
            a = b;
            b = c;
 
        }
 }
    </script>
JavaScript  - Fibonacci Series

The function fibonacci()  gets the input from the html by,
var res = document.getElementById("val").value;

now we will perform the actual logic for generating finonacci series
while (b <= res) {

            document.write(c);
   document.write("</br>");
   
            c = a + b;
            a = b;
            b = c;
 
        }


JavaScript  - Fibonacci Series

The complete HTML file  code is as below,
<html>
   <body>
      Enter Some Value :<input type = "text" id= "val" ></input></br>
      <input type = "button" value ="Calculate"  onclick="fibonacci()">
<script type="text/javascript">
         function fibonacci(){
                var a = 0, b = 1, c = 0;
                var res = document.getElementById("val").value;
            
                while (b <= res) {
         
                    document.write(c);
                    document.write("</br>");
           
                    c = a + b;
                    a = b;
                    b = c;
         
                }
         }
           
</script>
   </body>
</html>


OUTPUT : 
Enter Some Value :




Tuesday, 13 January 2015

Reading values from HTML and processing those values in Java Script


All of us know HTML is only static representation of a web  page , we always wanted to add some functionality to it. For getting started with JavaScript is the best one. Lets now see a basic HTML page with some JavaScripting in it.

Here we will take two text boxes for entering 2 values and 4 buttons for addition, substraction ,multiplication and division respectively. When we enter some values in those textboxes and press any button then using JavaScript we perform the calculation and return the result.

For each textbox we will give some id so as to refer them in JavaScript

Enter first number:
<input type ="text" id="1stnum"  /><br>
Enter second number:
<input type ="text" id="2ndnum"  /><br>

we will also have 4 functions for calculating their sum , product , differencs and division respectively andwe call a function corresponding to it  when the button is clicked .
<input type="button" id="sum" value="sum" onclick="findsum()"/>
<input type="button" id="sub"value="sub" onclick="findsub()"/>
<input type="button" id="mul"value="mul" onclick="findmul()"/>
<input type="button" id="mul"value="div" onclick="finddiv()"/>

Now when any button is clicked its corresponding function is called.

We will get the value of the textbox in JavaScript by using
document.getElementById("elementId").value;

So now for getting the values of the 2  text boxes we use
document.getElementById("1stnum").value;

document.getElementById("2ndnum").value;

we will store those 2 values in variables x and y respectively and we will simply add or substract or multiply or divide x,y and store the result in another variable z.

Now for the result to show we will create an empty paragraph with some id and set the result to that empty paragarph.
<p id = "result"></p>

The Complete code is here,
<html>
<head>
<title>JavaScript Example</title>

<script>
function findsum()
{
    var y = document.getElementById("1stnum").value;
    var z = document.getElementById("2ndnum").value;
    var x = +y + +z;
    document.getElementById("result").innerHTML = "Sum is :" + x;
}
function findmul()
{
    var y = document.getElementById("1stnum").value;
    var z = document.getElementById("2ndnum").value;
    var x = +y * +z;
    document.getElementById("result").innerHTML = "Product is :" + x;
}
function findsub()
{
    var y = document.getElementById("1stnum").value;
    var z = document.getElementById("2ndnum").value;
    var x = +y - +z;
    document.getElementById("result").innerHTML = "Difference is :" + x;
}
function finddiv()
{
    var y = document.getElementById("1stnum").value;
    var z = document.getElementById("2ndnum").value;
    var x = +y / +z;
    document.getElementById("result").innerHTML = "Division is :" + x;
}</script>
</head>
<body style="text-align:center";>
<form>
Enter first number:
<input type ="text" id="1stnum"  /><br>
Enter second number:
<input type ="text" id="2ndnum"  /><br>
<input type="button" id="sum" value="sum" onclick="findsum()"/>
<input type="button" id="sub"value="sub" onclick="findsub()"/>
<input type="button" id="mul"value="mul" onclick="findmul()"/>
<input type="button" id="mul"value="div" onclick="finddiv()"/><br><br>

</form>
<p id = "result"></p>

</body>
</html>

OUTPUT :

Enter first number:
Enter second number: