Get data from database and display without refreshing the web page
Ajax...and jQuery..They are like twin brothers! When they get together, they are awesome guys.. Are you still new to Ajax? This is the best chance to learn how to send an ajax request and get the result from database as I did in one of my previous articles. Today I'm going to show you how to get the data of a particular record from database and display them without a page refresh. Here I will use Codeigniter as PHP framework, Ajax, jQuery and MYSQL to implement the functionality. Now you can watch a short demo video clip based on application that I'm going to implement.
...Wait for some time to explain the Ajax and jQuery part...
Little long article due to its content
Be patient Guys!
As usual you need to download Codeigniter and make a project folder to start this task..Then you need to prepare the essential configurations for a Codeigniter project. If you are not aware of it, vist the below link to get an idea.
Configurations
Project folder => FecthAjax
Base URL => $config['base_url'] = 'http://localhost/FecthAjax/
Database name => fetch_ajax
Database table name => phones
Autoload libraries => database
Autoload helpers => form , url
Default Controller => Fetch
Create a database called fetch_ajax and import the SQL file I have included in my GitHub repository called fetch_ajax.sql.
For this we need 3 view files. Create them in application/views folder. In my case, they are named as;
Now you should decide, which data should fetched from database. What are they?- mobile_phones.php - Display all mobile phones stored in database
- phone.php - Display the data of a selected phone
- compare_phones.php - Display the compare results for a phone
- For mobile_phones.php - names, images and prices of all phones(can get all data)
- For phone.php - all the data of a selected phone, according to ID
- For compare_phones.php - all data of a phone selected according to its name stored in database from a dropdown list
So, I will first create the model and prepare database with queries to fetch this data. My model;
Fetch_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Fetch_model extends CI_Model {
// fetch all data of all phones for first page
public function get_phones()
{
$this->db->select('*');
$this->db->order_by('price','DESC');
$query = $this->db->get('phones');
return $query->result();
}
//fetch data for a phone using its ID
public function get_a_phone($phone_id)
{
$this->db->where('phone_id',$phone_id);
$query = $this->db->get_where('phones', array('phone_id' => $phone_id));
return $query->row();
}
// fetch data according to the phone name selected from dropdown
public function get_com_phone($com)
{
$this->db->select('*');
$this->db->where('name',$com);
$res = $this->db->get('phones');
return $res;
}
}
You are now ready with queries. Now You have to create the controller to load views and particular data fetched through the model, for each page. All the explanations are given as comments. Read them to understand the process...
Fetch.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Fetch extends CI_Controller {
public function __construct()
{
parent::__construct();
// load model for each function. Don't need to load in in every function.can SKIP that step.
$this->load->model('Fetch_model');
}
public function index()
{
// assign the data of all phones to an array
$data['allphones'] = $this->Fetch_model->get_phones();
// load the view - mobile_phones.php
$this->load->view('mobile_phones',$data);
}
public function phone($phone_id)
{
// assign the data fetched according to an ID to an array
$data['row'] = $this->Fetch_model->get_a_phone($phone_id);
// load the view - phone.php
$this->load->view('phone',$data);
}
public function compare_phones($phone_id)
{
// assign the data fetched according to an ID to an array
$data['phone'] = $this->Fetch_model->get_a_phone($phone_id);
// assign the data of all phones to an array
$data['allphones'] = $this->Fetch_model->get_phones();
// load the view - compare_phones.php
$this->load->view('compare_phones',$data);
}
public function get_com_phone()
{
// get the entered input through POST method
$com = $this->input->post('phone2');
// check the selected input is not empty OR it is available on page
if(isset($com) and !empty($com)){
// assign the data of a phone to an array that is selected using it's name in DB
$records = $this->Fetch_model->get_com_phone($com);
// begin the printing the fetched phone data for comparing. output is an array
$output = '';
// start a foreach loop to print the rows for a phone in DB
foreach($records->result_array() as $row){
// concatenate the result to empty output variable
$output .= '<div class="card" style="width: 25rem;border: 1px solid; border-color: black;"><br>
<center><div style="width:60%;height:80%;"><img style="width:40%;height:60%;"
src="'.base_url().'assets/images/phones/'.$row['image1'].'"></div></center>
<div class="card-body">
<h5 class="card-title text-center">'.$row["name"].'</h5><br>
<ul class="list-group">
<li class="list-group-item"><b>RAM</b> : '.$row["ram"].'</li>
<li class="list-group-item"><b>Internal Memory</b> : '.$row['internal'].'</li>
<li class="list-group-item"><b>Back Camera</b> : '.$row['cam_primary'].'</li>
<li class="list-group-item"><b>Front Camera</b> : '.$row['cam_secondary'].'</li>
<li class="list-group-item"><b>Display Size</b> : '.$row['display_size'].'</li>';
}
$output .= '</ul"></div></div>';
// finally print the output to the view
echo $output;
}
}
}
Now you need to pass the data assigned in variables, to the view. Then you can display them in the views. Next step is creating views.
mobile_phones.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ajax Fetch Data</title>
<!-- load bootstrap CSS stored in assests/css folder -->
<link rel="stylesheet" href="<?php echo base_url() ?>assets/css/bootstrap.css">
<style type="text/css">
#phone-img {
width: 200px;
height: 200px;
margin: auto;
padding: 20px;
}
</style>
</head>
<body>
<main role="main">
<div class="container">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12" style="margin-top: 40px">
<div id="product_cards">
<div class="row">
<!-- start printing the data of allphones using a foreach loop -->
<?php foreach ($allphones as $row) : ?>
<!-- This part within the for loop will be printed again and again with the data rows in the database -->
<div class="col-lg-3 col-md-12 col-sm-12" id="phone-card">
<div class="card" style="margin-bottom: 20px;">
<img class="card-img-top" id="phone-img" src="<?php echo base_url();?>assets/images/phones/<?php echo $row->image1; ?>" alt="Card image cap">
<div class="card-body">
<!-- ID of each phone should be passed via the anchor link to get the relevant phone data from the model function called get_a_phone() -->
<a style="font-size: 16px;" href="<?php echo base_url();?>fetch/phone/<?php echo $row->phone_id;?>"><p class="card-title text-center"><?php echo $row->name; ?></p></a>
<center>
<span class="badge badge-info"><h6 class="text-center phone-price">Rs : <?php echo $row->price; ?></h6></span>
</center>
<br>
</div>
</div>
</div>
<?php endforeach; ?>
<!-- end foreach loop -->
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<!-- load jQuery stored in assests/js folder -->
<script src="<?php echo base_url() ?>assets/js/jquery-3.2.1.min.js"></script>
<!-- load bootstrap JS stored in assests/js folder -->
<script src="<?php echo base_url() ?>assets/js/bootstrap.js"></script>
</body>
</html>
If you have done with me, you will get this view.
When you select a phone by its name, the next page should be loaded with its content. That's why I took the ID of the phone to get the data unique for each phone. Now it's time to create the view for a single phone.
phone.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ajax Fetch Data</title>
<link rel="stylesheet" href="<?php echo base_url() ?>assets/css/bootstrap.css">
<link rel="stylesheet" href="<?php echo base_url() ?>assets/font-awesome/css/font-awesome.min.css">
<style type="text/css">
#phone-display {
width: 350px;
height: 400px;
margin: auto;
}
</style>
</head>
<body>
<main role="main" class="container" style="margin-bottom: 60px;">
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12">
<!-- print the data in left side container -->
<div class="col-lg-4 col-md-12" style="margin-top: 60px;float: left;">
<div id="spec-brief">
<img src="<?php echo base_url();?>assets/images/phones/<?php echo $row->image1; ?>" id="phone-display">
<div><br>
<ul class="list-group">
<li class="list-group-item text-center"><b style="font-size: 24px;color: #0C5997;"> Price : Rs. <?php echo $row->price; ?></b></li>
<li class="list-group-item"><a style="text-decoration: none;font-family: 'Oswald', sans-serif;" href="<?php echo base_url(); ?>fetch/compare_phones/<?php echo $row->phone_id; ?>"><button type="button" class="btn btn-info btn-block">Compare</button></a></li>
<li class="list-group-item"><a style="text-decoration: none;font-family: 'Oswald', sans-serif;" href="<?php echo base_url(); ?>fetch"><button type="button" class="btn btn-outline-danger btn-block">Back</button></a></li>
</ul>
</div>
</div>
</div>
<!-- print the data in right side container -->
<div class="col-lg-8 col-md-12 col-sm-12" style="float: right;margin-top: 60px">
<!-- print the main features -->
<h3 id="phone-name"><?php echo $row->name; ?></h3>
<br>
<div class="row">
<div class="col-lg-3 col-md-12 col-sm-12" id="prod-card">
<div class="card">
<div class="card-body">
<center><i class="fa fa-camera fa-3x" aria-hidden="true"></i></center><br>
<h5 class="card-title text-center">CAMERA</h5><br>
<h6 class="card-title text-center"><?php echo $row->cam_primary; ?></h6>
</div>
</div>
</div>
<div class="col-lg-3 col-md-12 col-sm-12" id="prod-card">
<div class="card">
<div class="card-body">
<center><i class="fa fa-bars fa-3x" aria-hidden="true"></i></center><br>
<h5 class="card-title text-center">RAM</h5><br>
<h6 class="card-title text-center"><?php echo $row->ram; ?></h6>
</div>
</div>
</div>
<div class="col-lg-3 col-md-12 col-sm-12" id="prod-card">
<div class="card">
<div class="card-body">
<center><i class="fa fa-battery-half fa-3x" aria-hidden="true"></i></center><br>
<h5 class="card-title text-center">BATTERY</h5><br>
<h6 class="card-title text-center"><?php echo $row->battery; ?></h6>
</div>
</div>
</div>
<div class="col-lg-3 col-md-12 col-sm-12" id="prod-card">
<div class="card">
<div class="card-body">
<center><i class="fa fa-desktop fa-3x" aria-hidden="true"></i></center><br>
<h5 class="card-title text-center">DISPLAY</h5><br>
<h6 class="card-title text-center"><?php echo $row->display_size; ?></h6>
</div>
</div>
</div>
</div>
<br>
<!-- print the other features using a table -->
<table class="table table-bordered">
<tr>
<th>Launch</th>
<td>Announced Time</td>
<td><?php echo $row->released_time; ?></td>
</tr>
<tr>
<th rowspan="2">Body</th>
<td>Dimensions</td>
<td><?php echo $row->dimension; ?></td>
</tr>
<tr>
<td>SIM</td>
<td><?php echo $row->sim; ?></td>
</tr>
<tr>
<th rowspan="3">Display</th>
<td>Type</td>
<td><?php echo $row->display_type; ?></td>
</tr>
<tr>
<td>Size</td>
<td><?php echo $row->display_size; ?></td>
</tr>
<tr>
<td>Resolution</td>
<td><?php echo $row->resolution; ?></td>
</tr>
<tr>
<th rowspan="4">Platform</th>
<td>OS</td>
<td><?php echo $row->os; ?></td>
</tr>
<tr>
<td>Chipset</td>
<td><?php echo $row->chipset; ?></td>
</tr>
<tr>
<td>CPU</td>
<td><?php echo $row->cpu; ?></td>
</tr>
<tr>
<td>GPU</td>
<td><?php echo $row->gpu; ?></td>
</tr>
<tr>
<th rowspan="2">Memory</th>
<td>Card Slot</td>
<td><?php echo $row->cardslot; ?></td>
</tr>
<tr>
<td>Internal</td>
<td><?php echo $row->internal; ?></td>
</tr>
<tr>
<th rowspan="2">Camera</th>
<td>Primary</td>
<td><?php echo $row->cam_primary; ?></td>
</tr>
<tr>
<td>Secondary</td>
<td><?php echo $row->cam_secondary; ?></td>
</tr>
<tr>
<th>Battery</th>
<td>Capacity</td>
<td><?php echo $row->battery; ?></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</main>
<script src="<?php echo base_url() ?>assets/js/jquery-3.2.1.min.js"></script>
<script src="<?php echo base_url() ?>assets/js/bootstrap.js"></script>
</body>
</html>
As I mentioned before, if you came here with me, you will have this kind of view for a phone.
OK.........Now you have come to the most important part of this article.
Create the remaining view file.
compare_phones.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ajax Fetch Data</title>
<link rel="stylesheet" href="<?php echo base_url() ?>assets/css/bootstrap.css">
</head>
<body>
<div class="container" style="margin-top: 60px;">
<div class="row">
<div class="col-lg-12 col-md-12">
<h2 class="text-center">Compare the Two phones</h2><br><br>
<div class="row">
<div class="col-lg-6 col-md-12">
<!-- dropdown to select the comparing phone -->
<select name="phone2" id="phone2" class="form-control">
<option selected disabled>Choose the phone you want to compare with this phone</option>
<!-- print all the names of the phones stored in DB using get_phones() model function -->
<?php foreach ($allphones as $row) : ?>
<option><?php echo $row->name; ?></option>
<?php endforeach; ?>
</select>
</div>
<!-- button that gets the result from an AJAX request -->
<a name="compare" class="btn btn-primary compare_phn" style="margin-right: 20px;">COMPARE</a>
</div>
<div class="col-lg-6 col-md-12"></div>
</div>
</div>
<!-- print some main features of the selected phone already from firat page.. -->
<div class="col-lg-6 col-md-12" style="margin-top: 40px;float: left;">
<div class="card" style="width: 25rem;border: 1px solid; border-color: black;"><br>
<center><div style="width:60%;height:80%;"><img style="width:40%;height:60%;" src="<?php echo base_url();?>assets/images/phones/<?php echo $phone->image1; ?>"></div></center>
<div class="card-body">
<h5 class="card-title text-center"><?php echo $phone->name; ?></h5><br>
<ul class="list-group">
<li class="list-group-item"><b>RAM</b> : <?php echo $phone->ram; ?></li>
<li class="list-group-item"><b>Internal Memory</b> : <?php echo $phone->internal; ?></li>
<li class="list-group-item"><b>Back Camera</b> : <?php echo $phone->cam_primary; ?></li>
<li class="list-group-item"><b>Front Camera</b> : <?php echo $phone->cam_secondary; ?></li>
<li class="list-group-item"><b>Display Size</b> : <?php echo $phone->display_size; ?></li>
</ul>
</div>
</div>
</div>
<!-- area to print the comparing features of the selected phone through the drop down via an AJAX request -->
<div class="col-lg-6 col-md-12" style="margin-top: 40px;float:right">
<div id="com_result"></div>
</div>
<!-- end the comparing area -->
</div>
</div>
</div>
</div>
<script src="<?php echo base_url() ?>assets/js/jquery-3.2.1.min.js"></script>
<script src="<?php echo base_url() ?>assets/js/bootstrap.js"></script>
<script>
// wait to start jQuery after page is fully loaded
$(document).ready(function(){
// get the name of the phone from dropdown via the jQuery click function
$(document).on('click', '.compare_phn', function(){
// store the phone name in a variable called $com
var com = $('#phone2').val();
// start AJAX request
$.ajax({
// URL for the controller function that fetches and prints the data of the selected phone from dropdown list
url : "<?php echo base_url() ?>Fetch/get_com_phone",
// method of getting data is POST..not GET..
method : "POST",
// Data got through input are sent to the server
data: {phone2: com},
// if data is fetched successfully, this function will be executed
success:function(data){
// print the recieved data from server in the section called com_result in compare_phones view file
$('#com_result').html(data);
},
// type of the data sent and received
dataType: "text"
});
// end of AJAX request
});
});
// end jQuery
</script>
</body>
</html>
Now you have completed the application. I explained each and every step of Ajax and jQuery part with my best effort that I can explain to you. I know this a bit long article..But I only included the important things..The importance of this application is fetching and displaying data got from database, without a page refresh! That is the power of Ajax and jQuery... So, I have to stop for today..Keep awaited for the next article!
If you have any question, please drop a comment below the article.
Do't forget to hit LIKE button for my FB page.. :D
Thank You guys...!
4 Comments
ReplyDeleteWeb hosting service is a fee that you have to pay to rent a space on very high speed server, so that your website would be available to the public. PkDomain is dedicated to provide the best, most reliable web hosting in Pakistan. Give your business an online presence with us today at www.pkdomain.com.pk.
Great blog! I appreciate the efforts you made when writing this article. I hope the best work from you in the future is good. I want to thank you for this site! Thank you for sharing. PLease visit site picbear
ReplyDeleteThank you very much!
DeleteWeb hosting can be a difficult subject for someone new to learn. Several areas of web hosting are identified and explained with https://apachis.com/differentiate-shared-hosting-vs-wordpress-hosting/, as well as different types of hosting.
ReplyDelete