Over a million developers have joined DZone.

Object-Oriented PHP and jQuery AJAX

In this article, I want to introduce Object-Oriented PHP, jQuery AJAX and explain how to combine PHP with jQuery AJAX by illustrating an example.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Object-Oriented PHP

Understanding Objects and Classes

Classes

A class is like a blueprint for a house. It defines the shape of the house on paper, with relationships between the different parts of the house clearly defined and planned out, even though the house doesn’t exist.

In PHP, a class is declared by using the class keyword, followed by the name of the class and a set of curly braces {}, it looks like this:

class Myclass
{
//class properties and methods go here
}            


Objects

If a class is like a blueprint for a house, then, an object is like the actual house built according to that blueprint. More than one object can be built from the same class at the same time, each one independent of the others.

After creating a class, an object can be created by using the new keyword. Example of creating an object (from the above Myclass class):

//creating an object
$obj = new Myclass;      


Understanding Properties and Methods

Properties

To add data to a class, properties are used. They work exactly like regular variables, except they’re bound to the object and therefore they can only be accessed by using the object.

To add a property to the Myclass class, adding the following code to your class Myclass:

class Myclass
{
// $prop1 property
public $prop1 = 'Hi, I am a property!';
}


The public keyword determines the visibility of the property (which we’ll mention about a little later in this post).

Accessing this property by using the above $obj object as follows:

echo $obj -> prop1;


The use of the arrow (->) is an OOP construct that accesses the contained properties (and methods) of a given object.

Methods

A method is a function. Individual actions that an object will be able to perform are defined within the class as methods.

For instance, to create a method getProp that gets the value of the $prop1 property, adding some code to Myclass:

class Myclass
{
// $prop1 property
public $prop1 = 'Hi, I am a property!';
// method
public function getProp()
{
return $this -> prop1;
}
}


Using this method by referencing the object (like properties) to which it belongs $obj) as follows:

echo $obj -> getProp();


Understanding Constructors and Destructors

Constructors

When an object is instantiated, it’s often desirable to set a few things right off the bat. To handle this, PHP provides the magic method __construct(), which is called automatically whenever an object is created.

Adding the __construct() method to Myclass as follows:

class Myclass
{
// $prop1 property
public $prop1 = 'Hi, I am a property!';
// constructor method
public function __construct()
{
echo 'I am the constructor!';
}
// method
public function getProp()
{
return $this -> prop1;
}
}


If we execute some code below:

$obj = new Myclass;
echo $obj -> getProp();


Then the output will look like this:

I am the constructor!
Hi, I am a property!


Destructors

To call a function when an object is destroyed, the __destruct() magic method is available.

Adding __destruct() method to Myclass as follows:

class Myclass
{
// $prop1 property
public $prop1 = 'Hi, I am a property!';
//constructor method
public function __construct()
{
echo 'I am the constructor!';
}
// destructor method
public function __destruct()
{
echo 'I am the destructor!';
}
// method
public function getProp()
{
return $this -> prop1;
}
}


If we execute some code below:

$obj = new Myclass;
echo $obj -> getProp();


Then the output will look like this:

I am the constructor!
Hi, I am a proper!
I am the destructor!


Using Class Inheritance

Classes can inherit the methods and properties of another class by using the extends keyword. For instance, to create a second class that extends Myclass and adds a method, you can add some code look like this:

class MyOtherClass extends Myclass
{
public function newMethod()
{
return 'I am a new method!';
}
}


If we execute some code below:

$newobj = new MyOtherClass;
echo $newobj -> newMethod();
echo $newobj -> getProp();


Then the output will look like this:

I am the constructor!
I am a new method!
Hi, I am a property!
I am the destructor!


Overwriting Inherited Properties and Methods

To change the behavior of an existing property or method in the new class, you can simply overwrite it by declaring it again in the new class:

class MyOtherClass extends Myclass
{
//define constructor again
public function __construct()
{
echo 'I am the new constructor!';
}
public function newMethod()
{
return 'I am a new method';
}
}


If we execute some code below:

$newobj = new MyOtherClass;
echo $newobj -> newMethod();
echo $newobj -> getProp();


Then the output will look like this:

I am the new constructor!
I am a new method!
Hi, I am a property!
I am the destructor!


Preserving Original Method Functionality While Overwriting Methods

To add new functionality to an inherited method while keeping the original method intact, you use the parent keyword with the scope resolution operator :::

class MyOtherClass extends Myclass
{
//define constructor again
public function __construct()
{
parent::__construct();// call the parent class's constructor
echo 'I am the new constructor!';
}
public function newMethod
{
return 'I am a new method';
}
}


We execute some code below:

$newobj = new MyOtherClass;
echo $newobj -> newMethod();
echo $newobj -> getProp();


The output will look like this:

I am the constructor!
I am the new constructor! 
I am a new method!
Hi, I am a property!
I am the destructor!


