Follow Me:
Showing posts with label JSON and JSONP. Show all posts
Showing posts with label JSON and JSONP. Show all posts

Wednesday 13 May 2015

What is JSON?

JavaScript Object Notation (JSON) is a lightweight data-interchange format inspired by the object literals of JavaScript. 

JSON values can consist of:

  •   objects (collections of name-value pairs)
  •   arrays (ordered lists of values)
  •   strings (in double quotes)
  •   numbers
  •   true, false, or null

JSON is language independent.

JSON with PHP?

   After PHP Version 5.2.0, JSON extension is decodes and encodes functionalities as default.

  • Json_encode     - returns the JSON representation of values
  • Json_decode     - Decodes the JSON String
  • Json_last_error - Returns the last error occured.

JSON Syntax and Rules?

   JSON syntax is derived from JavaScript object notation syntax:


  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

JSON Example

    This example is simple phone number validation and once phone number has validated , it will be sent this php page, there we are using the json format related encode data.

Html Page:
  
<html>
<head>
<title>JSON Example in Php</title>
<script src="js/jquery-1.11.0.min.js"></script>
</head>
<body>
<h1>Json Basic Example</h1>
<form name="phone-form" method="post" onsubmit="return validation();">
 <input type="text" name="phone" id="phone" value="" >
 <input type="submit" value="submit" >
</form>
<div id="outputDisplay"></div>


Javascript Function


<script>
function validation(value){ 
 //Phone Number Validations
 var phone   = $('#phone').val();
 var specialDigitPattern  = /[~`!@#\$%\^&\*()\-_\+=|\\{}\[\]:;"'<>,\?\/\.0123456789]/;
 //var mailvalidateregex  = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;  email validation
 if(phone == ""){
  alert("Please enter the phone ");
  return false;
 }else if(isNaN(phone)){
  alert('Please Enter Valid Phone Number');
  return false;
 }
 
 var postdata  = 'phone='+phone;
 var url   = 'testphone.php?phone='+phone;
 
 $.ajax({
  type  : "POST",
  url   : url, 
  data  : postdata,
  dataType : "json",
  success  : phonestatus_check,
 });
 return false;
}

function phonestatus_check(response){
 if(response.status == 1){
  alert('success');
  $("#outputDisplay").css("color","green");
  $("#outputDisplay").html(response.message);
 }else{
  alert('failure');
  return false;
 }
}
//ends
</script>



Php Page:

<?php
 if(isset($_POST['phone'])){
  $phonenumber = $_POST['phone'];
  $responsearray = array();$responsestatus = '1';
  if($responsestatus == 1){
      $responsearray = array('status' => 1,'message'=> 'Thanks for submitting the Phone Number');
  }else{
   $responsearray = array('status' => 0,'message'=> 'failure');
  }
  echo json_encode($responsearray);
  /* $json = json_encode($responsearray);
  if($_GET['jsoncallback'])
   exit("{$_GET['jsoncallback']}($json)"); */
 }
?>

Monday 3 November 2014

JSON (Javascript Object Notation) is a convenient way to transport data between applications, especially when the destination is a Javascript application.

Example :
Here is a minimal example that uses JSON as the transport for the server response. The client makes an ajax request with the JQuery shorthand function $.getJSON. The server generates a hash, formats it as JSON and returns this to the client. The client formats this and puts it in a page element.

Server:
get '/json' do
 content_type :json
 content = { :response  => 'Sent via JSON',
            :timestamp => Time.now,
            :random    => rand(10000) }
 content.to_json
end

Client:
var url = host_prefix + '/json';
$.getJSON(url, function(json){
  $("#json-response").html(JSON.stringify(json, null, 2));
});
 
Output:
  {
   "response": "Sent via JSON",
   "timestamp": "2014-06-18 09:49:01 +0000",
   "random": 6074
  }

JSONP (JSON with Padding)

JSONP is a simple way to overcome browser restrictions when sending JSON responses from different domains from the client. The only change on the Client side with JSONP is to add a callback parameter to the URL.

Server:
get '/jsonp' do
 callback = params['callback']
 content_type :js
 content = { :response  => 'Sent via JSONP',
            :timestamp => Time.now,
            :random    => rand(10000) }
 "#{callback}(#{content.to_json})"
end

Client:
var url = host_prefix + '/jsonp?callback=?';
$.getJSON(url, function(jsonp){
  $("#jsonp-response").html(JSON.stringify(jsonp, null, 2));
});

Output:
 {
  "response": "Sent via JSONP",
  "timestamp": "2014-06-18 09:50:15 +0000",
  "random": 364
}