Monday, 7 May 2018

Loading

PHP AND JQUERY AJAX

WHY USE JQUERY FOR AJAX REQUESTS?
I think it is to make things easier, have shorter more readable code. You can see some code examples of doing an AJAX request without jQuery here and here.

As you can see on those links, some tasks include creating a catch for different browser XMLHttpRequest, opening the url, checking if the request is in ready state and setting the request header.

jQuery solves this by having a short, more readable syntax.






1. JQUERY POST FORM DATA USING .AJAX() METHOD
This is a great way to show someone that you are now an AJAX programmer. Because of this .ajax() piece of code in your HTML page, you may now face the world with confidence and with a beautiful smile in your face.

<html>
<head>
<title>jQuery post form data using .ajax()</title>

</head>
<body>

<h1>jQuery post form data using .ajax() method</h1>
<div>Fill out and submit the form below to get response.</div>

<!-- our form -->
<form id='userForm'>
<div><input type='text' name='firstname' placeholder='Firstname' /></div>
<div><input type='text' name='lastname' placeholder='Lastname' /></div>
<div><input type='text' name='email' placeholder='Email' /></div>
<div><input type='submit' value='Submit' /></div>
</form>

<!-- where the response will be displayed -->
<div id='response'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
$('#userForm').submit(function(){

// show that something is loading
$('#response').html("<b>Loading response...</b>");

/*
* 'post_receiver.php' - where you will pass the form data
* $(this).serialize() - to easily read form data
* function(data){... - data contains the response from post_receiver.php
*/
$.ajax({
type: 'POST',
url: 'post_receiver.php',
data: $(this).serialize()
})
.done(function(data){

// show the response
$('#response').html(data);

})
.fail(function() {

// just in case posting your form failed
alert( "Posting failed." );

});

// to prevent refreshing the whole page page
return false;

});
});
</script>

</body>
</html>

POSTED DATA

<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>







2. JQUERY POST FORM DATA USING .POST() METHOD

.post() method has a more descriptive syntax, it is a shorthand of .ajax() method above. See how it was commonly used with the code below:


<html>
<head>
<title>jQuery post form data using .post()</title>

</head>
<body>

<h1>jQuery post form data using .post() method</h1>
<div>Fill out and submit the form below to get response.</div>

<!-- our form -->
<form id='userForm'>
<div><input type='text' name='firstname' placeholder='Firstname' /></div>
<div><input type='text' name='lastname' placeholder='Lastname' /></div>
<div><input type='text' name='email' placeholder='Email' /></div>
<div><input type='submit' value='Submit' /></div>
</form>

<!-- where the response will be displayed -->
<div id='response'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
$('#userForm').submit(function(){

// show that something is loading
$('#response').html("<b>Loading response...</b>");

/*
* 'post_receiver.php' - where you will pass the form data
* $(this).serialize() - to easily read form data
* function(data){... - data contains the response from post_receiver.php
*/
$.post('post_receiver.php', $(this).serialize(), function(data){

// show the response
$('#response').html(data);

}).fail(function() {

// just in case posting your form failed
alert( "Posting failed." );

});

// to prevent refreshing the whole page page
return false;

});
});
</script>

</body>
</html>


POSTED DATA

<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>









3. JQUERY POST JSON DATA USING .POST() METHOD
Sometimes you don’t want to post data from an HTML form. You can do it by creating a JSON string, and here’s how you’ll be able to post it.


<html>
<head>
<title>jQuery post JSON data using .post() method by codeofaninja.com</title>

</head>
<body>

<h1>jQuery post JSON data using .post() method</h1>
<div>Click the button below to get response.</div>

<!-- our form -->
<input type='button' value='Post JSON' id='postJson' />

<!-- where the response will be displayed -->
<div id='response'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){

$('#postJson').click(function(){

// show that something is loading
$('#response').html("<b>Loading response...</b>");

/*
* 'post_receiver.php' - where you will pass the form data
* $(this).serialize() - to easily read form data
* function(data){... - data contains the response from post_receiver.php
*/
$.post('post_receiver.php', { user_id: "143", username: "ninjazhai", website: "https://demo.com/" }, function(data){

// show the response
$('#response').html(data);

}).fail(function() {

// just in case posting your form failed
alert( "Posting failed." );

});

// to prevent refreshing the whole page page
return false;

});
});
</script>

</body>
</html>

POSTED DATA

<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
Loading

JSON to PHP

JSON to PHP Using json_decode