Assigning the Visibility of Properties and Methods

For added control over objects, properties and methods are assigned visibility. This controls how and from where properties and methods can be accessed. There are three visibility keywords: public, protected and private. How to use them that you can look like table below:

Keyword

Visibility

Public

The methods and properties can be accessed anywhere, both within the class and externally.

Protected

The methods and properties can only be accessed within the class itself or in descendant classes.

Private

The methods and properties can only be accessed within the class that defines it.


Static properties and methods

A method or property declared static can be accessed without first instantiating the class; you simply supply the class name, scope resolution operator ::, and the property or method name.

jQuery AJAX

  • AJAX = Asynchronous JavaScript and XML

  • AJAX is about loading data in the background and displaying it on the web page, without reloading the whole page.

  • jQuery provides several methods for AJAX functionality.

Now, We will look at the most important jQuery AJAX methods.

Method

Description

load()

Loads data from a server and puts the returned data into the selected element.

$.get()

Loads data from a server using an AJAX HTTP GET request

$.post()

Loads data from a server using an AJAX HTTP POST request

$.getJSON()

Loads JSON-encoded data from a server using a HTTP GET request

$.ajax()

Performs an async AJAX request


For a complete overview of all jQuery AJAX methods, you can visit at here.

Combining PHP with jQuery AJAX through an example

Assume that we have a list of people, each one will have the personal information as follows:

Name

Occupation

Image

Picasso

Painter


Ronaldo

Football Player


Picasso

Teacher


Madona

Singer




My first web page (PHP_AJAX.html) looks like this:

Image title


When I enter Picasso into the Name textbox and clicking the View button, the result will look like this:

Image title

Image title

And if I move the mouse pointer to an image, information about the image will occur, it can look like this:

Image title


Or

Image title


We can write some code as follows:

HTML code (HTML file, in this case that is PHP_AJAX.html)

<p id='bar'>Please enter name to view image! </p>
<p id='info'>info</p>
<form>
<p>Name:<input type='text' name='name'id ='name'/></p>
</form>
<button id='view' name ='view'>View</button>


Some styles

#info {color:black; border:5px blue solid; width:150px; height:100px;display:none;position:absolute;}


jQuery code (JS file, in this case that is PHP_AJAX.js)

$(document).ready(function(){
$('#view').click(function(){
var namevalue = $('#name').val(); 
$.post("PHP_AJAX.php",{name:namevalue}, function(data){
$('#bar').html(data);
$("img").hover(function(e){
var s1 = "<img src=";
var s2 = " width='110px' height='120px' />";
var srcval = s1.concat($(this).attr('src'), s2) ;
$.post("PHP_AJAX.php",{src:srcval}, function(data1){
 $('#info').css({top:e.clientY, left:e.clientX,backgroundColor:'yellow'})
                  .fadeIn()
                  .html(data1);
});}, function(){
 $('#info').fadeOut();
});
});//end post
});
});


PHP code (PHP file, in this case, that is PHP_AJAX.php)

class Person 
{
//some properties
private $name;
private $occupation;
private $image;
// constructor
public function __construct($nameval, $occuval, $imgval)
{
$this->name = $nameval;
$this->occupation = $occuval;
$this->image = "<img src=".$imgval." width='110px' height='120px' />";
}
// get name property
public function getname()
{
return $this->name;
}
// get occupation property
public function getoccupation()
{
return $this->occupation;
}
// get image property
public function getimage()
{
return $this->image;
}
}
$obj1 = new Person ("Picasso", "Painter", "pi1.jpg");
$obj2 = new Person ("Ronaldo", "Football Player", "ronaldo.jpg");
$obj3 = new Person ("Picasso", "Teacher", "pi2.jpg");
$obj4 = new Person ("Madonna", "Singer", "madonna.jpg");
//storing objects in an array
$arr = array($obj1,$obj2,$obj3,$obj4);
$count =0;
for ($i = 0; $i<4; $i++){
//if name already exist
if($arr[$i]->getname() == $_POST['name']){
echo "<p>Image of ".$arr[$i]->getname()."</p>";
echo "<p>".$arr[$i]->getimage()."</p>";
$count++;
}
if($arr[$i]->getimage() == $_POST['src'])
{
echo "<p>Name: ".$arr[$i]->getname()."</p>";
echo "<p> Occupation:".$arr[$i]->getoccupation()."</p>";
$count++;
}
}
//if name doesn't exist
if ($count == 0)
{
echo "<h3> NOT FOUND! </h3>";
}


My references

  • Pro PHP and jQuery, 2nd Edition (Jason Lengstorf and Keith Wald, Apress, 2016)

  • Learn PHP 7 (Steve Prettyman, Apress, 2016)

  • PHP.net

  • jquery.com

  • W3Schools.com


Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
web developement ,php ,jquery ,ajax

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}