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
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= {
{"fruit":"apple", "juice":"orange"},
{"fruit":"banana", "juice":"watermelon"}

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

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

Example 2: jQuery Ajax Jason example in PHP form
       <title>jQuery Ajax Jason example</title>
    <script type="text/javascript" src=""></script>
     <script type="text/javascript">
     $(document).ready(function() {


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


    <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"/>


    $message      = $_POST["message"];
    $firstName   = $_POST["firstName"];
    $lastName    = $_POST["lastName"];
    $email       = $_POST["email"];
        $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