PHP's json_decode function takes a JSON string and converts it into a PHP variable. Typically, the JSON data will represent a JavaScript array or object literal which json_decode will convert into a PHP array or object. The following two examples demonstrate, first with an array, then with an object:
$json = '["apple","orange","banana","strawberry"]';
$ar = json_decode($json);
// access first element of $ar array
echo $ar[0]; // apple




By default, objects are converted to standard objects by json_decode:
$json = '{
    "title": "JavaScript: The Definitive Guide",
    "author": "David Flanagan",
    "edition": 6
}';
$book = json_decode($json);
// access title of $book object
echo $book->title; // JavaScript: The Definitive Guide 

Convert JSON String to PHP Array

The json_decode function provides an optional second argument to convert objects to associative arrays. The following uses the object from the previous example and passes true as the second argument. The result, held in $book, is now an array, and its title and other elements can be accessed using array syntax:
// $json same as example object above
// pass true to convert objects to associative arrays
$book = json_decode($json, true);
// access title of $book array
echo $book['title']; // JavaScript: The Definitive Guide

JSON String to Multidimensional Array

The json_decode function can also be used to convert more complex data structures held in JSON strings. The JSON string ($json) in the following example represents an array of objects. That is, the outer level is an array literal whose elements are object literals. By default the result of json_decode will be a numerically indexed array of objects:
$json = '[
    {
        "title": "Professional JavaScript",
        "author": "Nicholas C. Zakas"
    },
    {
        "title": "JavaScript: The Definitive Guide",
        "author": "David Flanagan"
    },
    {
        "title": "High Performance JavaScript",
        "author": "Nicholas C. Zakas"
    }
]';

$books = json_decode($json);
// access property of object in array
echo $books[1]->title; // JavaScript: The Definitive Guide
If we pass true as the second argument to json_decode, the result is a multidimensional array that is numerically indexed at the outer level and associative at the inner level:
// $json same as example object above
// pass true to convert objects to associative arrays
$books = json_decode($json, true);
// numeric/associative array access
echo $books[1]['title']; // JavaScript: The Definitive Guide
Then we use a combination of numeric and associative array syntax to access the desired element in our multidimensional array.

Errors or Unexpected Results with json_decode?

The json_decode function will return null if the string passed to it cannot be converted. For example, the following demonstrates the result when our JSON string contains invalid characters:
$json = "{
    'title': 'JavaScript: The Definitive Guide',
    'author': 'David Flanagan',
    'edition': 6
}";




$book = json_decode($json);
echo $book->title; // Notice: Trying to get property of non-object...
echo json_last_error(); // 4 (JSON_ERROR_SYNTAX)
echo json_last_error_msg(); // unexpected character 




Our attempt to access a property of the object we are expecting results in an error. The PHP functions json_last_error and json_last_error_msg provide some information about errors encountered.

Saturday, 6 January 2018

Loading

Six good reasons to use Symfony



       Using a framework is a good thing. Making the right choice is even better. Here are six good reasons to use Symfony from a strategic point of view.

1. Reputation

Quickly adopted by professionals active in this field following its launch in 2005, Symfony today is a stable environment that is both well-known and recognized internationally. The number of its references attests to this, as they have grown significantly since its launch. Symfony is also an active community; developers, integrators, users and other contributors who participate in the on-going enrichment of this tool.

2. Permanence


Behind Symfony there is a company: SensioLabs. Created more than 18 years ago, SensioLabs is a web agency that has many major accounts among its references. Envisioned for its own needs, the Symfony framework is today still the daily tool used by its own teams to develop customer projects. Designed by professionals for professionals, Symfony is first and foremost a pragmatic tool, the features of which address real-world-requirements.

Permanence is also something that relates to long-term support. Today, this support is naturally provided by SensioLabs. But there is also an entire ecosystem that has grown up around Symfony since its launch: the community (mailing lists, IRC, etc.) and the many other service companies that have invested in the framework.

Lastly, it is also with a view towards sustainable development that Symfony is distributed under Open Source MIT license, which does not impose constraints and allows the development of Open Source as well as proprietary applications.

3. References


Intranets, major general public sites, social networks, community sites, management and workflow applications, etc. Examples are not lacking: Hundreds of sites and applications of all sizes and of all types trust Symfony.

This is specifically the case of Yahoo!, Dailymotion, Opensky.com, Exercise.com and even  applications such as phpBB and Drupal.

4. Innovation


Symfony is everything that you would come to expect from a framework: speed, flexibility, reusable components, etc. Then there is the structure of what has been developed and the use of best practices. Not bad!


