Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Read-Write JSON file using PHP

Posted in Javascript, Tutorials

With reference to my previous post JSON Tutorial in this posts we will see how to read/write data into JSON file.

[
    {
        "firstName": "Vijay",
        "lastName": "reddy",
        "email": "asdv@ymail.com",
        "mobile": ""
    },
    {
        "firstName": "ggdggg",
        "lastName": "nvnvnv",
        "email": "asddd@xmail.com",
        "mobile": ""
    },
    {
        "firstName": "ggdggg",
        "lastName": "nvnvnv",
        "email": "asddd@xmail.com",
        "mobile": ""
    },
    {
        "firstName": "ggdggg",
        "lastName": "nvnvnv",
        "email": "asddd@xmail.com",
        "mobile": ""
    }
]

We will use above user’s data to read and write it into JSON file. Consider we have a form and we will use this form information to write data into JSON file.

<form action="process.php" method="POST">
	First name:<br>
	<input type="text" name="firstName">
	<br><br/>
	Last name:<br>
	<input type="text" name="lastName">
	<br><br>
	  
	Email:<br>
	<input type="text" name="email">
	<br><br>
	  
	Mobile:<br>
	<input type="text" name="mobile">
	<br><br>
	<input type="submit" value="Submit">
</form>

Our form has action attribute which is pointing to process.php file. In process.php we will write below code.

<?php
   	
   $myFile = "data.json";
   $arr_data = array(); // create empty array

  try
  {
	   //Get form data
	   $formdata = array(
	      'firstName'=> $_POST['firstName'],
	      'lastName'=> $_POST['lastName'],
	      'email'=>$_POST['email'],
	      'mobile'=> $_POST['mobile']
	   );

	   //Get data from existing json file
	   $jsondata = file_get_contents($myFile);

	   // converts json data into array
	   $arr_data = json_decode($jsondata, true);

	   // Push user data to array
	   array_push($arr_data,$formdata);

       //Convert updated array to JSON
	   $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
	   
	   //write json data into data.json file
	   if(file_put_contents($myFile, $jsondata)) {
	        echo 'Data successfully saved';
	    }
	   else 
	        echo "error";

   }
   catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
   }

?>


In above code there is $formdata array in which we are storing form data send by the user. As we have used POST method in our form we are using $POST method in php to get form data. file_get_contents() is PHP function which is used to read data from file. Next we have used json_decode() function to convert JSON data into array. Note this is not a normal text file it’s a JSON file. That’s why we have used json_decode function to convert data into an array. array_push function will add formdata array into existing json array (arr_data). json_encode() will convert array into JSON format, so that we can write this json into json file. Note, we have used JSON_PRETTY_PRINT parameter in json_encode function. This parameter will format our JSON object and store it in json file. If we don’t use this parameter then output which is stored in JSON file will not be well formatted it will be a one line string. JSON_PRETTY_PRINT will work only in PHP version 5.3 and above.

Download source code here

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Window scroll animation using jQuery

Posted in JQuery, Jquery interview questions, Tutorials

It is possible to control scroll behavior of document using JQuery. Use jQuery scrollTop() method to scroll a html page. scrollTop() method returns vertical position of selected element.
Parameters:

  • scrollTop(): returns vertical scroll position of selected element.
  • scrollTop(value): sets scroll bar position to value in pixels.

Example:

$("#div1").scrollTop(300)

Animate scrollTop:

To animate scrollTop() use jQuery animate() method.

Example:

       $('html, body').stop().animate({
            scrollTop: $(link).offset().top
       }, 1000);

Here, link is the id of element to which you want to scroll a page. If you want to scroll a page at particular paragraph or div on click of link use below code.
<a href=”#”>scroll</a>

   $("a").click(function(e) {
        var link = $(this).attr('href');
        if ((link.charAt(0) == "#") && (link.length > 1)) {
             e.preventDefault();
             $('html, body').stop().animate({
                    scrollTop: $(link).offset().top
             }, 1000);
        }
   });

Above code will not work in IE 8. Below is the IE 8 fix to animate scrollTop()

    $("a").click(function(e) {
         var target = $(this.hash);
         target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
         var $main = $('html,body');
         e.preventDefault();
         $main.stop().animate({
               scrollTop: target.offset().top - ($main.offset().top - $main.scrollTop())
          }, 500);
     }); 

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

JSON Tutorial

Posted in javascript interview questions, Json Tutorial, Tutorials

JSON (Javascript Object Notation) is text file stored on a web server. JSON file contains data in text format. It is used to store small amount of data. If your requirement is store huge amount of data then go for a database like MSSQL, MySQL, Oracle etc. JSON is a data store where data is stored in key/value pair format. It is easier to access data from JSON file than XML file.

Below is the syntax for JSON:

Json Syntax

Example:

{
   "name": "John  Michel",
   "age": "28",
   "country": "USA",
   "designation": "Software engineer"
}

This is simple json format. In above example, values are stored in key/value pair format.
Note: JSON is not an object. There is difference between JSON and object in javascript. In JSON, keys and values should be in string format i.e with quotes except number and boolean values.

Example of object:

{
   name: "John  Michel",
   age: 28,
   country: "USA",
  designation: "Software engineer"
}

In above example, keys are not quoted. So this is the main difference between object and json.

Another JSON syntax

{
   "name": "John  Michel",
   "age": "28",
   "country": "USA",
   "designation”: "Software engineer",
   "hobbies": [
                 "cricket",
                 "Listening Music",
                 "LAN Gaming"
              ]
}

In above example, a person can have multiple hobbies. So hobbies is an array. A JSON can contain array.

Arrays in JSON
arrays-in-json

More Complex JSON Structure.

{
    "category-1": {
        "name": "ToothPaste",
        "Products": [
            {
                "name": "colgate",
                "InStock": true,
                "price": "250"
            },
            {
                "name": "Pepsodent",
                "InStock": false,
                "price": "150"
            }
        ]
    },
    "category-2": {
        "name": "Fruit Juice",
        "Products": [
            {
                "name": "Pepsi",
                "InStock": false,
                "price": "110"
            },
            {
                "name": "Sprite",
                "InStock": true,
                "price": "90"
            }
        ]
    },
    "category-3": {
        "name": "Soap",
        "Products": [
            {
                "name": "Lifeboy",
                "InStock": false,
                "price": "110"
            },
            {
                "name": "Cinthol",
                "InStock": true,
                "price": "90"
            }
        ]
    }
}

Retrieve data from JSON.
retrieve-data-from-json

Parameters:

  • url: URL is a string where JSON file is stored
  • data: data is an optional parameter represents key/value pairs that will be sent to the server.
  • Callback: This is called when data is fetched from server.

Example:

Suppose my json file contains below data

{
   "name": "John  Michel",
   "age": "28",
   "country": "USA",
   "designation”: "Software engineer",
   "hobbies": [
                 "cricket",
                 "Listening Music",
                 "LAN Gaming"
              ]
}

Use JQuery $.getJSON method to fetch data.


$.getJSON("http://localhost/data.json", function(data){

           console.log("Name: " + data.name);        // print name
           console.log("Age: " + data.age);                // print age
           console.log("Age: " + data.hobbies[0]);   //  print cricket

 });

In above example, data.json file is stored on your local web server.