---
description: https://www.nicesnippets.com/blog/jquery-select2-ajax-php-example
---

# \[SELECT2] lấy dữ liệu của wp, wordpress để thực hành (ok)

![](https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M1E4Gk2ppVKb4olmnun%2F-MQKk3q9ACVDvMA4ghbd%2F-MQKkIo_prr5JNA3s_iN%2FScreenshot_2.jpg?alt=media\&token=70582b82-a282-49e2-b392-738d13ffbc52)

![](https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M1E4Gk2ppVKb4olmnun%2F-MQKk3q9ACVDvMA4ghbd%2F-MQKkL6llQ9hes0nHSXB%2FScreenshot_3.jpg?alt=media\&token=274fcc8d-9a40-4e1e-aabf-14cadcf682c2)

![](https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M1E4Gk2ppVKb4olmnun%2F-MQKk3q9ACVDvMA4ghbd%2F-MQKkNaZrYWC07ntMUyb%2FScreenshot_4.jpg?alt=media\&token=f1e3c3a9-8364-497a-b546-fddb079a9342)

C:\xampp\htdocs\select2ajax\index.php

```
<html lang="en">
<head>
  <title>jquery select2 ajax php example</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" />
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body>
  <div class="row mt-5">
    <div class="col-md-6 offset-3 mt-5">
      <div class="card">
        <div class="card-header bg-info text-white">
          <h4>JQuery Select2 Ajax PHP Example - Nicesnippets.com</h4>
        </div>
        <div class="card-body" style="height: 280px;">
          <div>
            <select class="postName form-control" style="width:500px" name="postName"></select>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script type="text/javascript">
  $('.postName').select2({
    placeholder: 'Select an item',
    ajax: {
      url: 'autocompletePro.php',
      dataType: 'json',
      delay: 250,
      data: function(data) {
        return {
          searchTerm: data.term 
        };
      },
      processResults: function(response) {
        return {
          results: response
        };
      },
      cache: false
    }
  });
  </script>
</body>
</html>
```

C:\xampp\htdocs\select2ajax\autocompletePro.php

```
<?php
$mysqli = new mysqli("localhost", "root", "", "wordpress");
if (!isset($_GET['searchTerm'])) {
  $json = [];
} else {
  $search = $_GET['searchTerm'];
  $sql    = "SELECT wp_posts.ID, wp_posts.post_title FROM wp_posts WHERE post_status='publish' AND post_title LIKE '%" . $search . "%' LIMIT 10";
  $result = $mysqli->query($sql);
  $json   = [];
  while ($row = $result->fetch_assoc()) {
    $json[] = ['id' => $row['ID'], 'text' => $row['post_title']];
  }
}
echo json_encode($json);
?>
```