But that is not all! Since SensioLabs has developed a habit of shaking up the established order and is always striving for excellence, Symfony (and its entire community) has developed a sense of curiosity that goes well beyond PHP. And we do not hesitate to innovate by seeking out ideas
elsewhere and then adapt them to the world of PHP, such as dependency injection from the Java world.

In addition, Symfony, seeking out ongoing improvement in the productivity of developers, envisioned the “web debug toolbar,” taken from other frameworks, whether PHP or otherwise.


5. Resources


When using Symfony, you are assured of never “being alone with your screen.” Whether a question of community support (mailings lists, IRC, etc.) or company support (consulting, training, etc.), you will always find the answers to your questions.

Starting from the principle that “an undocumented line is a line that does not exist,” you will also find many works dedicated to Symfony, which will help you throughout the development of your sites and applications.


6. Interoperability


The idea behind Symfony: Don’t lock yourself up within Symfony! Allow yourself to build applications that precisely meets your needs!

Symfony respects the existing “de facto standards” of PHP: PHPUnit, naming conventions for classes, etc. Furthermore, Symfony also allows you to use certain pieces of its software building blocks (dependency injector, translations management, forms management, etc.) without necessarily
using the framework in its entirety.


By the way, Symfony is so interoperable that, at the core, it uses external software building blocks itself (ORM Doctrine, Swiftmailer, etc.)!


Loading

Why should I use a framework?







Why should I use a framework?




  A framework is not absolutely necessary: it is “just” one of the tools that is available to help you develop better and faster!

Better, because a framework provides you with the certainty that you are developing an application that is in full compliance with the business rules, that is structured, and that is both maintainable and up-gradable.

Faster, because it allows developers to save time by re-using generic modules in order to focus on other areas. Without, however, ever being tied to the framework itself.

Investing in the task, not in the technology

This is the basic principle of a framework: Not having to reinvent the wheel. And doing away with foreboding, low value added tasks (for example, the development of generic components) in order to
fully focus on the business rules.

As an example, a framework will keep the developer from having to spend 2 or 3 days creating an authentication form (which is not a specific task). The time that is saved can be dedicated to more
specific components as well as to the corresponding unit tests; giving you solid, sustainable and high quality code.

Guaranteed upgradability and maintenance

In the longer term, a framework ensures the longevity of your applications. If a development team works as they please, only that particular team will be able to maintain and upgrade the application
with ease. The way that a publisher supports a proprietary solution.


On the other hand, the structure that a framework provides for the application makes it possible to avoid this pitfall altogether and it gives any developer - whether they participated in its development or not – the ability to easily “adopt” an application, to maintain it over time and to upgrade it both quickly and neatly,
whenever necessary.


In this regard, a framework is not a black box! In the case of Symfony, it is still PHP... The applications that are developed are not limited to the Symfony universe, and they are natively
interoperable with any other PHP library, for example.


When should I use a framework?


Well... Whenever you need to, while developing a web application or a site, of course!


Why would you have a custom piece of furniture made if you could find one that perfectly matches your décor, right off the shelf? The same is true for computer applications: Before you dive in to
create a framework, a little survey work is in order.


The right questions


To make sure that you are making the right choice, both for the short as well as the long term, it is necessary to ask the right questions:

  1. What are my current needs? Are they covered by a packaged solution?
  2. What skills do I need if I choose a framework?
  3. Will the developed solution be upgradeable?
And finally, don’t fall into the trap of the "apparent simplicity of the requirements". In many cases it quickly becomes apparent that both the business rules and functions to be implemented are just not so simple to put in place.

By the way, Symfony is also very well suited for mini-projects.





Loading

Whats is Symfony Framework (MVC)

                                                                      a SensioLabs Products





Whats is Symfony Framework (MVC)

Symfony is a high performance PHP framework with a set of reusable components. It is using large scale application developments. It is the best platform for creating open-source projects.
Symfony is a mature framework used to develop a wide range of MVC applications.

Symfony is used to create robust applications quickly. The following are the features :

  • Easy installation
  • Simple in usage
  • Database engine-independent
  • Readability
  • Extendibility and integration
  • Enterprise-ready
 Symfony is open-source software and is released under the MIT License.




« Symfony is a set of PHP Components, a Web Application
framework, a Philosophy, and a Community — all working
together in harmony. »

Symfony Framework


The leading PHP framework to create websites and web
applications. Built on top of the Symfony Components.

Symfony Components


A set of decoupled and reusable components on which
the best PHP applications are built, such as Drupal,
phpBB, and eZ Publish.

Symfony Community


A huge community of Symfony fans committed to
take PHP to the next level.

Symfony Philosophy


