Upload an Image using Ajax in PHP

Prerequisite: Basic understanding of HTML, CSS, PHP and MySQL.


In this project:

  • We will create a HTML textbox.

  • On pressing a key, ajax based search is performed with the help of jQuery.

  • User will enter a Country Name and the results will be fetched from the MySQL Database.

  • CSS styling will be done to give it a look alike SELECT BOX in HTML.


index.php ⬇

<!DOCTYPE html>
<html>
    <head>
        <title>AJAX SEARCH</title>
        <style>        
            .main{width: 200px; position: relative; display: inline-block;}        
            #result{position: absolute; z-index: 1; top: 30px; left: 0; }        
            #result p{padding: 7px; border: 1px solid #CCC; border-top: none; cursor: pointer; margin: 0;}
            #result p:hover{background: #f3f3; cursor: pointer}        
            #searchBox{height: 30px; padding: 7px; border: 1px solid #CCC;}
            #searchBox, #result{width: 100%; box-sizing: border-box;}
            .error{cursor: none !important}
        </style>
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    </head>
    <body>
        <div class="main">
            <input type="text" id="searchBox" placeholder="Search Country" autocomplete="off"/>
            <div id="result"></div>
        </div>
    </body>
    <script>
        $(document).ready(function(){
            $('#searchBox').keyup(function(){
                var value = $(this).val();
                $.ajax({
                    url: 'process.php',
                    type: 'POST',
                    data: {text:value},
                    success: function(data) {
                        $("#result").html(data);
                    },
                    error: function(){
                        $("#result").empty();
                    }
                }); 
            });  
            $(document).on("click", "#result p", function(){
                var value = $(this).text();
                $(".main").find('input[type="text"]').val(value);
                $("#result").empty();
            });
        });
    </script>
</html> 

Start the localhost services and run index.php in your web browser to get the following output:

While searching the output will be:

Explanation of index.php

  1. HTML Textbox is created with ID “searchBox”. Attribute autocomplete is set to “off”, so that browser should not display its options to fill in the box.
    <input type="text" id="searchBox" placeholder="Search Country" autocomplete="off"/>
  2. A <div> is created with ID “result” which will contain the list of countries fetched from the database with the help of AJAX.

    <div id="result"></div>
    In <head> tag <div  id=”result”> is provided the css to position it right below the textbox.
    #result{ position: absolute; z-index: 1; top: 30px; left: 0; }
  3. To use jQuery Functions jQuery file is included in the <head> tag. You can use either an online link or download it from the jQuery.com and can include in the page accordingly.
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  4. All the jQuery functions are put inside the document ready function to make sure that all the events are executed after the DOM gets ready for it.
    $(document).ready(function(){
       …
    });
  5. Search is performed on keyup event using jQuery. “#searchBox” ID name is used to define keyup method. Current value is stored in value variable. AJAX is further defined to fetch the countries name from database.
    $('#searchBox').keyup(function(){
        var value = $(this).val();
        
          // Ajax method…
    
    });
  6. jQuery Ajax method defines the following parameters.

    url:

    url parameter specifies the url you want to request.

    type:

    HTTP GET and POST are used to request the data from the server.

    data:

    It specifies the data to send with the request.

    success:

    Success is invoked upon successful completion of Ajax request.

    error:

    Error is invoked upon the failure of Ajax request.

    $.ajax({
       url: 'process.php',
       type: 'POST',
       data: {text : value},
       success: function(data) {
                   $("#result").html(data);
                },
       error: function(){
                 $("#result").empty();
              }
    });

    - Current value of searchBox is sent to process.php using HTTP POST method.

    - On successful fetching of countries list, the result is assigned to <div id=”result”></div> block.

    - On error, <div id=”result”></div> block is emptied.

  7. When you click on any particular country being listed, the following jQuery event will be fired.
    $(document).on("click", "#result p", function(){
       // Code Here…
    });
  8. Code that gets executed, when u click the particular country is:
    var value = $(this).text();
    $(".main").find('input[type="text"]').val(value);
    $("#result").empty();

Above code will put the selected value into the textbox and the dropdown list of countries is emptied.

Request through Ajax is sent to the process.php file and the corresponding file is discussed below:


process.php ⬇

<?php
include "includes/conn.php";
if(isset($_POST["text"])){
    $text = trim($_POST['text']);
    $sql = "SELECT * FROM countries WHERE name LIKE '".$text."%'";
    $result = mysqli_query($con, $sql);
    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
            echo "<p>" . $row["name"] . "</p>";
        }
    }else{
        echo "<p class='error'>No Result</p>";
    }
}
?>

Explanation of process.php

  1. Connection file conn.php is included using PHP file include method. It connects to the “db” database.
    include "includes/conn.php";
  2. Below we have mentioned the code for conn.php file:
    <?php
        $con = new mysqli("localhost","root","","db");
        if ($con->connect_errno) {
            echo "Failed to connect to MySQL: ".$con->connect_error;
            exit();
        }
    ?>
    If there is any error in connecting to the database, error message is displayed on the screen and exit method is called to stop further execution of the php code. Otherwise, connection is successfully built and further execution is proceeded.
  3. If text POST variable is set then the control comes inside the if() block.
    if(isset($_POST["text"])){
    	// SOME CODE HERE…
    }
    You can write your code of instructions inside the if block, that you want to perform according to the requirement. In our case, we will fetch the list of countries from the database and will display them.
  4. A table named as countries is created in the MySQL Database db to which we are connected. Listed of countries is also inserted or imported in it according to our requirement. For example: the table we have created is as shown below:
  5. Countries are fetched using mysql SELECT STATEMENT. If number of rows is greater than 0, then the resultant array is iterated using while loop. Otherwise, “No Result” message is displayed.
    $sql = "SELECT * FROM countries WHERE name LIKE '".$text."%'";
    $result = mysqli_query($con, $sql);
    if(mysqli_num_rows($result) > 0){
       while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
            echo "<p>" . $row["name"] . "</p>";
       }
    }else{
       echo "<p class='error'>No Result</p>";
    }
  6. The statement:
    $sql = "SELECT * FROM countries WHERE name LIKE '".$text."%'";
    Defines to select the rows from countries table whose name starts from the value that is stored in $text variable for example: 
    $text = A
    All the rows whose name starts from A will be fetched from the table and will be listed.

Summary

In this project, we have learned ajax based Search in HTML textbox. We have applied the search on keyup event. The data is fetched from the database. We have fetched the list of countries using jQuery Ajax Method. Similarly, you can use the same concept or process to apply search on your website by manipulating the things your way.

Always remember to include jQuery file in the head tag of your document, before you are going to use anykind of jQuery method or plugin.

Help Us to Improve our content

Let's Talk
Go back to Previous Course