Retrieve data from SQL without redirecting from the webpage using AJAX and PHP

php sql ajax

AJAX allows to retrieve data from the SQL databases without being redirected to the php file which gets the data from SQL

First let us insert a button to invoke the action and a div element to where we will insert the data


<button id="btn">
    Get Data from PHP file
</button>

<div id="data">
</div>

Now we will write a simple php code that will select some data from SQL


$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM table";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo $row["col_name"] . “<br>”;
    }
}

Now we will get this data and display in the webpage using AJAX

First include the AJAX library


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>

And then the AJAX code


$.ajax({
    url:'test.php',
    type:'GET',
    success:function(data){
        $("#data").html(data);
    }
});

The test.php is the file where we wrote the php code to retrieve the SQL data

Inorder to invoke the ajax call on button click,


$(document).ready(function(){
    $('#btn').click(function(){
        $("#data").html('Loading...');

        $.ajax({
            url:'test.php',
            type:'GET',
            success:function(data){
                $("#data").html(data);
            }
        });
    });
});

What the above code does is, when the button is clicked, the php file is called and output data from php file is inserted to the #data div.
Till the response is received a ‘loading’ message is displayed.

Leave a Reply

Your email address will not be published.