Embracing and promoting professionalism, best
practices, standardization and interoperability
of applications.






Wednesday, 26 July 2017

Loading

Angular Multiple Components

Angular Multiple Components 
The AppComponent is doing everything at the moment. In the beginning, it showed details of a single hero. Then it became a master/detail form with both a list of heroes and the hero detail. Soon there will be new requirements and capabilities. You can't keep piling features on top of features in one component; that's not maintainable.
You'll need to break it up into sub-components, each focused on a specific task or workflow. Eventually, the AppComponent could become a simple shell that hosts those sub-components.
In this page, you'll take the first step in that direction by carving out the hero details into a separate, reusable component. When you're done, the app should look like this live example / download example .
Before getting started on this page, verify that you have the following structure from earlier in the Tour of Heroes. If not, go back to the previous pages.
angular-tour-of-heroes
src
app
app.component.ts
app.module.ts
main.ts
index.html
styles.css
systemjs.config.js
tsconfig.json
node_modules ...
package.json




Keep the app transpiling and running while you build the Tour of Heroes by entering the npm start command in a terminal window as you did before.

Make a hero detail component

Add a file named hero-detail.component.ts to the app/ folder. This file will hold the new HeroDetailComponent.
The file and component names follow the standard described in the Angular style guide.
  • The component class name should be written in upper camel case and end in the word "Component". The hero detail component class is HeroDetailComponent.
  • The component file name should be spelled in lower dash case, each word separated by dashes, and end in .component.ts. The HeroDetailComponent class goes in the hero-detail.component.ts file.
Start writing the HeroDetailComponent as follows:

app/hero-detail.component.ts (initial version)

import { Component } from '@angular/core';

@Component({
  selector: 'hero-detail',
})
export class HeroDetailComponent {
}

To define a component, you always import the Component symbol.
The @Component decorator provides the Angular metadata for the component. The CSS selector name, hero-detail, will match the element tag that identifies this component within a parent component's template. Near the end of this tutorial page, you'll add a <hero-detail> element to the AppComponent template.
Always export the component class because you'll always import it elsewhere.

Hero detail template

To move the hero detail view to the HeroDetailComponent, cut the hero detail content from the bottom of the AppComponent template and paste it into a new template property in the @Component metadata.
The HeroDetailComponent has a hero, not a selected hero. Replace the word, "selectedHero", with the word, "hero", everywhere in the template. When you're done, the new template should look like this:

src/app/hero-detail.component.ts (template)

@Component({
  selector: 'hero-detail',
  template: `
    <div *ngIf="hero">
      <h2>{{hero.name}} details!</h2>
      <div><label>id: </label>{{hero.id}}</div>
      <div>
        <label>name: </label>
        <input [(ngModel)]="hero.name" placeholder="name"/>
      </div>
    </div>
  `
})

Add the hero property

The HeroDetailComponent template binds to the component's hero property. Add that property to the HeroDetailComponent class like this:

src/app/hero-detail.component.ts (hero property)

hero: Hero;
The hero property is typed as an instance of Hero. The Hero class is still in the app.component.ts file. Now there are two components that need to reference the Hero class. The Angular style guide recommends one class per file anyway.
Move the Hero class from app.component.ts to its own hero.ts file.

src/app/hero.ts

export class Hero {
  id: number;
  name: string;
}
Now that the Hero class is in its own file, the AppComponent and the HeroDetailComponent have to import it. Add the following import statement near the top of both the app.component.ts and the hero-detail.component.tsfiles.

src/app/hero-detail.component.ts

import { Hero } from './hero';





The hero property is an input property

Later in this page, the parent AppComponent will tell the child HeroDetailComponent which hero to display by binding its selectedHero to the hero property of the HeroDetailComponent. The binding will look like this:

src/app/app.component.html

<hero-detail [hero]="selectedHero"></hero-detail>
Putting square brackets around the hero property, to the left of the equal sign (=), makes it the target of a property binding expression. You must declare a target binding property to be an input property. Otherwise, Angular rejects the binding and throws an error.
First, amend the @angular/core import statement to include the Input symbol.

src/app/hero-detail.component.ts (excerpt)

import { Component, Input } from '@angular/core';
Then declare that hero is an input property by preceding it with the @Input decorator that you imported earlier.

src/app/hero-detail.component.ts (excerpt)

@Input() hero: Hero;
Read more about input properties in the Attribute Directives page.
That's it. The hero property is the only thing in the HeroDetailComponent class.

src/src/app/hero-detail.component.ts

export class HeroDetailComponent {
  @Input() hero: Hero;
}
All it does is receive a hero object through its hero input property and then bind to that property with its template.
Here's the complete HeroDetailComponent.

