Friday, March 9, 2018

PHP Unit : 5 Web Services and JQuery for B.C.A., P.G.D.C.A. and all IT Students


--------------------------------------------------------------------------------------------------------------------------
Prepared By : Uday Shah (HOD - IT)
Contact No : 7600044051
E-Mail : rupareleducaion@gmail.com

#Press the follow button to get update.

Web Services

  • Web services are application components
  • Web services communicate using open protocols
  • Web services are self-contained and self-describing
  • Web services can be discovered using UDDI
  • Web services can be used by other applications
  • HTTP ,JSON and XML is the basis for Web services
  • By using Web services, your application can publish its function or message to the rest of the world.
  • Web services use XML to code and to decode data, and SOAP (Simple Object Access Protocol) to transport it using open protocols like JSON.
  • Web Services have Two Types of Uses
1.     Reusable application-components.
There are things applications needs very often. So why make these over and over again? Web services can offer application-components like: currency conversion, weather reports, or even language translation as services.
2.     Connect existing software.
Web services can help to solve the interoperability problem by giving different applications a way to link their data. With Web services you can exchange data between different applications and different platforms. Any application can have a Web Service component. Web Services can be created regardless of programming language.
Introduction to JSON
·        JSON is a language-independent data format.
·        JSON Stand For JavaScript Object Notation.
·        JSON is syntax for storing and exchanging data.
·        JSON is text, written with JavaScript object notation
·        When exchanging data between a browser and a server, the data can only be text.
·        JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.
·        JSON is an open-standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs.
·        It is the most common data format used for asynchronous browser/server communication, largely replacing XML, and is used by AJAX.
·        We can also convert any JSON received from the server into JavaScript objects.
·        This way we can work with the data as JavaScript objects, with no complicated parsing and translations.
For sending data then If you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server

For Example.

var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
window.location = "json1.php?x=" + myJSON;

And for receiving data in json format you have to convert it into JavaScript Object.

var myJSON = '{"name":"John", "age":31, "city":"New York"}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;


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 Data - A Name and a Value

JSON data is written as name/value pairs.
A name/value pair consists of a field name  in double quotes, followed by a colon, followed by a value:
For Example :

"name":"Uday"

Installation and Configuration

·        PHP 5.2.0 supports JSON.
·        So, when you install PHP, JSON support is automatically installed and you don't need any installation and configuration in addition.
·        If your PHP version is less that 5.2.0, you can run the following command using script. This extension requires the libxml PHP extension. This means that passing in --enable-libxml is also required, although this is implicitly accomplished because libxml is enabled by default.
·        XML-RPC (Remote Procedure Call) support in PHP is not enabled by default. You will need to use the --with-xmlrpc[=DIR] configuration option when compiling PHP to enable XML-RPC support.

·        This extension has no configuration directives defined in php.ini.

·        PHP json_encode() function converts a PHP value into a JSON value. For example, from a PHP array, it can create a JSON representation of that array.

·        json_decode() function decodes a JSON string. Suppose you have obtained some data in JSON format and you want to convert it into PHP variable for the purpose of presenting that data to a user or use it for further programming, you have to use this function.


Explain Resource type of JSON
A resource accessed through this convention is required as a JSON value with an application /JSON Internet media type.
It is also referred to as MIME(Multipurpose Internet Mail Extension)
An accessible resource is a member of a collection of resources.
A collection of resource must have a unique location, which is expressed as a part of the request URL of HTTP request.
Each resource must have unique identifier within a collection.
The server implementation may establish restrictions on identifiers can be used.

Explain JSON Serializable
Json Serializable – specifies data which should be serialized to JSON. It is an interface of JSON Serializable.

Syntax:
abstract public mixed JsonSerializable::jsonSerialize(void)

The function has no parameter and returns data which can be serialized by json_encode(), which is a value of any type other than a resource.

Ex:
<?php
     Class ArrayValue implements JsonSerializable                        
{
               Public function _construct(array $array)
{
                        $this->array = $array;
              }
              Public function jsonSerialize()
{
                        Return $this->array;
              }
     }
     $array = [1,2,3];
     echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>
OutPut
[
     1,
     2,
     3
]

Explain JSON Function:
1.json_encode() :
Json_encode – It is Used to Encodes a JSON string.
Syntax:
String json_encode ( mixed $value )
     Returns a string that contains JSON  representation of $value.
     $value: The value being encoded. Can be any type except a resource.
     This function only works only with UTF-8 encoded data.
Example:
     <?php
              $arr = array (‘a’ =>1, ‘b’ =>2, ‘c’ =>3, ‘d’ =>4,‘e’ =>5);
              echo json_encode($arr);
              $arr = array (1, 2, 3, 4, 5);
              echo json_encode($arr);
     ?>

