• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
seegatesite header

Seegatesite.com

Seegatesite.com - Programming Tutorial , Sharing , How and Learn Together

  • TOOLS
    • Bootstrap Navbar Online Generator
    • Customize Sidebar Menu Bootstrap 3
    • Bootstrap Demo
  • ADVERTISE
  • CATEGORIES
    • Android
    • Blogging Tips
    • Database
    • CSS
    • Info Gadget
    • Javascript
    • Linux
    • PHP
    • Various
    • WordPress
  • Q&A
  • PHP
  • JAVASCRIPT
  • JQUERY
  • ANGULAR
  • WORDPRESS
  • SEO
  • REACT
🏠 » Javascript » How To Use Select2 Remote AJAX With Example in JQuery, PHP And MySQL

How To Use Select2 Remote AJAX With Example in JQuery, PHP And MySQL

By Sigit Prasetya Nugroho ∙ September 11, 2017 ∙ Javascript, PHP ∙ Leave a Comment

Share : TwitterFacebookTelegramWhatsapp

Many of us are still confused how to implement the select2 JQuery plugin using Remote AJAX. Here I will share how to implement it using Jquery, PHP, and MySql. In addition, to beautify the view, select2 plugin can also facilitate the user in selecting the data displayed on the element select if it has a lot of data. Follow the tutorial select2 using the following ajax to apply to your application.

Table of Contents

  • 1 Surely did you already know “What is select2 JQuery Plugin” ?
  • 2 Tutorial Select2 Using AJAX With Example in Jquery, PHP, and MySQL.
    • 2.1 So my tutorials How To Use Select2 Remote AJAX With Example in JQuery, PHP, And MySQL 🙂

Surely did you already know “What is select2 JQuery Plugin” ?

Select2 is a jquery plugin to replace the default select box with a more beautiful view. Its use is quite easy, but to display remote ajax data on select2 initially is quite confusing (makes me confused especially). In general, the problem that is often encountered in remote ajax select2 is templateResult: formatRepo and click not working in select2 remote ajax option. From both of these problems, I will try to give the solution in this article.

Tutorial Select2 Using AJAX With Example in Jquery, PHP, and MySQL.

Note: Use Select2 Version 4.0.0 for the application to run properly

How To Use Select2 Remote AJAX With Example In JQuery, PHP And MySQL

1. Prepare the MySql database with “selectdb” name

Related Articles :

  • How To Make Web Push Notifications in PHP, JQuery , AJAX And Mysql
  • Web Applications as Desktop Flavor with Ajax Agent