src/app/hero-detail.component.ts

  1. import { Component, Input } from '@angular/core';
  2.  
  3. import { Hero } from './hero';
  4. @Component({
  5. selector: 'hero-detail',
  6. template: `
  7. <div *ngIf="hero">
  8. <h2>{{hero.name}} details!</h2>
  9. <div><label>id: </label>{{hero.id}}</div>
  10. <div>
  11. <label>name: </label>
  12. <input [(ngModel)]="hero.name" placeholder="name"/>
  13. </div>
  14. </div>
  15. `
  16. })
  17. export class HeroDetailComponent {
  18. @Input() hero: Hero;
  19. }

Declare HeroDetailComponent in the AppModule

Every component must be declared in one—and only one—NgModule.
Open app.module.ts in your editor and import the HeroDetailComponent so you can refer to it.

src/app/app.module.ts

import { HeroDetailComponent } from './hero-detail.component';
Add HeroDetailComponent to the module's declarations array.

src/app/app.module.ts

declarations: [
  AppComponent,
  HeroDetailComponent
],
In general, the declarations array contains a list of application components, pipes, and directives that belong to the module. A component must be declared in a module before other components can reference it. This module declares only the two application components, AppComponent and HeroDetailComponent.
Read more about NgModules in the NgModules guide.

Add the HeroDetailComponent to the AppComponent

The AppComponent is still a master/detail view. It used to display the hero details on its own, before you cut out that portion of the template. Now it will delegate to the HeroDetailComponent.
Recall that hero-detail is the CSS selector in the HeroDetailComponent metadata. That's the tag name of the element that represents the HeroDetailComponent.
Add a <hero-detail> element near the bottom of the AppComponent template, where the hero detail view used to be.
Coordinate the master AppComponent with the HeroDetailComponent by binding the selectedHero property of the AppComponent to the hero property of the HeroDetailComponent.

app.component.ts (excerpt)

<hero-detail [hero]="selectedHero"></hero-detail>
Now every time the selectedHero changes, the HeroDetailComponent gets a new hero to display.
The revised AppComponent template should look like this:

app.component.ts (excerpt)

template: `
  <h1>{{title}}</h1>
  <h2>My Heroes</h2>
  <ul class="heroes">
    <li *ngFor="let hero of heroes"
      [class.selected]="hero === selectedHero"
      (click)="onSelect(hero)">
      <span class="badge">{{hero.id}}</span> {{hero.name}}
    </li>
  </ul>
  <hero-detail [hero]="selectedHero"></hero-detail>
`,

What changed?

As before, whenever a user clicks on a hero name, the hero detail appears below the hero list. But now the HeroDetailView is presenting those details.
Refactoring the original AppComponent into two components yields benefits, both now and in the future:
  1. You simplified the AppComponent by reducing its responsibilities.
  2. You can evolve the HeroDetailComponent into a rich hero editor without touching the parent AppComponent.
  3. You can evolve the AppComponent without touching the hero detail view.
  4. You can re-use the HeroDetailComponent in the template of some future parent component.

Review the app structure

Verify that you have the following structure:
angular-tour-of-heroes
src
app
app.component.ts
app.module.ts
hero.ts
hero-detail.component.ts
main.ts
index.html
styles.css
systemjs.config.js
tsconfig.json
node_modules ...
package.json
Here are the code files discussed in this page.
  1. import { Component, Input } from '@angular/core';
  2.  
  3. import { Hero } from './hero';
  4. @Component({
  5. selector: 'hero-detail',
  6. template: `
  7. <div *ngIf="hero">
  8. <h2>{{hero.name}} details!</h2>
  9. <div><label>id: </label>{{hero.id}}</div>
  10. <div>
  11. <label>name: </label>
  12. <input [(ngModel)]="hero.name" placeholder="name"/>
  13. </div>
  14. </div>
  15. `
  16. })
  17. export class HeroDetailComponent {
  18. @Input() hero: Hero;
  19. }

The road you’ve travelled

Here's what you achieved in this page:
  • You created a reusable component.
  • You learned how to make a component accept input.
  • You learned to declare the required application directives in an NgModule. You listed the directives in the @NgModule decorator's declarations array.
  • You learned to bind a parent component to a child component.
Your app should look like this live example / download example .

The road ahead

The Tour of Heroes app is more reusable with shared components, but its (mock) data is still hard coded within the AppComponent. That's not sustainable. Data access should be refactored to a separate service and shared among the components that need data.
You’ll learn to create services in the next tutorial page.