Output
     {“a”:1,”b”:2,”c”:3,”d”:4,”e”:5}
     [1,2,3,4,5]

2.json_decode() :
Json_decode – It is Used to Decoded a JSON string.
Syntax:
          Mixed json_decode (string $json, bool $assoc)
          It accepts a JSON encoded string and convert it into a PHP value.
          $json: The JSON string being decoded.
Example:
          <?php
                   $json = ‘{“a”:1,”b”:2,”c”:3,”d”:4,”e”:5}’;
                   Var_dump(json_decode($json));
                   Var_dump(json_decode($json, true));
          ?>
Output:
Object(stdClass)#1 (5)
{
          [“a”] => int(1)
          [“b”] => int(2)
          [“c”] => int(3)
          [“d”] => int(4)
          [“e”] => int(5)
}
Array(5)
{
          [“a”] => int(1)
          [“b”] => int(2)
          [“c”] => int(3)
          [“d”] => int(4)
          [“e”] => int(5)
          }


Using JQuery with PHP

JQuery is a JavaScript framework, which purpose is to make it much easier to use JavaScript on your website. You could also describe JQuery as an abstraction layer, since it takes a lot of functionality that you would have to write many lines of JavaScript to accomplish and wrap it into function with a single line code.

With that in mind you should be aware that you don’t need to be a JavaScript expert to use JQuery. In fact JQuery tries to simplify a lot of the complicated things from the JavaScript, like AJAX calls and DOM manipulation, so that you may do these things without knowing a lot about JavaScript.
             

What is JQuery?

JQuery is the light weight version of JavaScript.
JQuery is fast, small and feature rich JavaScript library.
The purpose of JQuery is to make it much easier to use JavaScript on your website.
It’s features are working for things listed below with ready and easy to use supported for all browsers.
The JQuery library contains the following features.
1.     HTML manipulation
2.     CSS manipulation
3.     Event Handling
4.     Effect and Animation
5.     AJAX

Here are some of the reasons for giving being most popular.
1.     Cross browser compatibility:
§        JQuery team is aware of the cross browsers issues and they have written library, so that JQuery works on all the major browsers.
§        There are some of the plugins like parallax, 360 degree tour etc., which is supported in some major browsers like Internet explorer 8, Google chrome , fire fox , opera, safari etc.

2.     Fast and small foot print:
A lots of common functionality has been omitted from the JQuery library. So, that it is very easy to include in your application and very fast as well.

3. CSS3 selectors compliant:
JQuery fully supports the css3 selector specifications.

4. JQuery UI:
JQuery user interface (UI) separates out higher level constructs and is packaged into a library, like sliders, dialog boxes, date pickers and more user interface is used.

5. Lots of Plug-in:
By including only a set of features while providing a framework for extending the library, JQuery team
Made it easy to create plug-in that it can be reused in JQuery projects.

Q-8: How JQuery works and how it is used?
Ans:  JQuery developers uses window.onload() function to Initiate some action on page load. But there are some of using this function. It does not  fire until all the images are Loaded.

A more modern approach, instead of downloading and hosting JQuery yourself, is to include it from a CDN (content Delivery Network). Both Google and Microsoft host several different versions of JQuery and other JavaScript frameworks.
It saves you from having to download and store the JQuery framework.
There are some of the JQuery selectors, used with framework.
                  

What is jQuery?

·        jQuery is a lightweight, "write less, do more", JavaScript library.
·        The purpose of jQuery is to make it much easier to use JavaScript on your website.
·        jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.
·        jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.
jQuery Syntax
·        The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the elements.

Basic syntax is:  $(selector).action()

·         A $ sign to define/access jQuery
·         A (selector) to "query (or find)" HTML elements
·         A jQuery action() to be performed on the element(s)

For Examples:

·        $(this).hide() - hides the current element.
·        $("p").hide() - hides all <p> elements.
·        $(".test").hide() - hides all elements with class="test".
·        $("#test").hide() - hides the element with id="test".


JQuery Selector

·        jQuery selectors allow you to select and manipulate HTML element(s).
·        jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
·        All selectors in jQuery start with the dollar sign and parentheses: $().

·        Element       $("p")                              All <p> elements
·        #id               $("#id1")                         The element with id="id1"
·   .class            $(".cls1")                         All elements with class="cls1"

Explain JQuery Events:

Mouse Events
Keyboard Events
Form Event
Document Events
Click
Keypress
Submit
Load
Dblclick
Keydown
Change
Resize
Mouseenter
Keyup
Focus
Scroll
Mouseleave

Blur
Unload