2. Create a table with country name then fill in the code list and country name as shown below (to speed up the process, please download through my repository at https://github.com/seegatesite/country-db-mysql-list/blob/master/mysql_country_list.sql

3. I use PDO as PHP connection method with MySQL. Please create a class for database connections and classes to call MySql tables

dbconn.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
$dbuserx='root';
$dbpassx='123456';
class dbconn {
public $dblocal;
public function __construct()
{
 
}
public function initDBO()
{
global $dbuserx,$dbpassx;
try {
$this->dblocal = new PDO("mysql:host=localhost;dbname=selectdb;charset=latin1",$dbuserx,$dbpassx,array(PDO::ATTR_PERSISTENT => true));
$this->dblocal->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
die("Tidak dapat konek ke database");
}
}
}
?>

sql.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
class sql extends dbconn {
public function __construct()
{
$this->initDBO();
}
 
public function getAllCountry($term){
$term = '%'.$term.'%';
$db = $this->dblocal;
try
{
$stmt = $db->prepare("SELECT a.* FROM country a WHERE a.country_name LIKE :term OR  a.country_code LIKE :term ");
 
$stmt->bindParam("term",$term);
$stmt->execute();
$stat[0] = true;
$stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $stat;
}
catch(PDOException $ex)
{
$stat[0] = false;
$stat[1] = $ex->getMessage();
return $stat;
}
}
}

4. Create an ajax.php file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
header('Content-Type: application/json');
require_once ("dbconn.php");
require_once ("sql.php");
$term = trim(strip_tags($_GET['q']));
$sql = new sql();
$countrylist = $sql->getAllCountry($term);
$country = array();
$i = 0;
foreach ($countrylist[1] as $key) {
$countrylist[1][$i]['desc'] = $key['country_code'].' - '.$key['country_name'];;
$countrylist[1][$i]['id'] = $key['country_code'];
$i++;
}
$country['items'] = $countrylist[1];
echo json_encode($country);
?>

5. Create an index.php file in the selectdb project folder and fill in the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!DOCTYPE html>
<html>
<head>
<title>Tutorial selectDB remote ajax using jquery,php and mysql by seegatesite.com</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<h4>Tutorial selectDB remote ajax using jquery,php and mysql by <a href="https://seegatesite.com"></a>seegatesite.com</a></h4>
<div>
<select class="select2"></select>
</div>
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script type="text/javascript">
$(".select2").select2({
placeholder: "Search country here...",
width: '175px',
ajax: {
url: "ajax.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
          q: params.term, // search term
          page: params.page
      };
  },
  processResults: function (data, params) {
   params.page = params.page || 1;
   return {
   results: data.items,
   pagination: {
   more: (params.page * 30) < data.total_count
   }
   };
  },
  cache: false
},
// escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
 
function formatRepo (repo) {
if (repo.loading) return repo.text;
return repo.desc;
}
 
function formatRepoSelection (repo) {
return repo.desc || repo.text;
}
</script>
</body>
</html>

A brief description:

  • In order to select2 remote ajax to run properly, do not forget to create the format formatRepo and formatRepoSelection.
  • On the server side, json data must have an attribute named “id“

To download the source code of the project, please use the following download link. Please share this article using social media button below to open download link.

 

Select2 Remote AJAX With Example In JQuery, PHP And MySQL Project

Hopefully, this tutorial help solves your problem using remote2 ajax select2.

So my tutorials How To Use Select2 Remote AJAX With Example in JQuery, PHP, And MySQL 🙂

Another Javascript Related Post :

  • Adept Using Datatables Plugin In 10 Minutes For Beginners (Tutorial)
  • The Using Of Reactstrap And React-Table, Suitable For Beginners
  • Tutorial Create Simple Block UI Using React JS
  • How To Implement Login Page And Protected Route ReactJS
  • Complete Tutorial React Router Dom For Beginners (Easy-To-Understand)
  • The Right Way Understanding React Lifecycle For Beginners

Avatar for Sigit Prasetya Nugroho

About Sigit Prasetya Nugroho

This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Welcome to my Home,

Avatar for Sigit Prasetya NugrohoThis site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.



Popular Articles

Checked checkbox AdminLTE Bootstrap in Jquery

November 4, 2014 By Sigit Prasetya Nugroho 7 Comments

Simple create date format validation with jqueryUI

December 21, 2014 By Sigit Prasetya Nugroho Leave a Comment

Create Simple Progress Bar for Fake Online Generator with Jquery

January 10, 2015 By Sigit Prasetya Nugroho Leave a Comment

22+ Coolest Free Jquery Plugin For Premium Theme

October 3, 2015 By Sigit Prasetya Nugroho Leave a Comment

Easy Build Your Anti Copy Paste Plugin

October 6, 2015 By Sigit Prasetya Nugroho Leave a Comment

Popular Tags

adminlte (15) adsense (13) adsense tips (4) affiliate amazon (13) amazon (12) Android (8) angular (16) angular 4 (12) angular 5 (4) asin grabber (3) Bootstrap (27) codeigniter (5) create wordpress theme (5) crud (8) css (6) free wordpress theme (7) google adsense (4) imacros (4) increase traffic (6) jquery (34) laravel (10) laravel 5 (5) learn android (5) modal dialog (5) mysql (6) nodeJs (4) optimize seo (4) pdo (6) php (30) plugin (53) pos (7) Publisher Tips (5) react (3) Reactjs (7) SEO (37) theme (17) tutorial angular (5) tutorial angular 4 (6) tutorial javascript (10) tutorial javascript beginners (4) twitter (3) widget (3) wordpress (18) wordpress plugin (13) XMLRPC (5)




  • About
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

©2021 Seegatesite.com