Saturday, March 1, 2014

JSON Examples in PHP




JSON: JavaScript Object Notation.  
JSON is smaller than XML and easy to parse.
JSON format:
a name followed by colon, followed by a value, such as
"fruit":"apple"
i.e fruit = "apple"
JSON object using curly bracket
var  temp={"fruit":"apple", "juice":"orange"}
To access JSON object value:
temp.fruit, temp.juice
JSON array using square bracket:
var JSONarray= {
"food":[
{"fruit":"apple", "juice":"orange"},
{"fruit":"banana", "juice":"watermelon"}
]
}


To access the value  apple in array
JSONarray.food[0].fruit
Example 1: convert.php - Convert PHP associative array to javascript associative array

 <?php
 //Example 1: Convert PHP associative array to javascript associative array
$arr = array('price' => 2, 'high' => 3, 'low' => 1);
echo json_encode($arr);
?>
<script>
    var quote=<?php echo json_encode($arr); ?>;
    alert(quote["price"]);
    alert(quote.price);
</script>

Example 2: jQuery Ajax Jason example in PHP form
test.php
<html>
    <head>
       <title>jQuery Ajax Jason example</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
     <script type="text/javascript">
     $(document).ready(function() {

            $("#submit").click(function(){

            $.ajax({
            url: "post.php",
            type: "POST",
            data: {
                message: $("#message").val(),
                firstName: $("#firstName").val(),
                lastName: $("#lastName").val(),
                email: $("#email").val()
            },
            dataType: "JSON",
            success: function (jsonStr) {
                $("#result").text(JSON.stringify(jsonStr));
            }
        });

    });

    });
    </script>
    </head>
    <body>
    <h1>jQuery Ajax Jason example</h1>
    <div id="result"></div>
        <form name="contact" id="contact" method="post">
         Message : <textarea name="message" id="message"></textarea><br/>
         firstName : <input type="text" name="firstName" id="firstName"/><br/>
         lastName : <input type="text" name="lastName" id="lastName"/><br/>
         email : <input type="text" name="email" id="email"/><br/>
        <input type="button" value="Submit" name="submit" id="submit"/>
        </form>

    </body>
</html>

post.php
<?php
    $message      = $_POST["message"];
    $firstName   = $_POST["firstName"];
    $lastName    = $_POST["lastName"];
    $email       = $_POST["email"];
    if(isset($message)){
        $data = array(
            "User message"     => $message,
            "User firstName"  => $firstName,
            "User lastName"   => $lastName,
            "User email"      => $email
        );
        echo json_encode($data);
    }
?>
Video: JSON Examples in PHP

No comments:

Post a Comment