In JQuery most DOM events have an equivalent JQuery
Method. To assign a click event to all paragraph on a page
You can do this
$(“p”).click(function(){
//action goes here
});

Example:
<html>
<head>
<script src=http://code.jquery.com/jquery-latest.js>
</script>
<script>
$(document).ready(function(){
$("p").click(function(){
alert("The paragraph was clicked.");
});
});
</script>
</head>
<body>
<p>Click on this paragraph</p>
</body>
</html>

Explanation of above program:
JQuery –latest is latest version of jquery.js. Here we are using content delivery network but instead can download and host JQuery yourself from jquery.com website. It is the library file and you reference it with the html <script> tag.
          In above example we have used selector as <p> tag, when user clicks on paragraph it will show an alert box with Message “The paragraph was clicked”.



Commonly Used jQuery Event Methods
$(document).ready()
The $(document).ready() method allows us to execute a function when the document is fully loaded. 

click()
The click() method attaches an event handler function to an HTML element.
The function is executed when the user clicks on the HTML element.
The following example says: When a click event fires on a <p> element; hide the current <p> element:
$("p").click(function()
{
    $(
this).hide();
});

dblclick()
The dblclick() method attaches an event handler function to an HTML element.
The function is executed when the user double-clicks on the HTML element:
$("p").dblclick(function()
{
   $(
this).hide();
});

keypress()
The keypress() method attaches an event handler function to an HTML element.
The function is executed when the user keypress on the HTML element:
$("input").keypress(function(){
  $("span").text(i += 1);
});

keydown()
The keydown() method attaches an event handler function to an HTML element.
The function is executed when the user keydown on the HTML element:
$("input").keydown(function(){
  $("input").css("background-color""yellow");
});

keyup()
The keyup() method attaches an event handler function to an HTML element.
The function is executed when the user keyup on the HTML element:
$("input").keyup(function(){
  $("input").css("background-color""pink");
});

submit()
The submit() method attaches an event handler function to an HTML element.

The function is executed when the user submit on the HTML element:
$("form").submit(function(){
  alert("Submitted");
});


change()
The change() method attaches an event handler function to an HTML element.


The function is executed when the user change on the HTML element:
$("input").change(function(){
  alert("The text has been changed.");
});


focus()
The focus() method attaches an event handler function to an HTML form field.
The function is executed when the form field gets focus:
$("input").focus(function()
{
    $(
this).css("background-color""#cccccc");
});

blur()
The blur() method attaches an event handler function to an HTML form field.
The function is executed when the form field loses focus:
$("input").blur(function()

{
    $(
this).css("background-color""#ffffff");
});


load()
The load() method attaches an event handler function to an HTML form field.

The function is executed when the user load on the HTML element:
$("#div1").load("demo_test.txt");

jQuery Resize() Method
The resize event occurs when the browser window changes size.
The resize() method triggers the resize event, or attaches a function to run when a resize event occurs.
Trigger the resize event for the selected elements:


$(selector).resize()


scroll() Method
The scroll event occurs when the user scrolls in the specified element. The scroll event works for all scrollable elements and the window object (browser window).
The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.
$("div").scroll(function(){
  $("span").text(x += 1);
});

unload() Method
The unload event occurs when the user navigates away from the page.
The unload event is triggered when:
  • a link to leave the page is clicked
  • a new URL is typed in the address bar
  • the forward or back buttons are used
  • the browser window is closed
  • the page is reloaded
$(window).unload(function(){
  alert("Goodbye!");
});

mouseenter()
The mouseenter() method attaches an event handler function to an HTML element.
The function is executed when the mouse pointer enters the HTML element:
$("#p1").mouseenter(function()
{
   alert(
"You entered p1!");
});

mouseleave()
The mouseleave() method attaches an event handler function to an HTML element.
The function is executed when the mouse pointer leaves the HTML element:
$("#p1").mouseleave(function()
{
   alert(
"Bye! You now leave p1!");
});

mousedown()
The mousedown() method attaches an event handler function to an HTML element.
The function is executed, when the left, middle or right mouse button is pressed down, while the mouse is over the HTML element:
$("#p1").mousedown(function()
{
    alert(
"Mouse down over p1!");
});

mouseup()
The mouseup() method attaches an event handler function to an HTML element.
The function is executed, when the left, middle or right mouse button is released, while the mouse is over the HTML element:
$("#p1").mouseup(function(){
    alert(
"Mouse up over p1!");
});

hover()
The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods.
The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element:
$("#p1").hover(function()
{
    alert(
"You entered p1!");
},
function()
{
    alert(
"Bye! You now leave p1!");
});


#Press the follow button to get update.

Best Of Luck

Please Give your comment and share it… Thank You