DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Shallow and Deep Copies in JavaScript: What’s the Difference?
  • What Is Ant, Really?
  • How to Call Rest API by Using jQuery AJAX in Spring Boot? [Video]
  • Accessing Payload, Variables and Environment Properties in Kumologica

Trending

  • Docker Base Images Demystified: A Practical Guide
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • Top Book Picks for Site Reliability Engineers
  1. DZone
  2. Coding
  3. Frameworks
  4. Object-Oriented PHP and jQuery AJAX

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.

By 
Ngoc Minh Tran user avatar
Ngoc Minh Tran
DZone Core CORE ·
May. 17, 16 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
33.7K Views

Join the DZone community and get the full member experience.

Join For Free

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


AJAX PHP JQuery Property (programming) Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Shallow and Deep Copies in JavaScript: What’s the Difference?
  • What Is Ant, Really?
  • How to Call Rest API by Using jQuery AJAX in Spring Boot? [Video]
  • Accessing Payload, Variables and Environment Properties in Kumologica

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!