Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] jQuery AJAX AutoComplete with Create-New Feature

#1
[Tut] jQuery AJAX AutoComplete with Create-New Feature

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2023/08/jquery-ajax-autocomplete-with-create-new-feature.jpg" width="550" height="367" title="" alt="" /></div><div><div class="modified-on" readability="7.0697674418605"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on July 25th, 2023.</div>
<p>Autocomplete textbox feature shows the suggestion list when the user enters a value. The suggestions are, in a way, related to the entered keyword.</p>
<p>For example, when typing in a Google search box, it displays auto-suggested keywords in a dropdown.</p>
<p><a class="demo" href="https://phppot.com/demo/jquery-ajax-autocomplete-create-new/">View Demo</a></p>
<p>This tutorial will show how to add this feature to a website. The code uses the <strong>JQuery library</strong> with PHP and MySQL to show <span>dynamic auto-suggestions on entering the search key</span>.</p>
<p>It allows typing the start letter of the country name to get suggested with the list of country names accordingly. See the linked code for <a href="https://phppot.com/jquery/jquery-autocomplete-with-xml-data-source/">enabling autocomplete using the jQuery-Ui library</a>.</p>
<p><strong>The specialty of this example is that it also allows adding a new option that is not present in the list of suggestions.</strong></p>
<p><img decoding="async" loading="lazy" class="alignnone size-large wp-image-20871" src="https://phppot.com/wp-content/uploads/2023/05/jquery-ajax-autocomplete-create-new-550x367.jpg" alt="jquery ajax autocomplete create new" width="550" height="367" srcset="https://phppot.com/wp-content/uploads/2023/05/jquery-ajax-autocomplete-create-new-550x367.jpg 550w, https://phppot.com/wp-content/uploads/20...00x200.jpg 300w, https://phppot.com/wp-content/uploads/20...68x512.jpg 768w, https://phppot.com/wp-content/uploads/20...te-new.jpg 1200w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p>On key-up, a function executes the Jquery Autocomplete script. It reads suggestions based on entered value. This event handler is an AJAX function. It requests PHP for the list of related countries from the database.</p>
<p>When submitting a new country, the PHP will update the database. Then, this new option will come from the next time onwards.</p>
<h2>Steps to have a autocomplete field with a create-new option</h2>
<ol>
<li>Create HTML with a autocomplete field.</li>
<li>Integrate jQuery library and initialize autocomplete for the field.</li>
<li>Create an external data source (database here) for displaying suggestions.</li>
<li>Fetch the autocomplete suggestions from the database using PHP.</li>
<li>Insert a newly created option into the database.</li>
</ol>
<h2>1. Create HTML with a autocomplete field</h2>
<p>This HTML is for creating an autocomplete search field in a form. It is a suggestion box that displays dynamic auto-suggestions via AJAX.</p>
<p>On the key-up event of this input field, the <a href="https://phppot.com/php/ajax-programming-with-php/">AJAX script sends the request to the PHP</a>.&nbsp; The PHP search performs database fetch about the entered keyword.</p>
<p>This HTML form also posts data not chosen from the suggestions. This feature allows adding new options to the source of the search suggestions.</p>
<p class="code-heading">index.php</p>
<pre class="prettyprint"><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt;
&lt;link rel="stylesheet" type="text/css" href="style.css" /&gt;
&lt;/head&gt;
&lt;body&gt; &lt;div class="outer-container"&gt; &lt;div class="row"&gt; &lt;form id="addCountryForm" autocomplete="off" method="post"&gt; &lt;div Class="input-row"&gt; &lt;label for="countryName"&gt;Country Name:&lt;/label&gt;&lt;input type="text" id="countryName" name="countryName" required&gt; &lt;div id="countryList"&gt;&lt;/div&gt; &lt;/div&gt; &lt;input type="submit" class="submit-btn" value="Save Country"&gt; &lt;div id="message"&gt;&lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h2>2. Integrate the jQuery library and initialize autocomplete for the field</h2>
<p>This code uses AJAX to show the dynamic autocomplete dropdown. This script sends the user input to the PHP endpoint.</p>
<p>In the success callback, the AJAX script captures the response and updates the auto-suggestions in the UI. This happens on the key-up event.</p>
<p>The suggested options are selectable. The input box will be filled with the chosen option on clicking each option.</p>
<p>Then, the <a href="https://phppot.com/php/access-form-data-from-php/">form input is posted to the PHP</a> via AJAX on the form-submit event.</p>
<p>This <a href="https://phppot.com/jquery/jquery-fading-methods/">jQuery script shows the fade-in fade-out effect</a> to display and hide the autocomplete dropdown in the UI.</p>
<p class="code-heading">index.php(ajax script)</p>
<pre class="prettyprint"><code class="language-javascript">$(document).ready(function() { $('#countryName').keyup(function() { var query = $(this).val(); if (query != '') { $.ajax({ url: 'searchCountry.php', type: 'POST', data: { query: query }, success: function(response) { $('#countryList').fadeIn(); $('#countryList').html(response); } }); } else { $('#countryList').fadeOut(); $('#countryList').html(''); } }); $(document).on('click', 'li', function() { $('#countryName').val($(this).text()); $('#countryList').fadeOut(); }); $('#addCountryForm').submit(function(event) { event.preventDefault(); var countryName = $('#countryName').val(); $.ajax({ type: 'POST', url: 'addCountry.php', data: { countryName: countryName }, success: function(response) { $('#countryList').hide(); $('#message').html(response).show(); } }); });
});
</code></pre>
<h2>3. Create an external data source (database here) for displaying suggestions</h2>
<p>Import this SQL to create to database structure to save the autocomplete suggestions. It has some initial data that helps to understand the autocomplete code during the execution.</p>
<p class="code-heading">database.sql</p>
<pre class="prettyprint"><code class="language-sql">CREATE TABLE IF NOT EXISTS `democountries` (
`id` int NOT NULL AUTO_INCREMENT, `countryname` varchar(255) NOT NULL, PRIMARY KEY (id)
); INSERT INTO `democountries` (`countryname`) VALUES
('Afghanistan'),
('Albania'),
('Bahamas'),
('Bahrain'),
('Cambodia'),
('Cameroon'),
('Denmark'),
('Djibouti'),
('East Timor'),
('Ecuador'),
('Falkland Islands (Malvinas)'),
('Faroe Islands'),
('Gabon'),
('Gambia'),
('Haiti'),
('Heard and Mc Donald Islands'),
('Iceland'),
('India'),
('Jamaica'),
('Japan'),
('Kenya'),
('Kiribati'),
('Lao Peoples Democratic Republic'),
('Latvia'),
('Macau'),
('Macedonia');
</code></pre>
<h2>4. Fetch the autocomplete suggestions from the database using PHP</h2>
<p>The PHP code prepares the MySQL select query to fetch suggestions based on the search keyword.</p>
<p>It fetches records by searching for the country names that start with the keyword sent via AJAX.</p>
<p>This endpoint builds the HTML lists of autocomplete suggestions. This HTML response is used to update the UI to render relevant suggestions.</p>
<p class="code-heading">searchCountry.php</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
$conn = new mysqli('localhost', 'root', '', 'db_autocomplete'); if (isset($_POST['query'])) { $query = "{$_POST['query']}%"; $stmt = $conn-&gt;prepare("SELECT countryname FROM democountries WHERE countryname LIKE ? ORDER BY countryname ASC"); $stmt-&gt;bind_param("s", $query); $stmt-&gt;execute(); $result = $stmt-&gt;get_result(); if ($result-&gt;num_rows &gt; 0) { while ($row = $result-&gt;fetch_assoc()) { echo '&lt;li&gt;' . $row['countryname'] . '&lt;/li&gt;'; } }
}
?&gt;
</code></pre>
<h2>5. Insert a newly created option into the database</h2>
<p>The expected value is not in the database if no result is found for the entered keyword. This code allows you to update the existing source with your new option.</p>
<p>The form submits action calls the below PHP script. It checks if the country name sent by the AJAX form submit is existed in the database. If not, it inserts that new country name.</p>
<p>After this insert, the newly added item can be seen in the suggestion box in the subsequent autocomplete search.</p>
<p class="code-heading">addCountry.php</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
$conn = new mysqli('localhost', 'root', '', 'db_autocomplete'); if (isset($_POST['countryName'])) { $countryName = "{$_POST['countryName']}"; $stmt = $conn-&gt;prepare("SELECT * FROM democountries WHERE countryname =?"); $stmt-&gt;bind_param("s", $countryName); $stmt-&gt;execute(); $result = $stmt-&gt;get_result(); if ($result-&gt;num_rows &gt; 0) { echo '&lt;p&gt;Country Selected: ' . $countryName . '&lt;/p&gt;'; } else { $stmt = $conn-&gt;prepare("INSERT INTO democountries (countryname) VALUES (?)"); $stmt-&gt;bind_param("s", $countryName); $stmt-&gt;execute(); $result = $stmt-&gt;insert_id; if (! empty($result)) { echo $countryName . ' saved to the country database.&lt;/br&gt;'; } else { echo '&lt;p&gt;Error adding ' . $countryName . ' to the database: ' . mysqli_error($conn) . '&lt;/p&gt;'; } }
}
?&gt;
</code></pre>
<h2>Different libraries providing Autocomplete feature</h2>
<p>In this script, I give a custom autocomplete solution. But, many libraries are available to provide advanced feature-packed autocomplete util for your application.</p>
<ol>
<li>The <a href="https://jqueryui.com/autocomplete/" target="_blank" rel="noopener">jQueryUI provides autocomplete feature</a> to enable an HTML field.</li>
<li>One more library is the <a href="https://github.com/fitiskin/jquery-autocompleter" target="_blank" rel="noopener">jQuery Autocompleter plugin</a> that captures more data from the options to be chosen.</li>
</ol>
<p>These libraries give additional features associated with the autocomplete solution.</p>
<ol>
<li>It allows to select single and multiple values from the autocomplete dropdown.</li>
<li>It reads the option index or the key-value pair of the chosen item from the list.</li>
</ol>
<h2>Advantages of autocomplete</h2>
<p>Most of us experience the advantages of the autocomplete feature. But, this list is to mention the pros of this must-needed UI feature intensely.</p>
<ol>
<li>It’s one of the top time-saving UI utilities that saves users the effort of typing the full option.</li>
<li>It’s easy to search and get your results by shortlisting and narrowing. This is the same as how <a href="https://phppot.com/php/live-search-in-php-and-mysql-with-ajax/">a search feature of a data table</a> narrows down the result set.</li>
<li>It helps to get relevant searches.</li>
</ol>
<p><a class="demo" href="https://phppot.com/demo/jquery-ajax-autocomplete-create-new/">View Demo</a> <a class="download" href="https://phppot.com/downloads/jquery/jquery-ajax-autocomplete-create-new.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/jquery/jquery-ajax-autocomplete/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2023/05/...w-feature/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016